diff --git a/.gitignore b/.gitignore index 442f8578a..b41282457 100644 --- a/.gitignore +++ b/.gitignore @@ -27,9 +27,8 @@ ngClient/_system/js/appSettings/*.js WebApi/Configs/*.config # Gulp generated files -ngClient/_system/js/app/app.js -ngClient/_system/js/app/app.min.js -ngClient/_system/js/app/app.min.js.map +ngClient/_system/js/app/*.js +ngClient/_system/js/app/*.map ngClient/_system/js/lib/*.js ngClient/_system/js/lib/*.map ngClient/_system/css/app.css diff --git a/BusinessObjects/Models/ElementCell.cs b/BusinessObjects/Models/ElementCell.cs index 0d24b4269..7b3c872b4 100644 --- a/BusinessObjects/Models/ElementCell.cs +++ b/BusinessObjects/Models/ElementCell.cs @@ -37,12 +37,12 @@ public ElementCell(ElementField field, ElementItem item) public string StringValue { get; private set; } // TODO Doesn't have to be nullable but it requires a default value then which needs to be done - // by manually editing migration file which is not necessary at the moment / SH - 03 Aug. '15 + // by manually editing migration file which is not necessary at the moment / coni2k - 03 Aug. '15 [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public decimal? NumericValueTotal { get; private set; } // TODO Doesn't have to be nullable but it requires a default value then which needs to be done - // by manually editing migration file which is not necessary at the moment / SH - 03 Aug. '15 + // by manually editing migration file which is not necessary at the moment / coni2k - 03 Aug. '15 [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public int? NumericValueCount { get; private set; } diff --git a/BusinessObjects/Models/ElementField.cs b/BusinessObjects/Models/ElementField.cs index c8c88c28a..514456757 100644 --- a/BusinessObjects/Models/ElementField.cs +++ b/BusinessObjects/Models/ElementField.cs @@ -118,7 +118,7 @@ public ElementField EnableIndex(ElementFieldIndexCalculationType calculationType return this; } - // TODO Where is DisableIndex my dear?! / SH - 11 Jun. '16 + // TODO Where is DisableIndex my dear?! / coni2k - 11 Jun. '16 void ValidateEnableIndex() { diff --git a/BusinessObjects/Models/ResourcePool.cs b/BusinessObjects/Models/ResourcePool.cs index 2b17c5ed5..3ecdcd39a 100644 --- a/BusinessObjects/Models/ResourcePool.cs +++ b/BusinessObjects/Models/ResourcePool.cs @@ -61,12 +61,12 @@ public string Key public bool UseFixedResourcePoolRate { get; set; } // TODO Doesn't have to be nullable but it requires a default value then which needs to be done - // by manually editing migration file which is not necessary at the moment / SH - 03 Aug. '15 + // by manually editing migration file which is not necessary at the moment / coni2k - 03 Aug. '15 [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public decimal? ResourcePoolRateTotal { get; private set; } // TODO Doesn't have to be nullable but it requires a default value then which needs to be done - // by manually editing migration file which is not necessary at the moment / SH - 03 Aug. '15 + // by manually editing migration file which is not necessary at the moment / coni2k - 03 Aug. '15 [DatabaseGenerated(DatabaseGeneratedOption.Computed)] public int? ResourcePoolRateCount { get; private set; } diff --git a/BusinessObjects/WealthEconomyContext.cs b/BusinessObjects/WealthEconomyContext.cs index 3a869af03..56a0b2213 100644 --- a/BusinessObjects/WealthEconomyContext.cs +++ b/BusinessObjects/WealthEconomyContext.cs @@ -38,7 +38,7 @@ public static WealthEconomyContext Create() return new WealthEconomyContext(); } - // These definitions are used in generating OData metadata at the moment / SH - 07 Nov '14 + // These definitions are used in generating OData metadata at the moment / coni2k - 07 Nov '14 public virtual DbSet ResourcePool { get; set; } public virtual DbSet Element { get; set; } public virtual DbSet ElementField { get; set; } diff --git a/CHANGELOG.md b/CHANGELOG.md index e65d04ca4..d39a823fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,12 @@ ### Changelog -**0.61.4** +**0.62.0** -* New contributor: Shai Aharoni +* Typescript +https://github.com/forCrowd/WealthEconomy/issues/88 +* Resharper +https://github.com/forCrowd/WealthEconomy/issues/89 +* Comments signature update - coni2k **0.61.3** @@ -369,7 +373,7 @@ Now both cases call updateAnonymousChanges method which handles this case correc **0.40.0** -* Email confirmation has implemented +* Email confirmation was implemented * Survey.docx: A simple survey about the content. * logger.js minor improvements * forEach, some, filter functions instead of 'for' loops for arrays diff --git a/Facade/EmailService.cs b/Facade/EmailService.cs index a96c4ea4e..d78979bf0 100644 --- a/Facade/EmailService.cs +++ b/Facade/EmailService.cs @@ -58,7 +58,7 @@ public async Task SendAsync(IdentityMessage message) } case EnvironmentType.Live: { - // TODO Get rid of this ugliness asap! / SH - 04 Jan. '16 + // TODO Get rid of this ugliness asap! / coni2k - 04 Jan. '16 // This email type is only a notification to the admin var notificationToAdmin = message.Subject == "New external login" || message.Subject == "New anonymous login"; diff --git a/Framework/T4/EF6.Utility.ttinclude b/Framework/T4/EF6.Utility.ttinclude index 410135366..0f7f6abcd 100644 --- a/Framework/T4/EF6.Utility.ttinclude +++ b/Framework/T4/EF6.Utility.ttinclude @@ -10,7 +10,7 @@ IMPORTANT REMARK: EntityFramework.dll + EntityFramework.SqlServer.dll files unde "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE" folder were replaced with Entity Framework 6.1.3 versions that copied from "packages" folder under the solution. -v0.35.1 - SH - 02 Nov. '15 +v0.35.1 - coni2k - 02 Nov. '15 */ #> <#@ assembly name="%VS140COMNTOOLS%..\IDE\EntityFramework.dll" #> <#@ assembly name="%VS140COMNTOOLS%..\IDE\Microsoft.Data.Entity.Design.dll" #> diff --git a/SolutionItems/Properties/AssemblyInfo.cs b/SolutionItems/Properties/AssemblyInfo.cs index 6562929af..2393f3fc3 100644 --- a/SolutionItems/Properties/AssemblyInfo.cs +++ b/SolutionItems/Properties/AssemblyInfo.cs @@ -30,5 +30,5 @@ // // AssemblyFileVersion is not in use for the moment // -[assembly: AssemblyVersion("0.61.4")] +[assembly: AssemblyVersion("0.62.0")] [assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/SolutionItems/Scripts/Build/MSBuild.bat b/SolutionItems/Scripts/Build/MSBuild.bat index 3d716e8d4..126a45f97 100644 --- a/SolutionItems/Scripts/Build/MSBuild.bat +++ b/SolutionItems/Scripts/Build/MSBuild.bat @@ -1,7 +1,7 @@ @echo off REM Compiles the project with MSBuild & quite mode -REM SH - 07 May '14 +REM coni2k - 07 May '14 REM Confirmation CHOICE /M "Are you sure you want to run the script" diff --git a/SolutionItems/Scripts/Build/RunIISExpress.ps1 b/SolutionItems/Scripts/Build/RunIISExpress.ps1 index f99d8e54f..ccbebf366 100644 --- a/SolutionItems/Scripts/Build/RunIISExpress.ps1 +++ b/SolutionItems/Scripts/Build/RunIISExpress.ps1 @@ -1,5 +1,5 @@ # Manually runs IIS Express with the current applicationhost.config file # -# SH - 03 Jan. '16 +# coni2k - 03 Jan. '16 & 'C:\Program Files\IIS Express\iisexpress.exe' /config:'..\..\..\.vs\config\applicationhost.config' /systray:true diff --git a/SolutionItems/Scripts/Build/WebApiWarmUp.ps1 b/SolutionItems/Scripts/Build/WebApiWarmUp.ps1 index 46e43638a..ca05cb351 100644 --- a/SolutionItems/Scripts/Build/WebApiWarmUp.ps1 +++ b/SolutionItems/Scripts/Build/WebApiWarmUp.ps1 @@ -2,7 +2,7 @@ # # Makes a request to WebApi application to prevent waiting after the build operations (check WebApi project properties - Build Events tab) # -# SH - 05 Oct. '14 +# coni2k - 05 Oct. '14 # Make an async request (New-Object System.Net.WebClient).DownloadStringAsync("http://localhost:15001") diff --git a/WebApi/App_Start/Startup.cs b/WebApi/App_Start/Startup.cs index b1eefdd69..ce98b20f9 100644 --- a/WebApi/App_Start/Startup.cs +++ b/WebApi/App_Start/Startup.cs @@ -11,7 +11,7 @@ public partial class Startup // Configuration order is important // 1a. CorsConfig - 1b. ConfigureAuth // 2a. config.SuppressDefaultHostAuthentication() - 2b. MessageHandlers + ServerCompressionHandler - // TODO There should be more (maybe routing?) - Try to make the rest clear as well / SH - 13 Jan. '16 + // TODO There should be more (maybe routing?) - Try to make the rest clear as well / coni2k - 13 Jan. '16 // More info on Cors part; http://stackoverflow.com/a/25758949/1087768 public void Configuration(IAppBuilder app) { diff --git a/WebApi/Controllers/Api/AccountController.cs b/WebApi/Controllers/Api/AccountController.cs index 2c6f00333..66a1fe9f1 100644 --- a/WebApi/Controllers/Api/AccountController.cs +++ b/WebApi/Controllers/Api/AccountController.cs @@ -131,7 +131,7 @@ public async Task ExternalLoginCallback(string clientReturnUr // Since this method MUST return RedirectResult, cover the whole block with try & catch, // so it always redirect the user back to ngClient and won't get stuck on WebApi in case of an error - // SH - 16 Jan. '16 + // coni2k - 16 Jan. '16 try { var content = await GetLoginInfoText(); diff --git a/WebApi/Results/ChallengeResult.cs b/WebApi/Results/ChallengeResult.cs index be62ad754..b40baed78 100644 --- a/WebApi/Results/ChallengeResult.cs +++ b/WebApi/Results/ChallengeResult.cs @@ -24,7 +24,7 @@ public ChallengeResult(HttpRequestMessage request, string provider, string redir public Task ExecuteAsync(CancellationToken cancellationToken) { var properties = new AuthenticationProperties { - RedirectUri = RedirectUri // Without this prop, external provider returns to the page that it came from (in the current case /api/Account/ExternalLogin / SH - 29 Dec' 15) + RedirectUri = RedirectUri // Without this prop, external provider returns to the page that it came from (in the current case /api/Account/ExternalLogin / coni2k - 29 Dec' 15) }; Request.GetOwinContext().Authentication.Challenge(properties, LoginProvider); diff --git a/ngClient.Tests/entities/ElementTests.js b/ngClient.Tests/entities/ElementTests.js index 48af4a329..45b121ff8 100644 --- a/ngClient.Tests/entities/ElementTests.js +++ b/ngClient.Tests/entities/ElementTests.js @@ -777,7 +777,7 @@ describe('ng Element', function () { // TODO Manually update?! directIncomeField.setIndexIncome(); - // TODO Doesn't work at the moment, fix it later / SH - 27 Oct. '15 + // TODO Doesn't work at the moment, fix it later / coni2k - 27 Oct. '15 //expect(element.totalIncome()).toBe(2750); // TODO Update / remove @@ -862,7 +862,7 @@ describe('ng Element', function () { // TODO Manually update?! directIncomeField.setIndexIncome(); - // TODO Doesn't work at the moment, fix it later / SH - 27 Oct. '15 + // TODO Doesn't work at the moment, fix it later / coni2k - 27 Oct. '15 //expect(element.totalIncomeAverage()).toBe(2750 / 2); // TODO Update / remove diff --git a/ngClient/Web.config b/ngClient/Web.config index 903004a2f..150b19278 100644 --- a/ngClient/Web.config +++ b/ngClient/Web.config @@ -3,7 +3,7 @@ + coni2k - 17 Jan. '16 --> diff --git a/ngClient/_system/css/main.css b/ngClient/_system/css/main.css index 0665bd6fa..2eccfb97c 100644 --- a/ngClient/_system/css/main.css +++ b/ngClient/_system/css/main.css @@ -174,7 +174,7 @@ input[type="checkbox"].input-validation-error { display: none; } -/* Project level custom helpers / SH 24 Jan. '14 */ +/* Project level custom helpers / coni2k 24 Jan. '14 */ /* #region - Spaces - */ diff --git a/ngClient/_system/js/app/config/authorization.js b/ngClient/_system/js/app/config/authorization.ts similarity index 68% rename from ngClient/_system/js/app/config/authorization.js rename to ngClient/_system/js/app/config/authorization.ts index 4250e98c9..d16731c00 100644 --- a/ngClient/_system/js/app/config/authorization.js +++ b/ngClient/_system/js/app/config/authorization.ts @@ -2,21 +2,18 @@ * Authorization interceptors for angular & OData */ -(function () { +module Main.Config { 'use strict'; - angular.module('main') - .config(['$httpProvider', authorizationConfig]); - - angular.module('main') - .run(['logger', '$window', authorizationRun]); + var angularInterceptorId = 'AngularInterceptor'; - var interceptorId = 'angularInterceptor'; angular.module('main') - .factory(interceptorId, ['logger', '$q', '$window', angularInterceptor]); + .config(['$httpProvider', authorizationConfig]) + .run(['logger', '$window', authorizationRun]) + .factory(angularInterceptorId, ['logger', '$q', '$window', angularInterceptor]); - function authorizationConfig($httpProvider) { - $httpProvider.interceptors.push(interceptorId); + function authorizationConfig($httpProvider: ng.IHttpProvider) { + $httpProvider.interceptors.push(angularInterceptorId); } function authorizationRun(logger, $window) { @@ -27,7 +24,7 @@ // OData interceptor var oldClient = $window.OData.defaultHttpClient; var newClient = { - request: function (request, success, error) { + request(request, success, error) { request.headers = request.headers || {}; var token = angular.fromJson($window.localStorage.getItem('token')); request.headers.Authorization = token !== null ? 'Bearer ' + token.access_token : ''; @@ -37,20 +34,19 @@ $window.OData.defaultHttpClient = newClient; } - // angular function angularInterceptor(logger, $q, $window) { // Logger - logger = logger.forSource(interceptorId); + logger = logger.forSource(angularInterceptorId); return { - request: function (config) { + request(config) { config.headers = config.headers || {}; var token = angular.fromJson($window.localStorage.getItem('token')); config.headers.Authorization = token !== null ? 'Bearer ' + token.access_token : ''; return config; }, - response: function (response) { + response(response) { if (response.status === 401) { // handle the case where the user is not authenticated } @@ -58,4 +54,4 @@ } }; } -})(); +} diff --git a/ngClient/_system/js/app/config/breeze.js b/ngClient/_system/js/app/config/breeze.ts similarity index 58% rename from ngClient/_system/js/app/config/breeze.js rename to ngClient/_system/js/app/config/breeze.ts index b51c01a7e..c999aa49a 100644 --- a/ngClient/_system/js/app/config/breeze.js +++ b/ngClient/_system/js/app/config/breeze.ts @@ -1,12 +1,11 @@ -(function () { +module Main.Config { 'use strict'; angular.module('main') .config(['breezeProvider', breezeConfig]) - .config(['zDirectivesConfigProvider', breezeConfigDirective]); - - function breezeConfig(breezeProvider) { + .config(['zDirectivesConfigProvider', breezeDirectiveConfig]); + function breezeConfig(breezeProvider: any) { breeze.config.initializeAdapterInstance('uriBuilder', 'odata'); // Use Web API OData to query and save @@ -16,16 +15,11 @@ // convert between server-side PascalCase and client-side camelCase // breeze.NamingConvention.camelCase.setAsDefault(); - function getRoutePrefix_Microsoft_AspNet_WebApi_OData_5_3_x(dataService) { + function getRoutePrefix_Microsoft_AspNet_WebApi_OData_5_3_x(dataService: any) { // Copied from breeze.debug and modified for Web API OData v.5.3.1. - var parser = null; - if (typeof document === 'object') { // browser - parser = document.createElement('a'); - parser.href = dataService.serviceName; - } else { // node - parser = url.parse(dataService.serviceName); - } + var parser = document.createElement('a'); + parser.href = dataService.serviceName; // THE CHANGE FOR 5.3.1: Add '/' prefix to pathname var prefix = parser.pathname; @@ -40,13 +34,11 @@ } } - // Configure the Breeze Validation Directive for bootstrap - function breezeConfigDirective(config) { - - // Custom template with warning icon before the error message - config.zRequiredTemplate = ''; - config.zValidateTemplate = '%error%!'; + function breezeDirectiveConfig(config: any) { + // Custom template with warning icon before the error message + config.zRequiredTemplate = ''; + config.zValidateTemplate = '%error%!'; + } - -})(); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/config/exceptionHandlerExtension.js b/ngClient/_system/js/app/config/exceptionHandlerExtension.ts similarity index 73% rename from ngClient/_system/js/app/config/exceptionHandlerExtension.js rename to ngClient/_system/js/app/config/exceptionHandlerExtension.ts index 194599b50..a4842cb1b 100644 --- a/ngClient/_system/js/app/config/exceptionHandlerExtension.js +++ b/ngClient/_system/js/app/config/exceptionHandlerExtension.ts @@ -1,20 +1,19 @@ -(function () { +module Main.Config { 'use strict'; - var factoryId = 'exceptionHandlerExtension'; angular.module('main') .config(['$provide', extendHandler]); - function extendHandler($provide) { + function extendHandler($provide: any) { $provide.decorator('$exceptionHandler', ['logger', 'serviceAppUrl', '$delegate', '$injector', '$window', exceptionHandlerExtension]); } - function exceptionHandlerExtension(logger, serviceAppUrl, $delegate, $injector, $window) { - logger = logger.forSource(factoryId); + function exceptionHandlerExtension(logger: any, serviceAppUrl: any, $delegate: any, $injector: any, $window: any) { + logger = logger.forSource('exceptionHandlerExtension'); var exceptionUrl = serviceAppUrl + '/api/Exception/Record'; - return function (exception, cause) { + return (exception, cause) => { // No need to call the base, will be logged here // $delegate(exception, cause); @@ -26,7 +25,7 @@ } getSourceMappedStackTrace(exception) - .then(function (sourceMappedStack) { + .then(sourceMappedStack => { // Send the exception to the server var exceptionModel = { @@ -40,25 +39,25 @@ $http.post(exceptionUrl, exceptionModel); // Rethrow the exception - setTimeout(function () { + setTimeout(() => { throw exception; }); }); }; - function getSourceMappedStackTrace(exception) { + function getSourceMappedStackTrace(exception: any) { var $q = $injector.get('$q'), $http = $injector.get('$http'), SMConsumer = $window.sourceMap.SourceMapConsumer, cache = {}; if (exception.stack) { // not all browsers support stack traces - return $q.all($.map(exception.stack.split(/\n/), function (stackLine) { + return $q.all($.map(exception.stack.split(/\n/), stackLine => { var match = stackLine.match(/^(.+)(http.+):(\d+):(\d+)/); if (match) { var prefix = match[1], url = match[2], line = match[3], col = match[4]; - return getMapForScript(url).then(function (map) { + return getMapForScript(url).then(map => { var pos = map.originalPositionFor({ line: parseInt(line, 10), @@ -69,34 +68,28 @@ mangledName = (mangledName && mangledName[2]) || ''; return ' at ' + (pos.name ? pos.name : mangledName) + ' ' + - $window.location.origin + pos.source + ':' + pos.line + ':' + - pos.column; - }, function () { - return stackLine; - }); + $window.location.origin + pos.source + ':' + pos.line + ':' + + pos.column; + }, () => stackLine); } else { return $q.when(stackLine); } - })).then(function (lines) { - return lines.join('\n'); - }); + })).then(lines => lines.join('\n')); } else { return $q.when(''); } // Retrieve a SourceMap object for a minified script URL - function getMapForScript(url) { + function getMapForScript(url: any) { if (cache[url]) { return cache[url]; } else { - var promise = $http.get(url).then(function (response) { + var promise = $http.get(url).then(response => { var m = response.data.match(/\/\/# sourceMappingURL=(.+\.map)/); if (m) { var path = url.match(/^(.+)\/[^/]+$/); path = path && path[1]; - return $http.get(path + '/' + m[1]).then(function (response) { - return new SMConsumer(response.data); - }); + return $http.get(path + '/' + m[1]).then(response => new SMConsumer(response.data)); } else { return $q.reject(); } @@ -107,4 +100,4 @@ } } } -})(); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/config/googleAnalytics.js b/ngClient/_system/js/app/config/googleAnalytics.js deleted file mode 100644 index 14495852e..000000000 --- a/ngClient/_system/js/app/config/googleAnalytics.js +++ /dev/null @@ -1,14 +0,0 @@ -(function () { - 'use strict'; - - angular.module('main') - .config(['AnalyticsProvider', 'analyticsTrackingCode', 'analyticsDomainName', analyticsConfig]); - - angular.module('main').run(['Analytics', function (Analytics) { }]); - - function analyticsConfig(AnalyticsProvider, analyticsTrackingCode, analyticsDomainName) { - AnalyticsProvider.setAccount(analyticsTrackingCode) - .setDomainName(analyticsDomainName) - .ignoreFirstPageLoad(true); - } -})(); diff --git a/ngClient/_system/js/app/config/googleAnalytics.ts b/ngClient/_system/js/app/config/googleAnalytics.ts new file mode 100644 index 000000000..23f3a53d4 --- /dev/null +++ b/ngClient/_system/js/app/config/googleAnalytics.ts @@ -0,0 +1,14 @@ +module Main.Config { + 'use strict'; + + angular.module('main') + .config(['AnalyticsProvider', 'analyticsTrackingCode', 'analyticsDomainName', analyticsConfig]); + + angular.module('main').run(['Analytics', analytics => { }]); + + function analyticsConfig(analyticsProvider: any, analyticsTrackingCode: any, analyticsDomainName: any) { + analyticsProvider.setAccount(analyticsTrackingCode) + .setDomainName(analyticsDomainName) + .ignoreFirstPageLoad(true); + } +} \ No newline at end of file diff --git a/ngClient/_system/js/app/config/route.js b/ngClient/_system/js/app/config/route.js deleted file mode 100644 index abc1ca965..000000000 --- a/ngClient/_system/js/app/config/route.js +++ /dev/null @@ -1,126 +0,0 @@ -(function () { - 'use strict'; - - angular.module('main') - .config(['$locationProvider', '$routeProvider', routeConfig]); - - angular.module('main') - .run(['locationHistory', 'logger', '$location', '$rootScope', routeRun]); - - function routeConfig($locationProvider, $routeProvider) { - - // Routes - $routeProvider - - /* Content */ - .when('/', { title: 'Home', templateUrl: '/_system/views/content/home.html?v=0.53.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/default.aspx', { title: 'Home', templateUrl: '/_system/views/content/home.html?v=0.53.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - // Different than other content pages, enableDisqus: false - .when('/_system/content/notFound', { title: 'Not Found', templateUrl: '/_system/views/content/notFound.html?v=0.52.0', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/content/allInOne', { title: 'All in One', templateUrl: '/_system/views/content/allInOne.html?v=0.49.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/content/basics', { title: 'Basics', templateUrl: '/_system/views/content/basics.html?v=0.53.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/content/home', { title: 'Home', templateUrl: '/_system/views/content/home.html?v=0.53.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/content/implementation', { title: 'Implementation', templateUrl: '/_system/views/content/implementation.html?v=0.49.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/content/introduction', { title: 'Introduction', templateUrl: '/_system/views/content/introduction.html?v=0.53.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/content/knowledgeIndex', { title: 'Knowledge Index', templateUrl: '/_system/views/content/knowledgeIndex.html?v=0.51.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/content/priorityIndex', { title: 'Priority Index', templateUrl: '/_system/views/content/priorityIndex.html?v=0.49.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/content/prologue', { title: 'Prologue', templateUrl: '/_system/views/content/prologue.html?v=0.51.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/content/reason', { title: 'Reason', templateUrl: '/_system/views/content/reason.html?v=0.58.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/content/totalCostIndex', { title: 'Total Cost Index', templateUrl: '/_system/views/content/totalCostIndex.html?v=0.49.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/content/contributors', { title: 'Contributors', templateUrl: '/_system/views/content/contributors.html?v=0.60.1', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - - /* Account */ - .when('/_system/account', { title: 'Account', templateUrl: '/_system/views/account/account.html?v=0.55.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/account/accountEdit', { title: 'Account Edit', templateUrl: '/_system/views/account/accountEdit.html?v=0.55.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/account/addPassword', { title: 'Add Password', templateUrl: '/_system/views/account/addPassword.html?v=0.55.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/account/changeEmail', { title: 'Change Email', templateUrl: '/_system/views/account/changeEmail.html?v=0.55.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/account/changePassword', { title: 'Change Password', templateUrl: '/_system/views/account/changePassword.html?v=0.55.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/account/changeUserName', { title: 'Change Username', templateUrl: '/_system/views/account/changeUsername.html?v=0.55.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/account/confirmEmail', { title: 'Confirm Email', templateUrl: '/_system/views/account/confirmEmail.html?v=0.51.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/account/login', { title: 'Login', templateUrl: '/_system/views/account/login.html?v=0.58.0', accessType: 'unauthenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/account/register', { title: 'Register', templateUrl: '/_system/views/account/register.html?v=0.58.0', accessType: 'unauthenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/_system/account/resetPassword', { title: 'Reset Password', templateUrl: '/_system/views/account/resetPassword.html?v=0.55.0', accessType: 'unauthenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - - /* CMRP Search */ - .when('/_system/resourcePool/search', { title: 'CMRP Search', templateUrl: '/_system/views/resourcePool/resourcePoolSearch.html?v=0.57.0', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - - /* User */ - .when('/:userName', { title: 'Profile', templateUrl: '/_system/views/account/profile.html?v=0.57.0', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/:userName/new', { title: 'New CMRP', templateUrl: '/_system/views/resourcePool/resourcePoolManage.html?v=0.58.0', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/:userName/:resourcePoolKey/edit', { title: 'Edit CMRP', templateUrl: '/_system/views/resourcePool/resourcePoolManage.html?v=0.58.0', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - .when('/:userName/:resourcePoolKey', { title: 'View CMRP', templateUrl: '/_system/views/resourcePool/resourcePoolView.html?v=0.57.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) - - /* Otherwise */ - .otherwise({ redirectTo: getNotFound }) - ; - - // Html5Mode is on, if supported (# will not be used) - if (window.history && window.history.pushState) { - $locationProvider.html5Mode({ enabled: true }); - } - - function getNotFound(routeParams, path, search) { - - var invalidUrl = path; - var keys = Object.keys(search); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - invalidUrl += (i === 0 ? '?' : '&') + key + '=' + search[key]; - } - - return '/_system/content/notFound?url=' + invalidUrl; - } - - function validateAccess(dataContext, locationHistory, logger, $location, $q, $route) { - - logger = logger.forSource('validateAccess'); - - var deferred = $q.defer(); - - locationHistory.createItem($location, $route.current); - - dataContext.initializeCurrentUser() - .then(function (currentUser) { - if ($route.current.accessType !== 'undefined') { - - // Invalid access cases - if (($route.current.accessType === 'unauthenticatedRequired' && currentUser.isAuthenticated() && !currentUser.IsAnonymous) || - ($route.current.accessType === 'authenticatedRequired' && !currentUser.isAuthenticated())) { - deferred.reject({ accessType: $route.current.accessType }); - } - } - - deferred.resolve(); - }) - .catch(function () { - deferred.reject(); // TODO Handle? - }); - - return deferred.promise; - } - } - - function routeRun(locationHistory, logger, $location, $rootScope) { - - // Logger - logger = logger.forSource('routeRun'); - - $rootScope.$on('$routeChangeError', routeChangeError); - $rootScope.$on('$routeChangeSuccess', routeChangeSuccess); - - // Navigate to correct page in 'Invalid access' cases - function routeChangeError(event, current, previous, eventObj) { - if (eventObj.accessType === 'unauthenticatedRequired') { - $location.url('/'); - } else if (eventObj.accessType === 'authenticatedRequired') { - $location.url('/_system/account/login?error=To be able to continue, please login first'); - } - } - - function routeChangeSuccess(event, current, previous) { - - // View title - $rootScope.viewTitle = typeof current.title !== 'undefined' ? current.title : ''; - } - } -})(); diff --git a/ngClient/_system/js/app/config/route.ts b/ngClient/_system/js/app/config/route.ts new file mode 100644 index 000000000..526a265a6 --- /dev/null +++ b/ngClient/_system/js/app/config/route.ts @@ -0,0 +1,128 @@ +module Main.Config { + 'use strict'; + + angular.module('main') + .config(['$locationProvider', '$routeProvider', routeConfig]); + + angular.module('main') + .run(['locationHistory', 'logger', '$location', '$rootScope', routeRun]); + + function routeConfig($locationProvider: any, $routeProvider: any) { + + // Routes + $routeProvider + + /* Content */ + .when('/', { title: 'Home', templateUrl: '/_system/views/content/home.html?v=0.53.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/default.aspx', { title: 'Home', templateUrl: '/_system/views/content/home.html?v=0.53.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + // Different than other content pages, enableDisqus: false + .when('/_system/content/notFound', { title: 'Not Found', templateUrl: '/_system/views/content/notFound.html?v=0.52.0', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/content/allInOne', { title: 'All in One', templateUrl: '/_system/views/content/allInOne.html?v=0.49.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/content/basics', { title: 'Basics', templateUrl: '/_system/views/content/basics.html?v=0.53.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/content/home', { title: 'Home', templateUrl: '/_system/views/content/home.html?v=0.53.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/content/implementation', { title: 'Implementation', templateUrl: '/_system/views/content/implementation.html?v=0.49.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/content/introduction', { title: 'Introduction', templateUrl: '/_system/views/content/introduction.html?v=0.53.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/content/knowledgeIndex', { title: 'Knowledge Index', templateUrl: '/_system/views/content/knowledgeIndex.html?v=0.51.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/content/priorityIndex', { title: 'Priority Index', templateUrl: '/_system/views/content/priorityIndex.html?v=0.49.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/content/prologue', { title: 'Prologue', templateUrl: '/_system/views/content/prologue.html?v=0.51.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/content/reason', { title: 'Reason', templateUrl: '/_system/views/content/reason.html?v=0.58.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/content/totalCostIndex', { title: 'Total Cost Index', templateUrl: '/_system/views/content/totalCostIndex.html?v=0.49.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/content/contributors', { title: 'Contributors', templateUrl: '/_system/views/content/contributors.html?v=0.60.1', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + + /* Account */ + .when('/_system/account', { title: 'Account', templateUrl: '/_system/views/account/account.html?v=0.55.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/account/accountEdit', { title: 'Account Edit', templateUrl: '/_system/views/account/accountEdit.html?v=0.55.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/account/addPassword', { title: 'Add Password', templateUrl: '/_system/views/account/addPassword.html?v=0.55.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/account/changeEmail', { title: 'Change Email', templateUrl: '/_system/views/account/changeEmail.html?v=0.55.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/account/changePassword', { title: 'Change Password', templateUrl: '/_system/views/account/changePassword.html?v=0.55.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/account/changeUserName', { title: 'Change Username', templateUrl: '/_system/views/account/changeUsername.html?v=0.55.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/account/confirmEmail', { title: 'Confirm Email', templateUrl: '/_system/views/account/confirmEmail.html?v=0.51.0', accessType: 'authenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/account/login', { title: 'Login', templateUrl: '/_system/views/account/login.html?v=0.58.0', accessType: 'unauthenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/account/register', { title: 'Register', templateUrl: '/_system/views/account/register.html?v=0.58.0', accessType: 'unauthenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/_system/account/resetPassword', { title: 'Reset Password', templateUrl: '/_system/views/account/resetPassword.html?v=0.55.0', accessType: 'unauthenticatedRequired', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + + /* CMRP Search */ + .when('/_system/resourcePool/search', { title: 'CMRP Search', templateUrl: '/_system/views/resourcePool/resourcePoolSearch.html?v=0.57.0', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + + /* User */ + .when('/:userName', { title: 'Profile', templateUrl: '/_system/views/account/profile.html?v=0.57.0', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/:userName/new', { title: 'New CMRP', templateUrl: '/_system/views/resourcePool/resourcePoolManage.html?v=0.58.0', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/:userName/:resourcePoolKey/edit', { title: 'Edit CMRP', templateUrl: '/_system/views/resourcePool/resourcePoolManage.html?v=0.58.0', resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + .when('/:userName/:resourcePoolKey', { title: 'View CMRP', templateUrl: '/_system/views/resourcePool/resourcePoolView.html?v=0.57.0', enableDisqus: true, resolve: { validateAccess: ['dataContext', 'locationHistory', 'logger', '$location', '$q', '$route', validateAccess] } }) + + /* Otherwise */ + .otherwise({ redirectTo: getNotFound }) + ; + + // Html5Mode is on, if supported (# will not be used) + if (window.history && window.history.pushState) { + $locationProvider.html5Mode({ enabled: true }); + } + + function getNotFound(routeParams: any, path: any, search: any) { + + var invalidUrl = path; + var keys = Object.keys(search); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + invalidUrl += (i === 0 ? '?' : '&') + key + '=' + search[key]; + } + + return '/_system/content/notFound?url=' + invalidUrl; + } + + function validateAccess(dataContext: any, locationHistory: any, logger: any, $location: any, $q: any, $route: any) { + + logger = logger.forSource('validateAccess'); + + var deferred = $q.defer(); + + locationHistory.createItem($location, $route.current); + + dataContext.initializeCurrentUser() + .then(currentUser => { + if ($route.current.accessType !== 'undefined') { + + // Invalid access cases + if (($route.current.accessType === 'unauthenticatedRequired' && currentUser.isAuthenticated() && !currentUser.IsAnonymous) || + ($route.current.accessType === 'authenticatedRequired' && !currentUser.isAuthenticated())) { + deferred.reject({ accessType: $route.current.accessType }); + } + } + + deferred.resolve(); + }) + .catch(() => { + deferred.reject(); // TODO Handle? + }); + + return deferred.promise; + } + } + + function routeRun(locationHistory: any, logger: any, $location: any, $rootScope: any) { + + // Logger + logger = logger.forSource('routeRun'); + + $rootScope.$on('$routeChangeError', routeChangeError); + $rootScope.$on('$routeChangeSuccess', routeChangeSuccess); + + // Navigate to correct page in 'Invalid access' cases + function routeChangeError(event: any, current: any, previous: any, eventObj: any); + function routeChangeError(event, current, previous, eventObj) { + if (eventObj.accessType === 'unauthenticatedRequired') { + $location.url('/'); + } else if (eventObj.accessType === 'authenticatedRequired') { + $location.url('/_system/account/login?error=To be able to continue, please login first'); + } + } + + function routeChangeSuccess(event: any, current: any, previous: any); + function routeChangeSuccess(event, current, previous) { + + // View title + $rootScope.viewTitle = typeof current.title !== 'undefined' ? current.title : ''; + } + } +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/account/AccountController.js b/ngClient/_system/js/app/controllers/account/AccountController.js deleted file mode 100644 index 9a50eed33..000000000 --- a/ngClient/_system/js/app/controllers/account/AccountController.js +++ /dev/null @@ -1,28 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'AccountController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', '$routeParams', '$scope', AccountController]); - - function AccountController(dataContext, logger, $routeParams, $scope) { - - // Logger - logger = logger.forSource(controllerId); - - var vm = this; - vm.currentUser = dataContext.getCurrentUser(); - - // Events - $scope.$on('dataContext_currentUserChanged', currentUserChanged); - - _init(); - - function _init() { - } - - function currentUserChanged(event, newUser) { - vm.currentUser = newUser; - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/account/AccountController.ts b/ngClient/_system/js/app/controllers/account/AccountController.ts new file mode 100644 index 000000000..a824d8d22 --- /dev/null +++ b/ngClient/_system/js/app/controllers/account/AccountController.ts @@ -0,0 +1,34 @@ +module Main.Controllers { + 'use strict'; + + var controllerId = 'AccountController'; + + export class AccountController { + + static $inject = ['dataContext', 'logger', '$routeParams', '$scope']; + + constructor(dataContext: any, logger: any, $routeParams: any, $scope: any) { + + // Logger + logger = logger.forSource(controllerId); + + var vm: any = this; + vm.currentUser = dataContext.getCurrentUser(); + + // Events + $scope.$on('dataContext_currentUserChanged', currentUserChanged); + + _init(); + + function _init() { + } + + function currentUserChanged(event: any, newUser: any); + function currentUserChanged(event, newUser) { + vm.currentUser = newUser; + } + } + } + + angular.module('main').controller(controllerId, AccountController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/account/AccountEditController.js b/ngClient/_system/js/app/controllers/account/AccountEditController.js deleted file mode 100644 index 0ee213b6a..000000000 --- a/ngClient/_system/js/app/controllers/account/AccountEditController.js +++ /dev/null @@ -1,52 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'AccountEditController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', '$location', AccountEditController]); - - function AccountEditController(dataContext, logger, $location) { - logger = logger.forSource(controllerId); - - var isSaving = false; - - // Controller methods (alphabetically) - var vm = this; - vm.cancel = cancel; - vm.isSaveDisabled = isSaveDisabled; - vm.currentUser = dataContext.getCurrentUser(); - vm.saveChanges = saveChanges; - - /*** Implementations ***/ - - function cancel() { - vm.currentUser.entityAspect.rejectChanges(); - $location.url('/_system/account'); - } - - function isSaveDisabled() { - //return isSaving || (!dataContext.hasChanges()); - return isSaving; - } - - function saveChanges() { - - isSaving = true; - dataContext.saveChanges() - .then(function (result) { - logger.logSuccess('Your changes have been saved!', null, true); - $location.url('/_system/account'); - }) - .catch(function (error) { - - // Conflict (Concurrency exception) - if (error.status === '409') { - // TODO Try to recover! - } - }) - .finally(function () { - isSaving = false; - }); - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/account/AccountEditController.ts b/ngClient/_system/js/app/controllers/account/AccountEditController.ts new file mode 100644 index 000000000..b425d6efa --- /dev/null +++ b/ngClient/_system/js/app/controllers/account/AccountEditController.ts @@ -0,0 +1,59 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'AccountEditController'; + + export class AccountEditController { + + static $inject = ['dataContext', 'logger', '$location']; + + constructor(dataContext: any, logger: any, $location: any) { + + // Logger + logger = logger.forSource(controllerId); + + var isSaving = false; + + // Controller methods (alphabetically) + var vm: any = this; + vm.cancel = cancel; + vm.currentUser = dataContext.getCurrentUser(); + vm.isSaveDisabled = isSaveDisabled; + vm.saveChanges = saveChanges; + + /*** Implementations ***/ + + function cancel() { + vm.currentUser.entityAspect.rejectChanges(); + $location.url('/_system/account'); + } + + function isSaveDisabled() { + //return isSaving || (!dataContext.hasChanges()); + return isSaving; + } + + function saveChanges() { + + isSaving = true; + dataContext.saveChanges() + .then(result => { + logger.logSuccess('Your changes have been saved!', null, true); + $location.url('/_system/account'); + }) + .catch(error => { + + // Conflict (Concurrency exception) + if (error.status === '409') { + // TODO Try to recover! + } + }) + .finally(() => { + isSaving = false; + }); + } + } + } + + angular.module('main').controller(controllerId, AccountEditController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/account/AddPasswordController.js b/ngClient/_system/js/app/controllers/account/AddPasswordController.js deleted file mode 100644 index cfc0b880e..000000000 --- a/ngClient/_system/js/app/controllers/account/AddPasswordController.js +++ /dev/null @@ -1,43 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'AddPasswordController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', '$location', AddPasswordController]); - - function AddPasswordController(dataContext, logger, $location) { - logger = logger.forSource(controllerId); - - var vm = this; - vm.addPassword = addPassword; - vm.bindingModel = { - Password: '', - ConfirmPassword: '' - }; - vm.cancel = cancel; - vm.isSaving = false; - vm.isSaveDisabled = isSaveDisabled; - - function addPassword() { - - vm.isSaving = true; - - dataContext.addPassword(vm.bindingModel) - .success(function () { - logger.logSuccess('Your password has been set!', null, true); - $location.url('/_system/account'); - }) - .finally(function () { - vm.isSaving = false; - }); - } - - function cancel() { - $location.url('/_system/account'); - } - - function isSaveDisabled() { - return vm.isSaving; - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/account/AddPasswordController.ts b/ngClient/_system/js/app/controllers/account/AddPasswordController.ts new file mode 100644 index 000000000..87431bc45 --- /dev/null +++ b/ngClient/_system/js/app/controllers/account/AddPasswordController.ts @@ -0,0 +1,45 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'AddPasswordController'; + + export class AddPasswordController { + + static $inject = ['dataContext', 'logger', '$location']; + + constructor(dataContext: any, logger: any, $location: any) { + + // Logger + logger = logger.forSource(controllerId); + + var vm: any = this; + vm.addPassword = addPassword; + vm.cancel = cancel; + vm.isSaveDisabled = isSaveDisabled; + + function addPassword() { + + vm.isSaving = true; + + dataContext.addPassword(vm.bindingModel) + .success(() => { + logger.logSuccess('Your password has been set!', null, true); + $location.url('/_system/account'); + }) + .finally(() => { + vm.isSaving = false; + }); + } + + function cancel() { + $location.url('/_system/account'); + } + + function isSaveDisabled(): boolean { + return vm.isSaving; + } + } + } + + angular.module('main').controller(controllerId, AddPasswordController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/account/ChangeEmailController.js b/ngClient/_system/js/app/controllers/account/ChangeEmailController.js deleted file mode 100644 index 50544cbaa..000000000 --- a/ngClient/_system/js/app/controllers/account/ChangeEmailController.js +++ /dev/null @@ -1,51 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'ChangeEmailController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', '$location', ChangeEmailController]); - - function ChangeEmailController(dataContext, logger, $location) { - logger = logger.forSource(controllerId); - - var vm = this; - vm.bindingModel = { - Email: '' - }; - vm.cancel = cancel; - vm.changeEmail = changeEmail; - vm.isSaving = false; - vm.isSaveDisabled = isSaveDisabled; - - _init(); - - function _init() { - - // Generate test data if localhost - if ($location.host() === 'localhost') { - vm.bindingModel.Email = dataContext.getUniqueEmail(); - } - } - - function cancel() { - $location.url('/_system/account'); - } - - function changeEmail() { - - vm.isSaving = true; - - dataContext.changeEmail(vm.bindingModel) - .success(function () { - $location.url('/_system/account/confirmEmail'); - }) - .finally(function () { - vm.isSaving = false; - }); - } - - function isSaveDisabled() { - return vm.isSaving; - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/account/ChangeEmailController.ts b/ngClient/_system/js/app/controllers/account/ChangeEmailController.ts new file mode 100644 index 000000000..375677e4f --- /dev/null +++ b/ngClient/_system/js/app/controllers/account/ChangeEmailController.ts @@ -0,0 +1,58 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'ChangeEmailController'; + + export class ChangeEmailController { + + static $inject = ['dataContext', 'logger', '$location']; + + constructor(dataContext, logger, $location) { + + // Logger + logger = logger.forSource(controllerId); + + var vm: any = this; + vm.bindingModel = { + Email: '' + }; + vm.cancel = cancel; + vm.changeEmail = changeEmail; + vm.isSaving = false; + vm.isSaveDisabled = isSaveDisabled; + + _init(); + + function _init() { + + // Generate test data if localhost + if ($location.host() === 'localhost') { + vm.bindingModel.Email = dataContext.getUniqueEmail(); + } + } + + function cancel() { + $location.url('/_system/account'); + } + + function changeEmail() { + + vm.isSaving = true; + + dataContext.changeEmail(vm.bindingModel) + .success(() => { + $location.url('/_system/account/confirmEmail'); + }) + .finally(() => { + vm.isSaving = false; + }); + } + + function isSaveDisabled() { + return vm.isSaving; + } + } + } + + angular.module('main').controller(controllerId, ChangeEmailController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/account/ChangePasswordController.js b/ngClient/_system/js/app/controllers/account/ChangePasswordController.js deleted file mode 100644 index 1333d106c..000000000 --- a/ngClient/_system/js/app/controllers/account/ChangePasswordController.js +++ /dev/null @@ -1,44 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'ChangePasswordController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', '$location', ChangePasswordController]); - - function ChangePasswordController(dataContext, logger, $location) { - logger = logger.forSource(controllerId); - - var vm = this; - vm.bindingModel = { - CurrentPassword: '', - NewPassword: '', - ConfirmPassword: '' - }; - vm.cancel = cancel; - vm.changePassword = changePassword; - vm.isSaving = false; - vm.isSaveDisabled = isSaveDisabled; - - function cancel() { - $location.url('/_system/account'); - } - - function changePassword() { - - vm.isSaving = true; - - dataContext.changePassword(vm.bindingModel) - .success(function () { - logger.logSuccess('Your password has been changed!', null, true); - $location.url('/_system/account'); - }) - .finally(function () { - vm.isSaving = false; - }); - } - - function isSaveDisabled() { - return vm.isSaving; - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/account/ChangePasswordController.ts b/ngClient/_system/js/app/controllers/account/ChangePasswordController.ts new file mode 100644 index 000000000..324a09b6d --- /dev/null +++ b/ngClient/_system/js/app/controllers/account/ChangePasswordController.ts @@ -0,0 +1,50 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'ChangePasswordController'; + + export class ChangePasswordController { + + static $inject = ['dataContext', 'logger', '$location']; + + constructor(dataContext: any, logger: any, $location: any) { + + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.bindingModel = { + CurrentPassword: '', + NewPassword: '', + ConfirmPassword: '' + }; + vm.cancel = cancel; + vm.changePassword = changePassword; + vm.isSaving = false; + vm.isSaveDisabled = isSaveDisabled; + + function cancel() { + $location.url('/_system/account'); + } + + function changePassword() { + + vm.isSaving = true; + + dataContext.changePassword(vm.bindingModel) + .success(() => { + logger.logSuccess('Your password has been changed!', null, true); + $location.url('/_system/account'); + }) + .finally(() => { + vm.isSaving = false; + }); + } + + function isSaveDisabled() { + return vm.isSaving; + } + } + } + + angular.module('main').controller(controllerId, ChangePasswordController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/account/ChangeUserNameController.js b/ngClient/_system/js/app/controllers/account/ChangeUserNameController.js deleted file mode 100644 index a5b1065f7..000000000 --- a/ngClient/_system/js/app/controllers/account/ChangeUserNameController.js +++ /dev/null @@ -1,66 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'ChangeUserNameController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', '$location', ChangeUserNameController]); - - function ChangeUserNameController(dataContext, logger, $location) { - - // Logger - logger = logger.forSource(controllerId); - - var vm = this; - vm.bindingModel = { - UserName: '' - }; - vm.cancel = cancel; - vm.changeUserName = changeUserName; - vm.currentUser = { UserName: '' }; - vm.externalLoginInit = $location.search().init; // For external login's - vm.isSaving = false; - vm.isSaveDisabled = isSaveDisabled; - - _init(); - - function _init() { - - vm.currentUser = dataContext.getCurrentUser(); - vm.bindingModel.UserName = vm.currentUser.UserName; - - // Generate test data if localhost - if ($location.host() === 'localhost') { - vm.bindingModel.UserName = dataContext.getUniqueUserName(); - } - } - - function cancel() { - $location.url(getReturnUrl()); - } - - function changeUserName() { - - vm.isSaving = true; - - dataContext.changeUserName(vm.bindingModel) - .success(function () { - logger.logSuccess('Your username has been changed!', null, true); - $location.url(getReturnUrl()); - }) - .finally(function () { - vm.isSaving = false; - }); - } - - function getReturnUrl() { - var clientReturnUrl = $location.search().clientReturnUrl; - return typeof clientReturnUrl !== 'undefined' ? - clientReturnUrl : - '/_system/account'; - } - - function isSaveDisabled() { - return vm.bindingModel.UserName === vm.currentUser.UserName || vm.isSaving; - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/account/ChangeUserNameController.ts b/ngClient/_system/js/app/controllers/account/ChangeUserNameController.ts new file mode 100644 index 000000000..f7f5ddac8 --- /dev/null +++ b/ngClient/_system/js/app/controllers/account/ChangeUserNameController.ts @@ -0,0 +1,69 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'ChangeUserNameController'; + + export class ChangeUserNameController { + + static $inject = ['dataContext', 'logger', '$location']; + + constructor(dataContext: any, logger: any, $location: any) { + + // Logger + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.bindingModel = { + UserName: '' + }; + vm.cancel = cancel; + vm.changeUserName = changeUserName; + vm.currentUser = { UserName: '' }; + vm.externalLoginInit = $location.search().init; // For external login's + vm.isSaving = false; + vm.isSaveDisabled = isSaveDisabled; + + _init(); + + function _init() { + + vm.currentUser = dataContext.getCurrentUser(); + vm.bindingModel.UserName = vm.currentUser.UserName; + + // Generate test data if localhost + if ($location.host() === 'localhost') { + vm.bindingModel.UserName = dataContext.getUniqueUserName(); + } + } + + function cancel() { + $location.url(getReturnUrl()); + } + + function changeUserName() { + + vm.isSaving = true; + + dataContext.changeUserName(vm.bindingModel) + .success(() => { + logger.logSuccess('Your username has been changed!', null, true); + $location.url(getReturnUrl()); + }) + .finally(() => { + vm.isSaving = false; + }); + } + + function getReturnUrl() { + var clientReturnUrl = $location.search().clientReturnUrl; + return typeof clientReturnUrl !== 'undefined' ? clientReturnUrl : '/_system/account'; + } + + function isSaveDisabled() { + return vm.bindingModel.UserName === vm.currentUser.UserName || vm.isSaving; + } + } + } + + angular.module('main').controller(controllerId, ChangeUserNameController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/account/ConfirmEmailController.js b/ngClient/_system/js/app/controllers/account/ConfirmEmailController.js deleted file mode 100644 index e3fbbab82..000000000 --- a/ngClient/_system/js/app/controllers/account/ConfirmEmailController.js +++ /dev/null @@ -1,56 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'ConfirmEmailController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', '$location', '$rootScope', ConfirmEmailController]); - - function ConfirmEmailController(dataContext, logger, $location, $rootScope) { - - // Logger - logger = logger.forSource(controllerId); - - var vm = this; - vm.currentUser = { EmailConfirmed: false, isAuthenticated: function () { return false; } }; - vm.isResendDisabled = false; - vm.resendConfirmationEmail = resendConfirmationEmail; - - _init(); - - /*** Implementations ***/ - - function _init() { - - vm.currentUser = dataContext.getCurrentUser(); - - if (!vm.currentUser.isAuthenticated()) { - return; - } - - // If there is no token, no need to continue - var token = $location.search().token; - if (typeof token === 'undefined') { - return; - } - - dataContext.confirmEmail({ Token: token }) - .then(function () { - logger.logSuccess('Your email address has been confirmed!', null, true); - $location.url('/_system/account'); - }); - } - - function resendConfirmationEmail() { - - vm.isResendDisabled = true; - - dataContext.resendConfirmationEmail() - .then(function () { - logger.logSuccess('Confirmation email has been resent to your email address!', null, true); - }) - .finally(function () { - vm.isResendDisabled = false; - }); - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/account/ConfirmEmailController.ts b/ngClient/_system/js/app/controllers/account/ConfirmEmailController.ts new file mode 100644 index 000000000..081cb18f1 --- /dev/null +++ b/ngClient/_system/js/app/controllers/account/ConfirmEmailController.ts @@ -0,0 +1,66 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'ConfirmEmailController'; + + export class ConfirmEmailController { + + static $inject = ['dataContext', 'logger', '$location', '$rootScope']; + + constructor(dataContext: any, logger: any, $location: any, $rootScope: any) { + + // Logger + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.currentUser = { + EmailConfirmed: false, + isAuthenticated() { + return false; + } + }; + vm.isResendDisabled = false; + vm.resendConfirmationEmail = resendConfirmationEmail; + + _init(); + + /*** Implementations ***/ + + function _init() { + + vm.currentUser = dataContext.getCurrentUser(); + + if (!vm.currentUser.isAuthenticated()) { + return; + } + + // If there is no token, no need to continue + var token = $location.search().token; + if (typeof token === 'undefined') { + return; + } + + dataContext.confirmEmail({ Token: token }) + .then(() => { + logger.logSuccess('Your email address has been confirmed!', null, true); + $location.url('/_system/account'); + }); + } + + function resendConfirmationEmail() { + + vm.isResendDisabled = true; + + dataContext.resendConfirmationEmail() + .then(() => { + logger.logSuccess('Confirmation email has been resent to your email address!', null, true); + }) + .finally(() => { + vm.isResendDisabled = false; + }); + } + } + } + + angular.module('main').controller(controllerId, ConfirmEmailController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/account/LoginController.js b/ngClient/_system/js/app/controllers/account/LoginController.js deleted file mode 100644 index cc3462ef4..000000000 --- a/ngClient/_system/js/app/controllers/account/LoginController.js +++ /dev/null @@ -1,88 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'LoginController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'locationHistory', 'logger', 'serviceAppUrl', '$location', '$rootScope', '$scope', LoginController]); - - function LoginController(dataContext, locationHistory, logger, serviceAppUrl, $location, $rootScope, $scope) { - logger = logger.forSource(controllerId); - - var vm = this; - vm.isSaving = false; - vm.isSaveDisabled = isSaveDisabled; - vm.login = login; - vm.password = ''; - vm.rememberMe = true; - vm.showHeader = typeof $scope.showHeader !== 'undefined' ? $scope.showHeader : true; - vm.userName = ''; - - _init(); - - function _init() { - - // Error - var error = $location.search().error; - if (typeof error !== 'undefined') { - logger.logError(error, null, true); - return; - } - - login(); - } - - function getReturnUrl() { - // If login pages called after a result from server, it will have "clientReturnUrl" param, which will have a higher priority than locationHistory - var clientReturnUrl = $location.search().clientReturnUrl; - return typeof clientReturnUrl !== 'undefined' ? clientReturnUrl : locationHistory.previousItem().url(); - } - - function isSaveDisabled() { - return vm.isSaving; - } - - function login() { - - // External (single use token) login - var singleUseToken = $location.search().token; - var init = $location.search().init; - if (typeof singleUseToken !== 'undefined') { - vm.isSaving = true; - dataContext.login('', '', vm.rememberMe, singleUseToken).then(successExternal).catch(failedExternal).finally(function () { - vm.isSaving = false; - }); - } else { // Internal login - if (vm.userName !== '' && vm.password !== '') { - vm.isSaving = true; - dataContext.login(vm.userName, vm.password, vm.rememberMe).then(successInternal).finally(function () { - vm.isSaving = false; - }); - } - } - - function failedExternal() { - logger.logError('Invalid token', null, true); - } - - function successExternal() { - logger.logSuccess('You have been logged in!', null, true); - - // First time - if (typeof init !== 'undefined' && init) { - var url = '/_system/account/changeUserName?init=true&clientReturnUrl=' + getReturnUrl(); - $location.url(url); - } else { - $location.url(getReturnUrl()); - } - } - - function successInternal() { - logger.logSuccess('You have been logged in!', null, true); - - if ($location.path() === '/_system/account/login') { - $location.url(getReturnUrl()); - } - } - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/account/LoginController.ts b/ngClient/_system/js/app/controllers/account/LoginController.ts new file mode 100644 index 000000000..e0103fd0e --- /dev/null +++ b/ngClient/_system/js/app/controllers/account/LoginController.ts @@ -0,0 +1,105 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'LoginController'; + + export class LoginController { + + static $inject = ['dataContext', 'locationHistory', 'logger', 'serviceAppUrl', '$location', '$rootScope', '$scope']; + + constructor(dataContext: any, + locationHistory: any, + logger: any, + serviceAppUrl: any, + $location: any, + $rootScope: any, + $scope: any) { + + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.isSaving = false; + vm.isSaveDisabled = isSaveDisabled; + vm.login = login; + vm.password = ''; + vm.rememberMe = true; + vm.showHeader = typeof $scope.showHeader !== 'undefined' ? $scope.showHeader : true; + vm.userName = ''; + + _init(); + + function _init() { + + // Error + var error = $location.search().error; + if (typeof error !== 'undefined') { + logger.logError(error, null, true); + return; + } + + login(); + } + + function getReturnUrl() { + // If login pages called after a result from server, it will have "clientReturnUrl" param, which will have a higher priority than locationHistory + var clientReturnUrl = $location.search().clientReturnUrl; + return typeof clientReturnUrl !== 'undefined' ? clientReturnUrl : locationHistory.previousItem().url(); + } + + function isSaveDisabled() { + return vm.isSaving; + } + + function login() { + + // External (single use token) login + var singleUseToken = $location.search().token; + var init = $location.search().init; + if (typeof singleUseToken !== 'undefined') { + vm.isSaving = true; + dataContext.login('', '', vm.rememberMe, singleUseToken) + .then(successExternal) + .catch(failedExternal) + .finally(() => { + vm.isSaving = false; + }); + } else { // Internal login + if (vm.userName !== '' && vm.password !== '') { + vm.isSaving = true; + dataContext.login(vm.userName, vm.password, vm.rememberMe) + .then(successInternal) + .finally(() => { + vm.isSaving = false; + }); + } + } + + function failedExternal() { + logger.logError('Invalid token', null, true); + } + + function successExternal() { + logger.logSuccess('You have been logged in!', null, true); + + // First time + if (typeof init !== 'undefined' && init) { + var url = '/_system/account/changeUserName?init=true&clientReturnUrl=' + getReturnUrl(); + $location.url(url); + } else { + $location.url(getReturnUrl()); + } + } + + function successInternal() { + logger.logSuccess('You have been logged in!', null, true); + + if ($location.path() === '/_system/account/login') { + $location.url(getReturnUrl()); + } + } + } + } + } + + angular.module('main').controller(controllerId, LoginController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/account/ProfileController.js b/ngClient/_system/js/app/controllers/account/ProfileController.js deleted file mode 100644 index 7e7abdddb..000000000 --- a/ngClient/_system/js/app/controllers/account/ProfileController.js +++ /dev/null @@ -1,51 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'ProfileController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', '$location', '$routeParams', '$scope', ProfileController]); - - function ProfileController(dataContext, logger, $location, $routeParams, $scope) { - - // Logger - logger = logger.forSource(controllerId); - - var userName = $routeParams.userName; - var vm = this; - vm.currentUser = { Id: 0 }; - vm.user = { Id: 0, UserName: '', Email: '' }; - - // Events - $scope.$on('dataContext_currentUserChanged', currentUserChanged); - - _init(); - - function _init() { - - vm.currentUser = dataContext.getCurrentUser(); - - // If userName equals to current user - if (userName === vm.currentUser.UserName) { - vm.user = vm.currentUser; - } else { - - // If not, then check it against remote - dataContext.getUser(userName) - .then(function (user) { - - // Not found, navigate to 404 - if (user === null) { - $location.url('/_system/content/notFound?url=' + $location.url()); - return; - } - - vm.user = user; - }); - } - } - - function currentUserChanged(event, newUser) { - vm.currentUser = newUser; - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/account/ProfileController.ts b/ngClient/_system/js/app/controllers/account/ProfileController.ts new file mode 100644 index 000000000..2a4fb1e04 --- /dev/null +++ b/ngClient/_system/js/app/controllers/account/ProfileController.ts @@ -0,0 +1,57 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'ProfileController'; + + export class ProfileController { + + static $inject = ['dataContext', 'logger', '$location', '$routeParams', '$scope']; + + constructor(dataContext: any, logger: any, $location: any, $routeParams: any, $scope: any) { + + // Logger + logger = logger.forSource(controllerId); + + var userName = $routeParams.userName; + var vm:any = this; + vm.currentUser = { Id: 0 }; + vm.user = { Id: 0, UserName: '', Email: '' }; + + // Events + $scope.$on('dataContext_currentUserChanged', currentUserChanged); + + _init(); + + function _init() { + + vm.currentUser = dataContext.getCurrentUser(); + + // If userName equals to current user + if (userName === vm.currentUser.UserName) { + vm.user = vm.currentUser; + } else { + + // If not, then check it against remote + dataContext.getUser(userName) + .then(user => { + + // Not found, navigate to 404 + if (user === null) { + $location.url('/_system/content/notFound?url=' + $location.url()); + return; + } + + vm.user = user; + }); + } + } + + function currentUserChanged(event: any, newUser: any); + function currentUserChanged(event, newUser) { + vm.currentUser = newUser; + } + } + } + + angular.module('main').controller(controllerId, ProfileController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/account/RegisterController.js b/ngClient/_system/js/app/controllers/account/RegisterController.js deleted file mode 100644 index 7d8049313..000000000 --- a/ngClient/_system/js/app/controllers/account/RegisterController.js +++ /dev/null @@ -1,51 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'RegisterController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'locationHistory', 'logger', 'serviceAppUrl', '$location', '$rootScope', '$scope', RegisterController]); - - function RegisterController(dataContext, locationHistory, logger, serviceAppUrl, $location, $rootScope, $scope) { - - // Logger - logger = logger.forSource(controllerId); - - var vm = this; - vm.bindingModel = { - UserName: '', - Email: '', - Password: '', - ConfirmPassword: '' - }; - vm.isSaving = false; - vm.isSaveDisabled = isSaveDisabled; - vm.register = register; - vm.rememberMe = true; - vm.showHeader = typeof $scope.showHeader !== 'undefined' ? $scope.showHeader : true; - - function isSaveDisabled() { - return vm.isSaving; - } - - function register() { - - vm.isSaving = true; - - dataContext.register(vm.bindingModel, vm.rememberMe) - .then(function () { - logger.logSuccess('You have been registered!', null, true); - $location.url('/_system/account/confirmEmail'); - }) - .catch(failed) - .finally(function () { - vm.isSaving = false; - }); - - function failed(response) { - if (typeof response.error_description !== 'undefined') { - logger.logError(response.error_description, null, true); - } - } - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/account/RegisterController.ts b/ngClient/_system/js/app/controllers/account/RegisterController.ts new file mode 100644 index 000000000..f716156e3 --- /dev/null +++ b/ngClient/_system/js/app/controllers/account/RegisterController.ts @@ -0,0 +1,65 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'RegisterController'; + + export class RegisterController { + + static $inject = [ + 'dataContext', 'locationHistory', 'logger', 'serviceAppUrl', '$location', '$rootScope', '$scope' + ]; + + constructor(dataContext: any, + locationHistory: any, + logger: any, + serviceAppUrl: any, + $location: any, + $rootScope: any, + $scope: any) { + + // Logger + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.bindingModel = { + UserName: '', + Email: '', + Password: '', + ConfirmPassword: '' + }; + vm.isSaving = false; + vm.isSaveDisabled = isSaveDisabled; + vm.register = register; + vm.rememberMe = true; + vm.showHeader = typeof $scope.showHeader !== 'undefined' ? $scope.showHeader : true; + + function isSaveDisabled() { + return vm.isSaving; + } + + function register() { + + vm.isSaving = true; + + dataContext.register(vm.bindingModel, vm.rememberMe) + .then(() => { + logger.logSuccess('You have been registered!', null, true); + $location.url('/_system/account/confirmEmail'); + }) + .catch(failed) + .finally(() => { + vm.isSaving = false; + }); + + function failed(response: any); + function failed(response) { + if (typeof response.error_description !== 'undefined') { + logger.logError(response.error_description, null, true); + } + } + } + } + } + + angular.module('main').controller(controllerId, RegisterController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/account/ResetPasswordController.js b/ngClient/_system/js/app/controllers/account/ResetPasswordController.js deleted file mode 100644 index c8fcd035b..000000000 --- a/ngClient/_system/js/app/controllers/account/ResetPasswordController.js +++ /dev/null @@ -1,62 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'ResetPasswordController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', '$location', ResetPasswordController]); - - function ResetPasswordController(dataContext, logger, $location) { - logger = logger.forSource(controllerId); - - var vm = this; - vm.bindingModel = { - Email: $location.search().email, - Token: $location.search().token, - NewPassword: '', - ConfirmPassword: '' - }; - vm.isSaving = false; - vm.isSaveDisabled = isSaveDisabled; - vm.requestBindingModel = { - Email: '' - }; - vm.resetPassword = resetPassword; - vm.resetPasswordRequest = resetPasswordRequest; - vm.viewMode = typeof $location.search().email === 'undefined' || typeof $location.search().token === 'undefined' ? - 'initial' : - 'received'; // initial | sent | received - - /*** Implementations ***/ - - function isSaveDisabled() { - return vm.isSaving; - } - - function resetPassword() { - - vm.isSaving = true; - - dataContext.resetPassword(vm.bindingModel) - .success(function () { - logger.logSuccess('Your password has been reset!', null, true); - $location.url('/_system/account/login'); - }) - .finally(function () { - vm.isSaving = false; - }); - } - - function resetPasswordRequest() { - - vm.isSaving = true; - - dataContext.resetPasswordRequest(vm.requestBindingModel) - .success(function () { - vm.viewMode = 'sent'; - }) - .finally(function () { - vm.isSaving = false; - }); - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/account/ResetPasswordController.ts b/ngClient/_system/js/app/controllers/account/ResetPasswordController.ts new file mode 100644 index 000000000..e76e8963e --- /dev/null +++ b/ngClient/_system/js/app/controllers/account/ResetPasswordController.ts @@ -0,0 +1,69 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'ResetPasswordController'; + + export class ResetPasswordController { + + static $inject = ['dataContext', 'logger', '$location']; + + constructor(dataContext: any, logger: any, $location: any) { + + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.bindingModel = { + Email: $location.search().email, + Token: $location.search().token, + NewPassword: '', + ConfirmPassword: '' + }; + vm.isSaving = false; + vm.isSaveDisabled = isSaveDisabled; + vm.requestBindingModel = { + Email: '' + }; + vm.resetPassword = resetPassword; + vm.resetPasswordRequest = resetPasswordRequest; + vm.viewMode = typeof $location.search().email === 'undefined' || + typeof $location.search().token === 'undefined' + ? 'initial' + : 'received'; // initial | sent | received + + /*** Implementations ***/ + + function isSaveDisabled() { + return vm.isSaving; + } + + function resetPassword() { + + vm.isSaving = true; + + dataContext.resetPassword(vm.bindingModel) + .success(() => { + logger.logSuccess('Your password has been reset!', null, true); + $location.url('/_system/account/login'); + }) + .finally(() => { + vm.isSaving = false; + }); + } + + function resetPasswordRequest() { + + vm.isSaving = true; + + dataContext.resetPasswordRequest(vm.requestBindingModel) + .success(() => { + vm.viewMode = 'sent'; + }) + .finally(() => { + vm.isSaving = false; + }); + } + } + } + + angular.module('main').controller(controllerId, ResetPasswordController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/account/SocialLoginsController.js b/ngClient/_system/js/app/controllers/account/SocialLoginsController.js deleted file mode 100644 index 689e99942..000000000 --- a/ngClient/_system/js/app/controllers/account/SocialLoginsController.js +++ /dev/null @@ -1,26 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'SocialLoginsController'; - angular.module('main') - .controller(controllerId, ['locationHistory', 'logger', 'serviceAppUrl', '$location', SocialLoginsController]); - - function SocialLoginsController(locationHistory, logger, serviceAppUrl, $location) { - - // Logger - logger = logger.forSource(controllerId); - - var vm = this; - vm.getExternalLoginUrl = getExternalLoginUrl; - - function getExternalLoginUrl(provider) { - return serviceAppUrl + '/api/Account/ExternalLogin?provider=' + provider + '&clientReturnUrl=' + getReturnUrl(); - } - - function getReturnUrl() { - // If login pages called after a result from server, it will have "clientReturnUrl" param, which will have a higher priority than locationHistory - var clientReturnUrl = $location.search().clientReturnUrl; - return typeof clientReturnUrl !== 'undefined' ? clientReturnUrl : locationHistory.previousItem().url(); - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/account/SocialLoginsController.ts b/ngClient/_system/js/app/controllers/account/SocialLoginsController.ts new file mode 100644 index 000000000..80b13382b --- /dev/null +++ b/ngClient/_system/js/app/controllers/account/SocialLoginsController.ts @@ -0,0 +1,36 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'SocialLoginsController'; + + export class SocialLoginsController { + + static $inject = ['locationHistory', 'logger', 'serviceAppUrl', '$location']; + + constructor(locationHistory: any, logger: any, serviceAppUrl: any, $location: any) { + + // Logger + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.getExternalLoginUrl = getExternalLoginUrl; + + function getExternalLoginUrl(provider: any); + function getExternalLoginUrl(provider) { + return serviceAppUrl + + '/api/Account/ExternalLogin?provider=' + + provider + + '&clientReturnUrl=' + + getReturnUrl(); + } + + function getReturnUrl() { + // If login pages called after a result from server, it will have "clientReturnUrl" param, which will have a higher priority than locationHistory + var clientReturnUrl = $location.search().clientReturnUrl; + return typeof clientReturnUrl !== 'undefined' ? clientReturnUrl : locationHistory.previousItem().url(); + } + } + } + + angular.module('main').controller(controllerId, SocialLoginsController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/content/AllInOneController.js b/ngClient/_system/js/app/controllers/content/AllInOneController.js deleted file mode 100644 index 372ec7dc1..000000000 --- a/ngClient/_system/js/app/controllers/content/AllInOneController.js +++ /dev/null @@ -1,60 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'AllInOneController'; - angular.module('main') - .controller(controllerId, ['logger', 'resourcePoolFactory', '$scope', AllInOneController]); - - function AllInOneController(logger, resourcePoolFactory, $scope) { - - logger = logger.forSource(controllerId); - - var vm = this; - vm.allInOneConfig = { userName: 'sample', resourcePoolKey: 'All-in-One' }; - - // Event listeners - $scope.$on('resourcePoolEditor_elementCellNumericValueIncreased', processNewInteraction); - $scope.$on('resourcePoolEditor_elementCellNumericValueDecreased', processNewInteraction); - $scope.$on('resourcePoolEditor_elementCellNumericValueReset', processNewInteraction); - - _init(); - - function _init() { - processExistingInteraction(); - } - - // Processes whether the current user had already interacted with this example - function processExistingInteraction() { - // Priority & Knowledge Index examples copy their ratings to this one - // However if the user starts directly playing .. - resourcePoolFactory.getResourcePoolExpanded(vm.allInOneConfig) - .then(function (resourcePool) { - // Elements - for (var elementIndex = 0; elementIndex < resourcePool.ElementSet.length; elementIndex++) { - var element = resourcePool.ElementSet[elementIndex]; - // Element fields - for (var elementFieldIndex = 0; elementFieldIndex < element.ElementFieldSet.length; elementFieldIndex++) { - var elementField = element.ElementFieldSet[elementFieldIndex]; - // Element cells - for (var elementCellIndex = 0; elementCellIndex < elementField.ElementCellSet.length; elementCellIndex++) { - var elementCell = elementField.ElementCellSet[elementCellIndex]; - - if (elementCell.currentUserCell()) { - resourcePool.userInteracted = true; - return; - } - } - } - } - }); - } - - // Processes whether the user is currently interacting with this example - function processNewInteraction(event, cell) { - if (cell.ElementField.Element.ResourcePool.User.UserName === vm.allInOneConfig.userName && cell.ElementField.Element.ResourcePool.Key === vm.allInOneConfig.resourcePoolKey) { - cell.ElementField.Element.ResourcePool.userInteracted = true; - return; - } - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/content/AllInOneController.ts b/ngClient/_system/js/app/controllers/content/AllInOneController.ts new file mode 100644 index 000000000..34c7b55bc --- /dev/null +++ b/ngClient/_system/js/app/controllers/content/AllInOneController.ts @@ -0,0 +1,71 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'AllInOneController'; + + export class AllInOneController { + + static $inject = ['logger', 'resourcePoolFactory', '$scope']; + + constructor(logger: any, resourcePoolFactory: any, $scope: any) { + + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.allInOneConfig = { userName: 'sample', resourcePoolKey: 'All-in-One' }; + + // Event listeners + $scope.$on('resourcePoolEditor_elementCellNumericValueIncreased', processNewInteraction); + $scope.$on('resourcePoolEditor_elementCellNumericValueDecreased', processNewInteraction); + $scope.$on('resourcePoolEditor_elementCellNumericValueReset', processNewInteraction); + + _init(); + + function _init() { + processExistingInteraction(); + } + + // Processes whether the current user had already interacted with this example + function processExistingInteraction() { + // Priority & Knowledge Index examples copy their ratings to this one + // However if the user starts directly playing .. + resourcePoolFactory.getResourcePoolExpanded(vm.allInOneConfig) + .then(resourcePool => { + // Elements + for (var elementIndex = 0; elementIndex < resourcePool.ElementSet.length; elementIndex++) { + var element = resourcePool.ElementSet[elementIndex]; + // Element fields + for (var elementFieldIndex = 0; + elementFieldIndex < element.ElementFieldSet.length; + elementFieldIndex++) { + var elementField = element.ElementFieldSet[elementFieldIndex]; + // Element cells + for (var elementCellIndex = 0; + elementCellIndex < elementField.ElementCellSet.length; + elementCellIndex++) { + var elementCell = elementField.ElementCellSet[elementCellIndex]; + + if (elementCell.currentUserCell()) { + resourcePool.userInteracted = true; + return; + } + } + } + } + }); + } + + // Processes whether the user is currently interacting with this example + function processNewInteraction(event: any, cell: any); + function processNewInteraction(event, cell) { + if (cell.ElementField.Element.ResourcePool.User.UserName === vm.allInOneConfig.userName && + cell.ElementField.Element.ResourcePool.Key === vm.allInOneConfig.resourcePoolKey) { + cell.ElementField.Element.ResourcePool.userInteracted = true; + return; + } + } + } + } + + angular.module('main').controller(controllerId, AllInOneController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/content/BasicsController.js b/ngClient/_system/js/app/controllers/content/BasicsController.js deleted file mode 100644 index 6bc6bc540..000000000 --- a/ngClient/_system/js/app/controllers/content/BasicsController.js +++ /dev/null @@ -1,59 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'BasicsController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', 'resourcePoolFactory', '$scope', BasicsController]); - - function BasicsController(dataContext, logger, resourcePoolFactory, $scope) { - - // Logger - logger = logger.forSource(controllerId); - - var vm = this; - vm.existingModelConfig = { userName: 'sample', resourcePoolKey: 'Basics-Existing-Model' }; - vm.newModelConfig = { userName: 'sample', resourcePoolKey: 'Basics-New-Model' }; - - // Listen resource pool updated event - $scope.$on('resourcePoolEditor_elementMultiplierIncreased', updateOppositeResourcePool); - $scope.$on('resourcePoolEditor_elementMultiplierDecreased', updateOppositeResourcePool); - $scope.$on('resourcePoolEditor_elementMultiplierReset', updateOppositeResourcePool); - - /*** Implementations ***/ - - function updateOppositeResourcePool(event, element) { - - var oppositeKey = null; - - if (element.ResourcePool.User.UserName === vm.existingModelConfig.userName && element.ResourcePool.Key === vm.existingModelConfig.resourcePoolKey) { - oppositeKey = vm.newModelConfig; - } else if (element.ResourcePool.User.UserName === vm.newModelConfig.userName && element.ResourcePool.Key === vm.newModelConfig.resourcePoolKey) { - oppositeKey = vm.existingModelConfig; - } - - // Call the service to increase the multiplier - if (oppositeKey !== null) { - resourcePoolFactory.getResourcePoolExpanded(oppositeKey) - .then(function (resourcePool) { - - switch (event.name) { - case 'resourcePoolEditor_elementMultiplierIncreased': { - resourcePoolFactory.updateElementMultiplier(resourcePool.mainElement(), 'increase'); - break; - } - case 'resourcePoolEditor_elementMultiplierDecreased': { - resourcePoolFactory.updateElementMultiplier(resourcePool.mainElement(), 'decrease'); - break; - } - case 'resourcePoolEditor_elementMultiplierReset': { - resourcePoolFactory.updateElementMultiplier(resourcePool.mainElement(), 'reset'); - break; - } - } - - dataContext.saveChanges(1500); - }); - } - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/content/BasicsController.ts b/ngClient/_system/js/app/controllers/content/BasicsController.ts new file mode 100644 index 000000000..8f9ee2484 --- /dev/null +++ b/ngClient/_system/js/app/controllers/content/BasicsController.ts @@ -0,0 +1,70 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'BasicsController'; + + export class BasicsController { + + static $inject = ['dataContext', 'logger', 'resourcePoolFactory', '$scope']; + + constructor(dataContext: any, logger: any, resourcePoolFactory: any, $scope: any) { + + // Logger + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.existingModelConfig = { userName: 'sample', resourcePoolKey: 'Basics-Existing-Model' }; + vm.newModelConfig = { userName: 'sample', resourcePoolKey: 'Basics-New-Model' }; + + // Listen resource pool updated event + $scope.$on('resourcePoolEditor_elementMultiplierIncreased', updateOppositeResourcePool); + $scope.$on('resourcePoolEditor_elementMultiplierDecreased', updateOppositeResourcePool); + $scope.$on('resourcePoolEditor_elementMultiplierReset', updateOppositeResourcePool); + + /*** Implementations ***/ + + function updateOppositeResourcePool(event: any, element: any); + function updateOppositeResourcePool(event, element) { + + var oppositeKey = null; + + if (element.ResourcePool.User.UserName === vm.existingModelConfig.userName && + element.ResourcePool.Key === vm.existingModelConfig.resourcePoolKey) { + oppositeKey = vm.newModelConfig; + } else if (element.ResourcePool.User.UserName === vm.newModelConfig.userName && + element.ResourcePool.Key === vm.newModelConfig.resourcePoolKey) { + oppositeKey = vm.existingModelConfig; + } + + // Call the service to increase the multiplier + if (oppositeKey !== null) { + resourcePoolFactory.getResourcePoolExpanded(oppositeKey) + .then(resourcePool => { + + switch (event.name) { + case 'resourcePoolEditor_elementMultiplierIncreased': + { + resourcePoolFactory.updateElementMultiplier(resourcePool.mainElement(), 'increase'); + break; + } + case 'resourcePoolEditor_elementMultiplierDecreased': + { + resourcePoolFactory.updateElementMultiplier(resourcePool.mainElement(), 'decrease'); + break; + } + case 'resourcePoolEditor_elementMultiplierReset': + { + resourcePoolFactory.updateElementMultiplier(resourcePool.mainElement(), 'reset'); + break; + } + } + + dataContext.saveChanges(1500); + }); + } + } + } + } + + angular.module('main').controller(controllerId, BasicsController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/content/ContributorsController.js b/ngClient/_system/js/app/controllers/content/ContributorsController.js deleted file mode 100644 index dc0d72637..000000000 --- a/ngClient/_system/js/app/controllers/content/ContributorsController.js +++ /dev/null @@ -1,20 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'ContributorsController'; - angular.module('main') - .controller(controllerId, ['logger', ContributorsController]); - - function ContributorsController(logger) { - - // Logger - logger = logger.forSource(controllerId); - - var vm = this; - vm.getDate = getDate; - - function getDate(day, month, year) { - return new Date(year, month - 1, day); - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/content/ContributorsController.ts b/ngClient/_system/js/app/controllers/content/ContributorsController.ts new file mode 100644 index 000000000..ffb74007f --- /dev/null +++ b/ngClient/_system/js/app/controllers/content/ContributorsController.ts @@ -0,0 +1,25 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'ContributorsController'; + + export class ContributorsController { + + static $inject = ['logger']; + + constructor(logger: any) { + + // Logger + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.getDate = getDate; + + function getDate(day: any, month: any, year: any) { + return new Date(year, month - 2, day); + } + } + } + + angular.module('main').controller(controllerId, ContributorsController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/content/DefaultController.js b/ngClient/_system/js/app/controllers/content/DefaultController.js deleted file mode 100644 index c1c7c31da..000000000 --- a/ngClient/_system/js/app/controllers/content/DefaultController.js +++ /dev/null @@ -1,161 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'DefaultController'; - angular.module('main') - .controller(controllerId, ['applicationFactory', 'dataContext', 'disqusShortname', 'logger', '$location', '$rootScope', '$scope', '$uibModal', DefaultController]); - - function DefaultController(applicationFactory, dataContext, disqusShortname, logger, $location, $rootScope, $scope, $uibModal) { - - // Logger - logger = logger.forSource(controllerId); - - // View model - var vm = this; - vm.applicationInfo = null; - vm.currentUser = { Email: '', isAuthenticated: function () { return false; }, HasPassword: false }; - vm.currentDate = new Date(); - vm.currentUserText = currentUserText; - vm.displayBankTransfer = false; - vm.displayFooterIcons = false; - vm.disqusConfig = { - disqus_shortname: disqusShortname, - disqus_identifier: '', - disqus_url: '' - }; - vm.guestAccountInfoVisible = false; - vm.logout = logout; - vm.openGuestAccountInfo = openGuestAccountInfo; - vm.toggleBankTransfer = toggleBankTransfer; - - // Events - $scope.$on('dataContext_currentUserChanged', currentUserChanged); - $scope.$on('dataContext_currentUserEmailAddressChanged', currentUserEmailAddressChanged); - $scope.$on('guestAccountCreated', guestAccountCreated); - $scope.$on('$locationChangeStart', locationChangeStart); - $scope.$on('$routeChangeSuccess', routeChangeSuccess); - - _init(); - - /*** Implementations ***/ - - function _init() { - getApplicationInfo(); - } - - function currentUserChanged(event, newUser) { - vm.currentUser = newUser; - vm.guestAccountInfoVisible = newUser.isAuthenticated() && newUser.IsAnonymous; - } - - function currentUserText() { - var userText = vm.currentUser.UserName; - - if (vm.currentUser.IsAnonymous) { - userText += ' (Guest)'; - } - - return userText; - } - - function currentUserEmailAddressChanged() { - vm.guestAccountInfoVisible = false; - } - - function getApplicationInfo() { - applicationFactory.getApplicationInfo() - .then(function (applicationInfo) { - vm.applicationInfo = applicationInfo; - vm.applicationInfo.CurrentVersionText = vm.applicationInfo.CurrentVersion + ' - Alpha ~ Beta'; - }); - } - - function guestAccountCreated() { - vm.guestAccountInfoVisible = true; - } - - function logout() { - dataContext.logout() - .then(function () { - $location.url('/'); - }); - } - - function locationChangeStart(event, newUrl, oldUrl) { - - if (dataContext.hasChanges()) { - - var modalInstance = $uibModal.open({ - controller: ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) { - - var vm = this; - vm.cancel = cancel; - vm.leave = leave; - - function cancel() { - $uibModalInstance.dismiss('cancel'); - } - - function leave() { - $uibModalInstance.close(); - } - }], - controllerAs: 'vm', - templateUrl: '/_system/views/account/confirmNavigateAway.html?v=0.53.0' - }); - - modalInstance.result.then(function () { - - // User choose to cancel the changes & navigate away - dataContext.rejectChanges(); - $location.path(newUrl.substring($location.absUrl().length - $location.url().length)); - - }, function () { }); - - // Always cancel route changes - event.preventDefault(); - return; - } - } - - function openGuestAccountInfo() { - - var modalInstance = $uibModal.open({ - controller: ['$scope', '$uibModalInstance', function ($scope, $uibModalInstance) { - - var vm = this; - vm.close = closeModal; - - $scope.$on('dataContext_currentUserChanged', closeModal); - - function closeModal() { - $uibModalInstance.close(); - } - }], - controllerAs: 'vm', - templateUrl: '/_system/views/account/guestAccountInfo.html?v=0.58.0' - }); - - modalInstance.result.then(function () { }, - function () { }); - } - - function routeChangeSuccess(event, current, previous) { - - // Footer icons - vm.displayFooterIcons = $location.path() === '/'; - - // Load related disqus - if (typeof current.enableDisqus !== 'undefined' && current.enableDisqus && vm.disqusConfig.disqus_shortname !== '') { - vm.disqusConfig.disqus_identifier = vm.disqusConfig.disqus_shortname + $location.path().replace(/\//g, '_'); - vm.disqusConfig.disqus_url = $location.absUrl().substring(0, $location.absUrl().length - $location.url().length + $location.path().length); - } else { - vm.disqusConfig.disqus_identifier = ''; - } - } - - function toggleBankTransfer() { - vm.displayBankTransfer = !vm.displayBankTransfer; - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/content/DefaultController.ts b/ngClient/_system/js/app/controllers/content/DefaultController.ts new file mode 100644 index 000000000..35ed48892 --- /dev/null +++ b/ngClient/_system/js/app/controllers/content/DefaultController.ts @@ -0,0 +1,193 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'DefaultController'; + + export class DefaultController { + + static $inject = [ + 'applicationFactory', 'dataContext', 'disqusShortname', 'logger', '$location', '$rootScope', '$scope', + '$uibModal' + ]; + + constructor(applicationFactory: any, + dataContext: any, + disqusShortname: any, + logger: any, + $location: any, + $rootScope: any, + $scope: any, + $uibModal: any) { + // Logger + logger = logger.forSource(controllerId); + + // View model + var vm:any = this; + vm.applicationInfo = null; + vm.currentUser = { + Email: '', + isAuthenticated() { + return false; + }, + HasPassword: false + }; + vm.currentDate = new Date(); + vm.currentUserText = currentUserText; + vm.displayBankTransfer = false; + vm.displayFooterIcons = false; + vm.disqusConfig = { + disqus_shortname: disqusShortname, + disqus_identifier: '', + disqus_url: '' + }; + vm.guestAccountInfoVisible = false; + vm.logout = logout; + vm.openGuestAccountInfo = openGuestAccountInfo; + vm.toggleBankTransfer = toggleBankTransfer; + + // Events + $scope.$on('dataContext_currentUserChanged', currentUserChanged); + $scope.$on('dataContext_currentUserEmailAddressChanged', currentUserEmailAddressChanged); + $scope.$on('guestAccountCreated', guestAccountCreated); + $scope.$on('$locationChangeStart', locationChangeStart); + $scope.$on('$routeChangeSuccess', routeChangeSuccess); + + _init(); + + /*** Implementations ***/ + + function _init() { + getApplicationInfo(); + } + + function currentUserChanged(event: any, newUser: any); + function currentUserChanged(event, newUser) { + vm.currentUser = newUser; + vm.guestAccountInfoVisible = newUser.isAuthenticated() && newUser.IsAnonymous; + } + + function currentUserText() { + var userText = vm.currentUser.UserName; + + if (vm.currentUser.IsAnonymous) { + userText += ' (Guest)'; + } + + return userText; + } + + function currentUserEmailAddressChanged() { + vm.guestAccountInfoVisible = false; + } + + function getApplicationInfo() { + applicationFactory.getApplicationInfo() + .then(applicationInfo => { + vm.applicationInfo = applicationInfo; + vm.applicationInfo.CurrentVersionText = vm.applicationInfo.CurrentVersion + ' - Alpha ~ Beta'; + }); + } + + function guestAccountCreated() { + vm.guestAccountInfoVisible = true; + } + + function logout() { + dataContext.logout() + .then(() => { + $location.url('/'); + }); + } + + function locationChangeStart(event: any, newUrl: any, oldUrl: any); + function locationChangeStart(event, newUrl, oldUrl) { + + if (dataContext.hasChanges()) { + + var modalInstance = $uibModal.open({ + controller: [ + '$scope', '$uibModalInstance', function($scope, $uibModalInstance) { + + var vm:any = this; + vm.cancel = cancel; + vm.leave = leave; + + function cancel() { + $uibModalInstance.dismiss('cancel'); + } + + function leave() { + $uibModalInstance.close(); + } + } + ], + controllerAs: 'vm', + templateUrl: '/_system/views/account/confirmNavigateAway.html?v=0.53.0' + }); + + modalInstance.result.then(() => { + + // User choose to cancel the changes & navigate away + dataContext.rejectChanges(); + $location.path(newUrl.substring($location.absUrl().length - $location.url().length)); + + }, + () => {}); + + // Always cancel route changes + event.preventDefault(); + return; + } + } + + function openGuestAccountInfo() { + + var modalInstance = $uibModal.open({ + controller: [ + '$scope', '$uibModalInstance', function($scope, $uibModalInstance) { + + var vm:any = this; + vm.close = closeModal; + + $scope.$on('dataContext_currentUserChanged', closeModal); + + function closeModal() { + $uibModalInstance.close(); + } + } + ], + controllerAs: 'vm', + templateUrl: '/_system/views/account/guestAccountInfo.html?v=0.58.0' + }); + + modalInstance.result.then(() => {}, + () => {}); + } + + function routeChangeSuccess(event: any, current: any, previous: any); + function routeChangeSuccess(event, current, previous) { + + // Footer icons + vm.displayFooterIcons = $location.path() === '/'; + + // Load related disqus + if (typeof current.enableDisqus !== 'undefined' && + current.enableDisqus && + vm.disqusConfig.disqus_shortname !== '') { + vm.disqusConfig.disqus_identifier = vm.disqusConfig.disqus_shortname + + $location.path().replace(/\//g, '_'); + vm.disqusConfig.disqus_url = $location.absUrl() + .substring(0, $location.absUrl().length - $location.url().length + $location.path().length); + } else { + vm.disqusConfig.disqus_identifier = ''; + } + } + + function toggleBankTransfer() { + vm.displayBankTransfer = !vm.displayBankTransfer; + } + } + } + + angular.module('main').controller(controllerId, DefaultController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/content/IntroductionController.js b/ngClient/_system/js/app/controllers/content/IntroductionController.js deleted file mode 100644 index 7db02275e..000000000 --- a/ngClient/_system/js/app/controllers/content/IntroductionController.js +++ /dev/null @@ -1,49 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'IntroductionController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', 'resourcePoolFactory', '$scope', '$timeout', IntroductionController]); - - function IntroductionController(dataContext, logger, resourcePoolFactory, $scope, $timeout) { - - // Logger - logger = logger.forSource(controllerId); - - var vm = this; - vm.upoConfig = { userName: 'sample', resourcePoolKey: 'Unidentified-Profiting-Object' }; - - // TODO Disabled for the moment, since it automatically triggers 'anonymous user interacted' / SH - 07 Jun. '16 - //_init(); - - /*** Implementations ***/ - - function _init() { - - resourcePoolFactory.getResourcePoolExpanded(vm.upoConfig) - .then(function (resourcePool) { - - var increaseMultiplierTimeout = $timeout(increaseMultiplier, 500); - - function increaseMultiplier() { - - // Increase the multiplier - resourcePool.ElementSet.forEach(function (element) { - resourcePoolFactory.updateElementMultiplier(element, 'increase'); - }); - - // Then increase recursively - increaseMultiplierTimeout = $timeout(increaseMultiplier, 2500); - } - - // When the DOM element is removed from the page, - // AngularJS will trigger the $destroy event on - // the scope. This gives us a chance to cancel any - // pending timer that we may have. - $scope.$on("$destroy", function (event) { - $timeout.cancel(increaseMultiplierTimeout); - }); - }); - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/content/IntroductionController.ts b/ngClient/_system/js/app/controllers/content/IntroductionController.ts new file mode 100644 index 000000000..a98362933 --- /dev/null +++ b/ngClient/_system/js/app/controllers/content/IntroductionController.ts @@ -0,0 +1,60 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'IntroductionController'; + + export class IntroductionController { + + static $inject = ['dataContext', 'logger', 'resourcePoolFactory', '$scope', '$timeout']; + + constructor(dataContext: any, + logger: any, + resourcePoolFactory: any, + $scope: any, + $timeout: + any) { + + // Logger + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.upoConfig = { userName: 'sample', resourcePoolKey: 'Unidentified-Profiting-Object' }; + + // TODO Disabled for the moment, since it automatically triggers 'anonymous user interacted' / coni2k - 07 Jun. '16 + //_init(); + + /*** Implementations ***/ + + function _init() { + + resourcePoolFactory.getResourcePoolExpanded(vm.upoConfig) + .then(resourcePool => { + + var increaseMultiplierTimeout = $timeout(increaseMultiplier, 500); + + function increaseMultiplier() { + + // Increase the multiplier + resourcePool.ElementSet.forEach(element => { + resourcePoolFactory.updateElementMultiplier(element, 'increase'); + }); + + // Then increase recursively + increaseMultiplierTimeout = $timeout(increaseMultiplier, 2500); + } + + // When the DOM element is removed from the page, + // AngularJS will trigger the $destroy event on + // the scope. This gives us a chance to cancel any + // pending timer that we may have. + $scope.$on("$destroy", + event => { + $timeout.cancel(increaseMultiplierTimeout); + }); + }); + } + } + } + + angular.module('main').controller(controllerId, IntroductionController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/content/KnowledgeIndexController.js b/ngClient/_system/js/app/controllers/content/KnowledgeIndexController.js deleted file mode 100644 index 63d09dc30..000000000 --- a/ngClient/_system/js/app/controllers/content/KnowledgeIndexController.js +++ /dev/null @@ -1,160 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'KnowledgeIndexController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', 'resourcePoolFactory', '$scope', '$timeout', KnowledgeIndexController]); - - function KnowledgeIndexController(dataContext, logger, resourcePoolFactory, $scope, $timeout) { - - logger = logger.forSource(controllerId); - - var vm = this; - vm.oldModelChartConfig = { - title: { - text: '' - }, - options: { - chart: { - type: 'column', - height: 358 - }, - plotOptions: { - column: { - allowPointSelect: true, - pointWidth: 15 - } - }, - xAxis: { categories: ['Knowledge'] }, - yAxis: { - title: { - text: 'Development process' - }, - allowDecimals: false, - min: 0 - } - }, - size: {}, - series: [ - { name: "My Precious Jewelry", data: [0] }, - { name: 'Death Star Architecture', data: [0] }, - { name: "Christina's Secret", data: [0] }, - { name: 'Nuka Cola Company', data: [0] } - ] - }; - vm.newModelChartConfig = { - title: { - text: '' - }, - options: { - chart: { - type: 'column', - height: 300 - }, - plotOptions: { - column: { - allowPointSelect: true, - pointWidth: 15 - } - }, - xAxis: { categories: ['Knowledge'] }, - yAxis: { - title: { - text: 'Development process' - }, - allowDecimals: false, - min: 0 - } - }, - size: {}, - series: [ - { name: 'Global Knowledge Database', data: [0] } - ] - }; - vm.knowledgeIndexConfig = { userName: 'sample', resourcePoolKey: 'Knowledge-Index-Sample' }; - vm.popularSoftwareLicensesConfig = { userName: 'sample', resourcePoolKey: 'Knowledge-Index-Popular-Software-Licenses' }; - - // Event listeners - $scope.$on('resourcePoolEditor_elementCellNumericValueIncreased', updateAllInOne); - $scope.$on('resourcePoolEditor_elementCellNumericValueDecreased', updateAllInOne); - $scope.$on('resourcePoolEditor_elementCellNumericValueReset', updateAllInOne); - - _init(); - - function _init() { - var timeout = $timeout(refreshPage, 10000); - - function refreshPage() { - var organizationIndex = Math.floor(Math.random() * 4); - vm.oldModelChartConfig.series[organizationIndex].data[0] += 1; - vm.newModelChartConfig.series[0].data[0] += 1; - - timeout = $timeout(refreshPage, 1000); - } - - // When the DOM element is removed from the page, - // AngularJS will trigger the $destroy event on - // the scope. This gives us a chance to cancel any - // pending timer that we may have. - $scope.$on("$destroy", function (event) { - $timeout.cancel(timeout); - }); - } - - // Sync this example's values with 'All in One' - function updateAllInOne(event, cell) { - - if (cell.ElementField.Element.ResourcePool.User.UserName !== vm.knowledgeIndexConfig.userName && - cell.ElementField.Element.ResourcePool.Key !== vm.knowledgeIndexConfig.resourcePoolKey) { - return; - } - - var allInOneUniqueKey = { userName: 'sample', resourcePoolKey: 'All-in-One' }; - resourcePoolFactory.getResourcePoolExpanded(allInOneUniqueKey) - .then(function (resourcePool) { - - // If the current user already interacted with 'All in One', stop copying ratings - if (typeof resourcePool.userInteracted !== 'undefined' && resourcePool.userInteracted) { - return; - } - - // Elements - for (var elementIndex = 0; elementIndex < resourcePool.ElementSet.length; elementIndex++) { - var element = resourcePool.ElementSet[elementIndex]; - if (element.Name === cell.ElementField.Element.Name) { - // Element fields - for (var elementFieldIndex = 0; elementFieldIndex < element.ElementFieldSet.length; elementFieldIndex++) { - var elementField = element.ElementFieldSet[elementFieldIndex]; - if (elementField.Name === cell.ElementField.Name) { - // Element cells - for (var elementCellIndex = 0; elementCellIndex < elementField.ElementCellSet.length; elementCellIndex++) { - var elementCell = elementField.ElementCellSet[elementCellIndex]; - if (elementCell.ElementItem.Name === cell.ElementItem.Name) { - switch (event.name) { - case 'resourcePoolEditor_elementCellNumericValueIncreased': { - resourcePoolFactory.updateElementCellDecimalValue(elementCell, 'increase'); - break; - } - case 'resourcePoolEditor_elementCellNumericValueDecreased': { - resourcePoolFactory.updateElementCellDecimalValue(elementCell, 'decrease'); - break; - } - case 'resourcePoolEditor_elementCellNumericValueReset': { - resourcePoolFactory.updateElementCellDecimalValue(elementCell, 'reset'); - break; - } - } - - // Save changes - dataContext.saveChanges(1500); - break; - } - } - } - } - } - } - }); - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/content/KnowledgeIndexController.ts b/ngClient/_system/js/app/controllers/content/KnowledgeIndexController.ts new file mode 100644 index 000000000..5f69ae340 --- /dev/null +++ b/ngClient/_system/js/app/controllers/content/KnowledgeIndexController.ts @@ -0,0 +1,184 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'KnowledgeIndexController'; + + export class KnowledgeIndexController { + + static $inject = ['dataContext', 'logger', 'resourcePoolFactory', '$scope', '$timeout']; + + constructor(dataContext: any, + logger: any, + resourcePoolFactory: any, + $scope: any, + $timeout: any) { + + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.oldModelChartConfig = { + title: { + text: '' + }, + options: { + chart: { + type: 'column', + height: 358 + }, + plotOptions: { + column: { + allowPointSelect: true, + pointWidth: 15 + } + }, + xAxis: { categories: ['Knowledge'] }, + yAxis: { + title: { + text: 'Development process' + }, + allowDecimals: false, + min: 0 + } + }, + size: {}, + series: [ + { name: "My Precious Jewelry", data: [0] }, + { name: 'Death Star Architecture', data: [0] }, + { name: "Christina's Secret", data: [0] }, + { name: 'Nuka Cola Company', data: [0] } + ] + }; + vm.newModelChartConfig = { + title: { + text: '' + }, + options: { + chart: { + type: 'column', + height: 300 + }, + plotOptions: { + column: { + allowPointSelect: true, + pointWidth: 15 + } + }, + xAxis: { categories: ['Knowledge'] }, + yAxis: { + title: { + text: 'Development process' + }, + allowDecimals: false, + min: 0 + } + }, + size: {}, + series: [ + { name: 'Global Knowledge Database', data: [0] } + ] + }; + vm.knowledgeIndexConfig = { userName: 'sample', resourcePoolKey: 'Knowledge-Index-Sample' }; + vm.popularSoftwareLicensesConfig = { + userName: 'sample', + resourcePoolKey: 'Knowledge-Index-Popular-Software-Licenses' + }; + + // Event listeners + $scope.$on('resourcePoolEditor_elementCellNumericValueIncreased', updateAllInOne); + $scope.$on('resourcePoolEditor_elementCellNumericValueDecreased', updateAllInOne); + $scope.$on('resourcePoolEditor_elementCellNumericValueReset', updateAllInOne); + + _init(); + + function _init() { + var timeout = $timeout(refreshPage, 10000); + + function refreshPage() { + var organizationIndex = Math.floor(Math.random() * 4); + vm.oldModelChartConfig.series[organizationIndex].data[0] += 1; + vm.newModelChartConfig.series[0].data[0] += 1; + + timeout = $timeout(refreshPage, 1000); + } + + // When the DOM element is removed from the page, + // AngularJS will trigger the $destroy event on + // the scope. This gives us a chance to cancel any + // pending timer that we may have. + $scope.$on("$destroy", + event => { + $timeout.cancel(timeout); + }); + } + + // Sync this example's values with 'All in One' + function updateAllInOne(event: any, cell: any); + function updateAllInOne(event, cell) { + + if (cell.ElementField.Element.ResourcePool.User.UserName !== vm.knowledgeIndexConfig.userName && + cell.ElementField.Element.ResourcePool.Key !== vm.knowledgeIndexConfig.resourcePoolKey) { + return; + } + + var allInOneUniqueKey = { userName: 'sample', resourcePoolKey: 'All-in-One' }; + resourcePoolFactory.getResourcePoolExpanded(allInOneUniqueKey) + .then(resourcePool => { + + // If the current user already interacted with 'All in One', stop copying ratings + if (typeof resourcePool.userInteracted !== 'undefined' && resourcePool.userInteracted) { + return; + } + + // Elements + for (var elementIndex = 0; elementIndex < resourcePool.ElementSet.length; elementIndex++) { + var element = resourcePool.ElementSet[elementIndex]; + if (element.Name === cell.ElementField.Element.Name) { + // Element fields + for (var elementFieldIndex = 0; + elementFieldIndex < element.ElementFieldSet.length; + elementFieldIndex++) { + var elementField = element.ElementFieldSet[elementFieldIndex]; + if (elementField.Name === cell.ElementField.Name) { + // Element cells + for (var elementCellIndex = 0; + elementCellIndex < elementField.ElementCellSet.length; + elementCellIndex++) { + var elementCell = elementField.ElementCellSet[elementCellIndex]; + if (elementCell.ElementItem.Name === cell.ElementItem.Name) { + switch (event.name) { + case 'resourcePoolEditor_elementCellNumericValueIncreased': + { + resourcePoolFactory + .updateElementCellDecimalValue(elementCell, 'increase'); + break; + } + case 'resourcePoolEditor_elementCellNumericValueDecreased': + { + resourcePoolFactory + .updateElementCellDecimalValue(elementCell, 'decrease'); + break; + } + case 'resourcePoolEditor_elementCellNumericValueReset': + { + resourcePoolFactory + .updateElementCellDecimalValue(elementCell, 'reset'); + break; + } + } + + // Save changes + dataContext.saveChanges(1500); + break; + } + } + } + } + } + } + }); + } + } + } + + angular.module('main').controller(controllerId, KnowledgeIndexController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/content/NotFoundController.js b/ngClient/_system/js/app/controllers/content/NotFoundController.js deleted file mode 100644 index 63a11ff56..000000000 --- a/ngClient/_system/js/app/controllers/content/NotFoundController.js +++ /dev/null @@ -1,24 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'NotFoundController'; - angular.module('main') - .controller(controllerId, ['logger', '$location', NotFoundController]); - - function NotFoundController(logger, $location) { - - // Logger - logger = logger.forSource(controllerId); - - _init(); - - /*** Implementations ***/ - - function _init() { - var url = $location.search().url; - if (typeof url !== 'undefined') { - throw new Error('Not found: ' + url); - } - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/content/NotFoundController.ts b/ngClient/_system/js/app/controllers/content/NotFoundController.ts new file mode 100644 index 000000000..18e3208b4 --- /dev/null +++ b/ngClient/_system/js/app/controllers/content/NotFoundController.ts @@ -0,0 +1,29 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'NotFoundController'; + + export class NotFoundController { + + static $inject = ['logger', '$location']; + + constructor(logger: any, $location: any) { + + // Logger + logger = logger.forSource(controllerId); + + _init(); + + /*** Implementations ***/ + + function _init() { + var url = $location.search().url; + if (typeof url !== 'undefined') { + throw new Error('Not found: ' + url); + } + } + } + } + + angular.module('main').controller(controllerId, NotFoundController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/content/PriorityIndexController.js b/ngClient/_system/js/app/controllers/content/PriorityIndexController.js deleted file mode 100644 index 49935af31..000000000 --- a/ngClient/_system/js/app/controllers/content/PriorityIndexController.js +++ /dev/null @@ -1,76 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'PriorityIndexController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', 'resourcePoolFactory', '$scope', PriorityIndexController]); - - function PriorityIndexController(dataContext, logger, resourcePoolFactory, $scope) { - - logger = logger.forSource(controllerId); - - var vm = this; - vm.priorityIndexConfig = { userName: 'sample', resourcePoolKey: 'Priority-Index-Sample' }; - - // Event listeners - $scope.$on('resourcePoolEditor_elementCellNumericValueIncreased', updateAllInOne); - $scope.$on('resourcePoolEditor_elementCellNumericValueDecreased', updateAllInOne); - $scope.$on('resourcePoolEditor_elementCellNumericValueReset', updateAllInOne); - - // Sync this example's values with 'All in One' - function updateAllInOne(event, cell) { - - if (cell.ElementField.Element.ResourcePool.User.UserName !== vm.priorityIndexConfig.userName && - cell.ElementField.Element.ResourcePool.Key !== vm.priorityIndexConfig.resourcePoolKey) { - return; - } - - var allInOneUniqueKey = { userName: 'sample', resourcePoolKey: 'All-in-One' }; - resourcePoolFactory.getResourcePoolExpanded(allInOneUniqueKey) - .then(function (resourcePool) { - - // If the current user already interacted with 'All in One', stop copying ratings - if (typeof resourcePool.userInteracted !== 'undefined' && resourcePool.userInteracted) { - return; - } - - // Elements - for (var elementIndex = 0; elementIndex < resourcePool.ElementSet.length; elementIndex++) { - var element = resourcePool.ElementSet[elementIndex]; - if (element.Name === cell.ElementField.Element.Name) { - // Element fields - for (var elementFieldIndex = 0; elementFieldIndex < element.ElementFieldSet.length; elementFieldIndex++) { - var elementField = element.ElementFieldSet[elementFieldIndex]; - if (elementField.Name === cell.ElementField.Name) { - // Element cells - for (var elementCellIndex = 0; elementCellIndex < elementField.ElementCellSet.length; elementCellIndex++) { - var elementCell = elementField.ElementCellSet[elementCellIndex]; - if (elementCell.ElementItem.Name === cell.ElementItem.Name) { - switch (event.name) { - case 'resourcePoolEditor_elementCellNumericValueIncreased': { - resourcePoolFactory.updateElementCellDecimalValue(elementCell, 'increase'); - break; - } - case 'resourcePoolEditor_elementCellNumericValueDecreased': { - resourcePoolFactory.updateElementCellDecimalValue(elementCell, 'decrease'); - break; - } - case 'resourcePoolEditor_elementCellNumericValueReset': { - resourcePoolFactory.updateElementCellDecimalValue(elementCell, 'reset'); - break; - } - } - - // Save changes - dataContext.saveChanges(1500); - break; - } - } - } - } - } - } - }); - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/content/PriorityIndexController.ts b/ngClient/_system/js/app/controllers/content/PriorityIndexController.ts new file mode 100644 index 000000000..8082fa16f --- /dev/null +++ b/ngClient/_system/js/app/controllers/content/PriorityIndexController.ts @@ -0,0 +1,92 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'PriorityIndexController'; + + export class PriorityIndexController { + + static $inject = ['dataContext', 'logger', 'resourcePoolFactory', '$scope']; + + constructor(dataContext: any, logger: any, resourcePoolFactory: any, $scope: any) { + + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.priorityIndexConfig = { userName: 'sample', resourcePoolKey: 'Priority-Index-Sample' }; + + // Event listeners + $scope.$on('resourcePoolEditor_elementCellNumericValueIncreased', updateAllInOne); + $scope.$on('resourcePoolEditor_elementCellNumericValueDecreased', updateAllInOne); + $scope.$on('resourcePoolEditor_elementCellNumericValueReset', updateAllInOne); + + // Sync this example's values with 'All in One' + function updateAllInOne(event: any, cell: any); + function updateAllInOne(event, cell) { + + if (cell.ElementField.Element.ResourcePool.User.UserName !== vm.priorityIndexConfig.userName && + cell.ElementField.Element.ResourcePool.Key !== vm.priorityIndexConfig.resourcePoolKey) { + return; + } + + var allInOneUniqueKey = { userName: 'sample', resourcePoolKey: 'All-in-One' }; + resourcePoolFactory.getResourcePoolExpanded(allInOneUniqueKey) + .then(resourcePool => { + + // If the current user already interacted with 'All in One', stop copying ratings + if (typeof resourcePool.userInteracted !== 'undefined' && resourcePool.userInteracted) { + return; + } + + // Elements + for (var elementIndex = 0; elementIndex < resourcePool.ElementSet.length; elementIndex++) { + var element = resourcePool.ElementSet[elementIndex]; + if (element.Name === cell.ElementField.Element.Name) { + // Element fields + for (var elementFieldIndex = 0; + elementFieldIndex < element.ElementFieldSet.length; + elementFieldIndex++) { + var elementField = element.ElementFieldSet[elementFieldIndex]; + if (elementField.Name === cell.ElementField.Name) { + // Element cells + for (var elementCellIndex = 0; + elementCellIndex < elementField.ElementCellSet.length; + elementCellIndex++) { + var elementCell = elementField.ElementCellSet[elementCellIndex]; + if (elementCell.ElementItem.Name === cell.ElementItem.Name) { + switch (event.name) { + case 'resourcePoolEditor_elementCellNumericValueIncreased': + { + resourcePoolFactory + .updateElementCellDecimalValue(elementCell, 'increase'); + break; + } + case 'resourcePoolEditor_elementCellNumericValueDecreased': + { + resourcePoolFactory + .updateElementCellDecimalValue(elementCell, 'decrease'); + break; + } + case 'resourcePoolEditor_elementCellNumericValueReset': + { + resourcePoolFactory + .updateElementCellDecimalValue(elementCell, 'reset'); + break; + } + } + + // Save changes + dataContext.saveChanges(1500); + break; + } + } + } + } + } + } + }); + } + } + } + + angular.module('main').controller(controllerId, PriorityIndexController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/content/TotalCostIndexController.js b/ngClient/_system/js/app/controllers/content/TotalCostIndexController.js deleted file mode 100644 index 2e0fc54ef..000000000 --- a/ngClient/_system/js/app/controllers/content/TotalCostIndexController.js +++ /dev/null @@ -1,56 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'TotalCostIndexController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', 'resourcePoolFactory', '$scope', TotalCostIndexController]); - - function TotalCostIndexController(dataContext, logger, resourcePoolFactory, $scope) { - - logger = logger.forSource(controllerId); - - var vm = this; - vm.existingModelConfig = { userName: 'sample', resourcePoolKey: 'Total-Cost-Index-Existing-Model' }; - vm.newModelConfig = { userName: 'sample', resourcePoolKey: 'Total-Cost-Index-New-Model' }; - - // Listen resource pool updated event - $scope.$on('resourcePoolEditor_elementMultiplierIncreased', updateOppositeResourcePool); - $scope.$on('resourcePoolEditor_elementMultiplierDecreased', updateOppositeResourcePool); - $scope.$on('resourcePoolEditor_elementMultiplierReset', updateOppositeResourcePool); - - function updateOppositeResourcePool(event, element) { - - var oppositeKey = null; - - if (element.ResourcePool.User.UserName === vm.existingModelConfig.userName && element.ResourcePool.Key === vm.existingModelConfig.resourcePoolKey) { - oppositeKey = vm.newModelConfig; - } else if (element.ResourcePool.User.UserName === vm.newModelConfig.userName && element.ResourcePool.Key === vm.newModelConfig.resourcePoolKey) { - oppositeKey = vm.existingModelConfig; - } - - // Call the service to increase the multiplier - if (oppositeKey !== null) { - resourcePoolFactory.getResourcePoolExpanded(oppositeKey) - .then(function (resourcePool) { - - switch (event.name) { - case 'resourcePoolEditor_elementMultiplierIncreased': { - resourcePoolFactory.updateElementMultiplier(resourcePool.mainElement(), 'increase'); - break; - } - case 'resourcePoolEditor_elementMultiplierDecreased': { - resourcePoolFactory.updateElementMultiplier(resourcePool.mainElement(), 'decrease'); - break; - } - case 'resourcePoolEditor_elementMultiplierReset': { - resourcePoolFactory.updateElementMultiplier(resourcePool.mainElement(), 'reset'); - break; - } - } - - dataContext.saveChanges(1500); - }); - } - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/content/TotalCostIndexController.ts b/ngClient/_system/js/app/controllers/content/TotalCostIndexController.ts new file mode 100644 index 000000000..b3d6d83d6 --- /dev/null +++ b/ngClient/_system/js/app/controllers/content/TotalCostIndexController.ts @@ -0,0 +1,66 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'TotalCostIndexController'; + + export class TotalCostIndexController { + + static $inject = ['dataContext', 'logger', 'resourcePoolFactory', '$scope']; + + constructor(dataContext: any, logger: any, resourcePoolFactory: any, $scope: any) { + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.existingModelConfig = { userName: 'sample', resourcePoolKey: 'Total-Cost-Index-Existing-Model' }; + vm.newModelConfig = { userName: 'sample', resourcePoolKey: 'Total-Cost-Index-New-Model' }; + + // Listen resource pool updated event + $scope.$on('resourcePoolEditor_elementMultiplierIncreased', updateOppositeResourcePool); + $scope.$on('resourcePoolEditor_elementMultiplierDecreased', updateOppositeResourcePool); + $scope.$on('resourcePoolEditor_elementMultiplierReset', updateOppositeResourcePool); + + function updateOppositeResourcePool(event: any, element: any); + function updateOppositeResourcePool(event, element) { + + var oppositeKey = null; + + if (element.ResourcePool.User.UserName === vm.existingModelConfig.userName && + element.ResourcePool.Key === vm.existingModelConfig.resourcePoolKey) { + oppositeKey = vm.newModelConfig; + } else if (element.ResourcePool.User.UserName === vm.newModelConfig.userName && + element.ResourcePool.Key === vm.newModelConfig.resourcePoolKey) { + oppositeKey = vm.existingModelConfig; + } + + // Call the service to increase the multiplier + if (oppositeKey !== null) { + resourcePoolFactory.getResourcePoolExpanded(oppositeKey) + .then(resourcePool => { + + switch (event.name) { + case 'resourcePoolEditor_elementMultiplierIncreased': + { + resourcePoolFactory.updateElementMultiplier(resourcePool.mainElement(), 'increase'); + break; + } + case 'resourcePoolEditor_elementMultiplierDecreased': + { + resourcePoolFactory.updateElementMultiplier(resourcePool.mainElement(), 'decrease'); + break; + } + case 'resourcePoolEditor_elementMultiplierReset': + { + resourcePoolFactory.updateElementMultiplier(resourcePool.mainElement(), 'reset'); + break; + } + } + + dataContext.saveChanges(1500); + }); + } + } + } + } + + angular.module('main').controller(controllerId, TotalCostIndexController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/content/obsolete/ClosingNotesController.js b/ngClient/_system/js/app/controllers/content/obsolete/ClosingNotesController.js deleted file mode 100644 index 9f7d5d189..000000000 --- a/ngClient/_system/js/app/controllers/content/obsolete/ClosingNotesController.js +++ /dev/null @@ -1,31 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'ClosingNotesController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', '$location', '$rootScope', '$scope', ClosingNotesController]); - - function ClosingNotesController(dataContext, logger, $location, $rootScope, $scope) { - - // Logger - logger = logger.forSource(controllerId); - - // View model - var vm = this; - vm.currentUser = { isAuthenticated: function () { return false; } }; - - $scope.$on('dataContext_currentUserChanged', currentUserChanged); - - _init(); - - /*** Implementations ***/ - - function _init() { - vm.currentUser = dataContext.getCurrentUser(); - } - - function currentUserChanged(event, newUser) { - vm.currentUser = newUser; - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/content/obsolete/ClosingNotesController.ts b/ngClient/_system/js/app/controllers/content/obsolete/ClosingNotesController.ts new file mode 100644 index 000000000..33f38029e --- /dev/null +++ b/ngClient/_system/js/app/controllers/content/obsolete/ClosingNotesController.ts @@ -0,0 +1,41 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'ClosingNotesController'; + + export class ClosingNotesController { + + static $inject = ['dataContext', 'logger', '$location', '$rootScope', '$scope']; + + constructor(dataContext: any, logger: any, $location: any, $rootScope: any, $scope: any) { + + // Logger + logger = logger.forSource(controllerId); + + // View model + var vm:any = this; + vm.currentUser = { + isAuthenticated() { + return false; + } + }; + + $scope.$on('dataContext_currentUserChanged', currentUserChanged); + + _init(); + + /*** Implementations ***/ + + function _init() { + vm.currentUser = dataContext.getCurrentUser(); + } + + function currentUserChanged(event: any, newUser: any); + function currentUserChanged(event, newUser) { + vm.currentUser = newUser; + } + } + } + + angular.module('main').controller(controllerId, ClosingNotesController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/content/obsolete/FairShareIndexSampleController.js b/ngClient/_system/js/app/controllers/content/obsolete/FairShareIndexSampleController.js deleted file mode 100644 index b406ee38b..000000000 --- a/ngClient/_system/js/app/controllers/content/obsolete/FairShareIndexSampleController.js +++ /dev/null @@ -1,14 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'FairShareIndexSampleController'; - angular.module('main') - .controller(controllerId, ['logger', FairShareIndexSampleController]); - - function FairShareIndexSampleController(logger) { - - logger = logger.forSource(controllerId); - - var vm = this; - } -})(); diff --git a/ngClient/_system/js/app/controllers/content/obsolete/FairShareIndexSampleController.ts b/ngClient/_system/js/app/controllers/content/obsolete/FairShareIndexSampleController.ts new file mode 100644 index 000000000..b4547a825 --- /dev/null +++ b/ngClient/_system/js/app/controllers/content/obsolete/FairShareIndexSampleController.ts @@ -0,0 +1,19 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'FairShareIndexSampleController'; + + export class FairShareIndexSampleController { + + static $inject = ['logger']; + + constructor(logger: any) { + + logger = logger.forSource(controllerId); + + var vm:any = this; + } + } + + angular.module('main').controller(controllerId, FairShareIndexSampleController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/content/obsolete/ResourcePoolRateSampleController.js b/ngClient/_system/js/app/controllers/content/obsolete/ResourcePoolRateSampleController.js deleted file mode 100644 index f12362031..000000000 --- a/ngClient/_system/js/app/controllers/content/obsolete/ResourcePoolRateSampleController.js +++ /dev/null @@ -1,15 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'ResourcePoolRateSampleController'; - angular.module('main') - .controller(controllerId, ['logger', ResourcePoolRateSampleController]); - - function ResourcePoolRateSampleController(logger) { - - logger = logger.forSource(controllerId); - - var vm = this; - vm.resourcePoolRate_SampleResourcePoolId = 12; - } -})(); diff --git a/ngClient/_system/js/app/controllers/content/obsolete/ResourcePoolRateSampleController.ts b/ngClient/_system/js/app/controllers/content/obsolete/ResourcePoolRateSampleController.ts new file mode 100644 index 000000000..bbaaf8066 --- /dev/null +++ b/ngClient/_system/js/app/controllers/content/obsolete/ResourcePoolRateSampleController.ts @@ -0,0 +1,20 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'ResourcePoolRateSampleController'; + + export class ResourcePoolRateSampleController { + + static $inject = ['logger']; + + constructor(logger: any) { + + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.resourcePoolRate_SampleResourcePoolId = 12; + } + } + + angular.module('main').controller(controllerId, ResourcePoolRateSampleController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolManageController.js b/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolManageController.js deleted file mode 100644 index 7de3349df..000000000 --- a/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolManageController.js +++ /dev/null @@ -1,444 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'ResourcePoolManageController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'Enums', 'logger', 'resourcePoolFactory', '$location', '$rootScope', '$routeParams', '$uibModal', ResourcePoolManageController]); - - function ResourcePoolManageController(dataContext, Enums, logger, resourcePoolFactory, $location, $rootScope, $routeParams, $uibModal) { - - // Logger - logger = logger.forSource(controllerId); - - var vm = this; - vm.addElement = addElement; - vm.addElementField = addElementField; - vm.addElementItem = addElementItem; - vm.cancelElement = cancelElement; - vm.cancelElementCell = cancelElementCell; - vm.cancelElementField = cancelElementField; - vm.cancelElementItem = cancelElementItem; - vm.cancelResourcePool = cancelResourcePool; - vm.editElement = editElement; - vm.editElementCell = editElementCell; - vm.editElementField = editElementField; - vm.editElementItem = editElementItem; - vm.element = null; - vm.elementMaster = null; - vm.elementCell = null; - vm.elementCellMaster = null; - vm.elementCellSet = elementCellSet; - vm.elementField = null; - vm.elementFieldMaster = null; - vm.elementFieldSet = elementFieldSet; - vm.elementFieldDataTypeFiltered = elementFieldDataTypeFiltered; - vm.elementItem = null; - vm.elementItemMaster = null; - vm.elementItemSet = elementItemSet; - vm.isElementEdit = false; - vm.isElementNew = true; - vm.isElementFieldEdit = false; - vm.isElementFieldNew = true; - vm.isElementItemEdit = false; - vm.isElementItemNew = true; - vm.isNew = $location.path().substring($location.path().lastIndexOf('/') + 1) === 'new'; - vm.isSaveEnabled = isSaveEnabled; - vm.isSaving = false; - vm.openRemoveResourcePoolModal = openRemoveResourcePoolModal; - vm.removeElement = removeElement; - vm.removeElementField = removeElementField; - vm.removeElementItem = removeElementItem; - vm.removeResourcePool = removeResourcePool; - vm.resourcePool = { ElementSet: [] }; - vm.resourcePoolKey = $routeParams.resourcePoolKey; - vm.saveResourcePool = saveResourcePool; - vm.saveElement = saveElement; - vm.saveElementCell = saveElementCell; - vm.saveElementField = saveElementField; - vm.saveElementItem = saveElementItem; - vm.userName = $routeParams.userName; - - // Enums - vm.ElementFieldDataType = Enums.ElementFieldDataType; - vm.ElementFieldIndexCalculationType = Enums.ElementFieldIndexCalculationType; - vm.ElementFieldIndexSortType = Enums.ElementFieldIndexSortType; - - _init(); - - /*** Implementations ***/ - - function _init() { - - if (vm.isNew) { - - var currentUser = dataContext.getCurrentUser(); - - // If userName equals to current user - if (vm.userName === currentUser.UserName) { - vm.user = currentUser; - - vm.resourcePool = resourcePoolFactory.createResourcePoolBasic(); - - // Title - // TODO viewTitle was also set in route.js? - $rootScope.viewTitle = vm.resourcePool.Name; - - } else { - $location.url('/_system/content/notFound?url=' + $location.url()); - return; - } - - } else { - - var resourcePoolUniqueKey = { userName: vm.userName, resourcePoolKey: vm.resourcePoolKey }; - - resourcePoolFactory.getResourcePoolExpanded(resourcePoolUniqueKey) - .then(function (resourcePool) { - - // Not found, navigate to 404 - if (resourcePool === null) { - $location.url('/_system/content/notFound?url=' + $location.url()); - return; - } - - vm.resourcePool = resourcePool; - - // Title - // TODO viewTitle was also set in route.js? - $rootScope.viewTitle = vm.resourcePool.Name; - }); - } - } - - function addElement() { - vm.element = resourcePoolFactory.createElement({ - ResourcePool: vm.resourcePool, - Name: 'New element', - IsMainElement: false - }); - - vm.isElementEdit = true; - vm.isElementNew = true; - } - - function addElementField() { - - var element = vm.resourcePool.ElementSet[0]; - - // A temp fix for default value of 'SortOrder' - // Later handle 'SortOrder' by UI, not by asking - var sortOrder = element.ElementFieldSet.length + 1; - - vm.elementField = resourcePoolFactory.createElementField({ - Element: element, - Name: 'New field', - DataType: 1, - SortOrder: sortOrder - }); - - vm.isElementFieldEdit = true; - vm.isElementFieldNew = true; - } - - function addElementItem() { - vm.elementItem = resourcePoolFactory.createElementItem({ - Element: vm.resourcePool.ElementSet[0], - Name: 'New item' - }); - vm.isElementItemEdit = true; - vm.isElementItemNew = true; - } - - function cancelElement() { - - // TODO Find a better way? - // Can't use reject changes because in 'New CMRP' case, these are newly added entities and reject changes removes them / SH - 23 Nov. '15 - if (vm.isElementNew) { - resourcePoolFactory.removeElement(vm.element); - } else { - vm.element.Name = vm.elementMaster.Name; - } - - vm.isElementEdit = false; - vm.element = null; - vm.elementMaster = null; - } - - function cancelElementCell() { - - // TODO Find a better way? - // Can't use reject changes because in 'New CMRP' case, these are newly added entities and reject changes removes them / SH - 23 Nov. '15 - vm.elementCell.SelectedElementItemId = vm.elementCellMaster.SelectedElementItemId; - vm.elementCell.UserElementCellSet[0].StringValue = vm.elementCellMaster.UserElementCellSet[0].StringValue; - vm.elementCell.UserElementCellSet[0].BooleanValue = vm.elementCellMaster.UserElementCellSet[0].BooleanValue; - vm.elementCell.UserElementCellSet[0].IntegerValue = vm.elementCellMaster.UserElementCellSet[0].IntegerValue; - vm.elementCell.UserElementCellSet[0].DecimalValue = vm.elementCellMaster.UserElementCellSet[0].DecimalValue; - vm.elementCell.UserElementCellSet[0].DateTimeValue = vm.elementCellMaster.UserElementCellSet[0].DateTimeValue; - - vm.isElementCellEdit = false; - vm.elementCell = null; - vm.elementCellMaster = null; - } - - function cancelElementField() { - - // TODO Find a better way? - // Can't use reject changes because in 'New CMRP' case, these are newly added entities and reject changes removes them / SH - 23 Nov. '15 - if (vm.isElementFieldNew) { - resourcePoolFactory.removeElementField(vm.elementField); - } else { - vm.elementField.Name = vm.elementFieldMaster.Name; - vm.elementField.DataType = vm.elementFieldMaster.DataType; - vm.elementField.SelectedElementId = vm.elementFieldMaster.SelectedElementId; - vm.elementField.UseFixedValue = vm.elementFieldMaster.UseFixedValue; - vm.elementField.IndexEnabled = vm.elementFieldMaster.IndexEnabled; - vm.elementField.IndexCalculationType = vm.elementFieldMaster.IndexCalculationType; - vm.elementField.IndexSortType = vm.elementFieldMaster.IndexSortType; - vm.elementField.SortOrder = vm.elementFieldMaster.SortOrder; - } - - vm.isElementFieldEdit = false; - vm.elementField = null; - vm.elementFieldMaster = null; - } - - function cancelElementItem() { - - // TODO Find a better way? - // Can't use reject changes because in 'New CMRP' case, these are newly added entities and reject changes removes them / SH - 23 Nov. '15 - if (!vm.isElementItemNew) { - vm.elementItem.Name = vm.elementItemMaster.Name; - } - - vm.isElementItemEdit = false; - vm.elementItem = null; - vm.elementItemMaster = null; - } - - function cancelResourcePool() { - - dataContext.rejectChanges(); - - var locationPath = vm.isNew ? - '/' + dataContext.getCurrentUser().UserName : - vm.resourcePool.urlView(); - - $location.url(locationPath); - } - - function editElement(element) { - vm.elementMaster = angular.copy(element); - vm.element = element; - vm.isElementEdit = true; - vm.isElementNew = false; - } - - function editElementCell(elementCell) { - vm.elementCellMaster = angular.copy(elementCell); - vm.elementCell = elementCell; - vm.isElementCellEdit = true; - } - - function editElementField(elementField) { - vm.elementFieldMaster = angular.copy(elementField); - vm.elementField = elementField; - vm.isElementFieldEdit = true; - vm.isElementFieldNew = false; - } - - function editElementItem(elementItem) { - vm.elementItemMaster = angular.copy(elementItem); - vm.elementItem = elementItem; - vm.isElementItemEdit = true; - vm.isElementItemNew = false; - } - - function elementCellSet() { - - var elementItems = elementItemSet(); - - var list = []; - elementItems.forEach(function (elementItem) { - elementItem.ElementCellSet.forEach(function (elementCell) { - list.push(elementCell); - }); - }); - return list; - } - - function elementFieldSet() { - var list = []; - vm.resourcePool.ElementSet.forEach(function (element) { - element.ElementFieldSet.forEach(function (elementField) { - list.push(elementField); - }); - }); - return list; - } - - function elementFieldDataTypeFiltered() { - - var filtered = {}; - for (var key in vm.ElementFieldDataType) { - - // These types can be added only once at the moment - if (key === 'DirectIncome' || key === 'Multiplier') { - var exists = vm.elementField.Element.ElementFieldSet.some(fieldExists); - - if (!exists) { - filtered[key] = vm.ElementFieldDataType[key]; - } - } else if (key === 'Element') { // Element type can only be added if there are more than one element in the pool - if (vm.elementField.Element.ResourcePool.ElementSet.length > 1) { - filtered[key] = vm.ElementFieldDataType[key]; - } - } else { - filtered[key] = vm.ElementFieldDataType[key]; - } - } - - function fieldExists(field) { - return vm.ElementFieldDataType[key] === field.ElementFieldDataType; - } - - return filtered; - } - - function elementItemSet() { - var list = []; - vm.resourcePool.ElementSet.forEach(function (element) { - element.ElementItemSet.forEach(function (elementItem) { - list.push(elementItem); - }); - }); - return list; - } - - function isSaveEnabled() { - var value = !vm.isSaving && - typeof vm.resourcePoolForm !== 'undefined' && - vm.resourcePoolForm.$valid; - - return value; - } - - function openRemoveResourcePoolModal() { - var modalInstance = $uibModal.open({ - controller: ['$scope', '$uibModalInstance', ResourcePoolRemoveController], - controllerAs: 'vm', - keyboard: false, - templateUrl: '/_system/views/resourcePool/resourcePoolRemove.html?v=0.53.0' - }); - - modalInstance.result.then(function () { - removeResourcePool(); - }, function () { }); - } - - function removeElement(element) { - resourcePoolFactory.removeElement(element); - } - - function removeElementField(elementField) { - resourcePoolFactory.removeElementField(elementField); - } - - function removeElementItem(elementItem) { - resourcePoolFactory.removeElementItem(elementItem); - } - - function removeResourcePool() { - - vm.isSaving = true; - - resourcePoolFactory.removeResourcePool(vm.resourcePool); - - dataContext.saveChanges() - .then(function () { - $location.url('/' + dataContext.getCurrentUser().UserName); - }) - .finally(function () { - vm.isSaving = false; - }); - } - - function saveElement() { - vm.isElementEdit = false; - vm.element = null; - vm.elementMaster = null; - } - - function saveElementCell() { - vm.isElementCellEdit = false; - vm.elementCell = null; - vm.elementCellMaster = null; - } - - function saveElementField() { - - // Fixes - // a. UseFixedValue must be null for String & Element types - if (vm.elementField.DataType === vm.ElementFieldDataType.String || - vm.elementField.DataType === vm.ElementFieldDataType.Element) { - vm.elementField.UseFixedValue = null; - } - - // b. UseFixedValue must be 'false' for Multiplier type - if (vm.elementField.DataType === vm.ElementFieldDataType.Multiplier) { - vm.elementField.UseFixedValue = false; - } - - // c. DirectIncome cannot be Use Fixed Value false at the moment - if (vm.elementField.DataType === vm.ElementFieldDataType.DirectIncome) { - vm.elementField.UseFixedValue = true; - } - - vm.isElementFieldEdit = false; - vm.elementField = null; - vm.elementFieldMaster = null; - } - - function saveElementItem() { - - if (vm.isElementItemNew) { - vm.elementItem = resourcePoolFactory.createElementItem(vm.elementItem); - } - - vm.isElementItemEdit = false; - vm.elementItem = null; - vm.elementItemMaster = null; - } - - function saveResourcePool() { - - vm.isSaving = true; - - // TODO Try to move this to a better place? - vm.resourcePool.updateCache(); - - dataContext.saveChanges() - .then(function () { - $location.url(vm.resourcePool.urlView()); - }) - .finally(function () { - vm.isSaving = false; - }); - } - } - - function ResourcePoolRemoveController($scope, $uibModalInstance) { - - var vm = this; - vm.cancel = cancel; - vm.remove = remove; - - function cancel() { - $uibModalInstance.dismiss('cancel'); - } - - function remove() { - $uibModalInstance.close(); - } - } - -})(); diff --git a/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolManageController.ts b/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolManageController.ts new file mode 100644 index 000000000..129313cb2 --- /dev/null +++ b/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolManageController.ts @@ -0,0 +1,473 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'ResourcePoolManageController'; + + export class ResourcePoolManageController { + + static $inject = ['dataContext', 'Enums', 'logger', 'resourcePoolFactory', '$location', '$rootScope', '$routeParams', '$uibModal']; + + constructor(dataContext: any, + Enums: any, + logger: any, + resourcePoolFactory: any, + $location: any, + $rootScope: any, + $routeParams: any, + $uibModal: any) { + + // Logger + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.addElement = addElement; + vm.addElementField = addElementField; + vm.addElementItem = addElementItem; + vm.cancelElement = cancelElement; + vm.cancelElementCell = cancelElementCell; + vm.cancelElementField = cancelElementField; + vm.cancelElementItem = cancelElementItem; + vm.cancelResourcePool = cancelResourcePool; + vm.editElement = editElement; + vm.editElementCell = editElementCell; + vm.editElementField = editElementField; + vm.editElementItem = editElementItem; + vm.element = null; + vm.elementMaster = null; + vm.elementCell = null; + vm.elementCellMaster = null; + vm.elementCellSet = elementCellSet; + vm.elementField = null; + vm.elementFieldMaster = null; + vm.elementFieldSet = elementFieldSet; + vm.elementFieldDataTypeFiltered = elementFieldDataTypeFiltered; + vm.elementItem = null; + vm.elementItemMaster = null; + vm.elementItemSet = elementItemSet; + vm.isElementEdit = false; + vm.isElementNew = true; + vm.isElementFieldEdit = false; + vm.isElementFieldNew = true; + vm.isElementItemEdit = false; + vm.isElementItemNew = true; + vm.isNew = $location.path().substring($location.path().lastIndexOf('/') + 1) === 'new'; + vm.isSaveEnabled = isSaveEnabled; + vm.isSaving = false; + vm.openRemoveResourcePoolModal = openRemoveResourcePoolModal; + vm.removeElement = removeElement; + vm.removeElementField = removeElementField; + vm.removeElementItem = removeElementItem; + vm.removeResourcePool = removeResourcePool; + vm.resourcePool = { ElementSet: [] }; + vm.resourcePoolKey = $routeParams.resourcePoolKey; + vm.saveResourcePool = saveResourcePool; + vm.saveElement = saveElement; + vm.saveElementCell = saveElementCell; + vm.saveElementField = saveElementField; + vm.saveElementItem = saveElementItem; + vm.userName = $routeParams.userName; + + // Enums + vm.ElementFieldDataType = Enums.ElementFieldDataType; + vm.ElementFieldIndexCalculationType = Enums.ElementFieldIndexCalculationType; + vm.ElementFieldIndexSortType = Enums.ElementFieldIndexSortType; + + _init(); + + /*** Implementations ***/ + + function _init() { + + if (vm.isNew) { + + var currentUser = dataContext.getCurrentUser(); + + // If userName equals to current user + if (vm.userName === currentUser.UserName) { + vm.user = currentUser; + + vm.resourcePool = resourcePoolFactory.createResourcePoolBasic(); + + // Title + // TODO viewTitle was also set in route.js? + $rootScope.viewTitle = vm.resourcePool.Name; + + } else { + $location.url('/_system/content/notFound?url=' + $location.url()); + return; + } + + } else { + + var resourcePoolUniqueKey = { userName: vm.userName, resourcePoolKey: vm.resourcePoolKey }; + + resourcePoolFactory.getResourcePoolExpanded(resourcePoolUniqueKey) + .then(resourcePool => { + + // Not found, navigate to 404 + if (resourcePool === null) { + $location.url('/_system/content/notFound?url=' + $location.url()); + return; + } + + vm.resourcePool = resourcePool; + + // Title + // TODO viewTitle was also set in route.js? + $rootScope.viewTitle = vm.resourcePool.Name; + }); + } + } + + function addElement() { + vm.element = resourcePoolFactory.createElement({ + ResourcePool: vm.resourcePool, + Name: 'New element', + IsMainElement: false + }); + + vm.isElementEdit = true; + vm.isElementNew = true; + } + + function addElementField() { + + var element = vm.resourcePool.ElementSet[0]; + + // A temp fix for default value of 'SortOrder' + // Later handle 'SortOrder' by UI, not by asking + var sortOrder = element.ElementFieldSet.length + 1; + + vm.elementField = resourcePoolFactory.createElementField({ + Element: element, + Name: 'New field', + DataType: 1, + SortOrder: sortOrder + }); + + vm.isElementFieldEdit = true; + vm.isElementFieldNew = true; + } + + function addElementItem() { + vm.elementItem = resourcePoolFactory.createElementItem({ + Element: vm.resourcePool.ElementSet[0], + Name: 'New item' + }); + vm.isElementItemEdit = true; + vm.isElementItemNew = true; + } + + function cancelElement() { + + // TODO Find a better way? + // Can't use reject changes because in 'New CMRP' case, these are newly added entities and reject changes removes them / coni2k - 23 Nov. '15 + if (vm.isElementNew) { + resourcePoolFactory.removeElement(vm.element); + } else { + vm.element.Name = vm.elementMaster.Name; + } + + vm.isElementEdit = false; + vm.element = null; + vm.elementMaster = null; + } + + function cancelElementCell() { + + // TODO Find a better way? + // Can't use reject changes because in 'New CMRP' case, these are newly added entities and reject changes removes them / coni2k - 23 Nov. '15 + vm.elementCell.SelectedElementItemId = vm.elementCellMaster.SelectedElementItemId; + vm.elementCell.UserElementCellSet[0] + .StringValue = vm.elementCellMaster.UserElementCellSet[0].StringValue; + vm.elementCell.UserElementCellSet[0] + .BooleanValue = vm.elementCellMaster.UserElementCellSet[0].BooleanValue; + vm.elementCell.UserElementCellSet[0] + .IntegerValue = vm.elementCellMaster.UserElementCellSet[0].IntegerValue; + vm.elementCell.UserElementCellSet[0] + .DecimalValue = vm.elementCellMaster.UserElementCellSet[0].DecimalValue; + vm.elementCell.UserElementCellSet[0] + .DateTimeValue = vm.elementCellMaster.UserElementCellSet[0].DateTimeValue; + + vm.isElementCellEdit = false; + vm.elementCell = null; + vm.elementCellMaster = null; + } + + function cancelElementField() { + + // TODO Find a better way? + // Can't use reject changes because in 'New CMRP' case, these are newly added entities and reject changes removes them / coni2k - 23 Nov. '15 + if (vm.isElementFieldNew) { + resourcePoolFactory.removeElementField(vm.elementField); + } else { + vm.elementField.Name = vm.elementFieldMaster.Name; + vm.elementField.DataType = vm.elementFieldMaster.DataType; + vm.elementField.SelectedElementId = vm.elementFieldMaster.SelectedElementId; + vm.elementField.UseFixedValue = vm.elementFieldMaster.UseFixedValue; + vm.elementField.IndexEnabled = vm.elementFieldMaster.IndexEnabled; + vm.elementField.IndexCalculationType = vm.elementFieldMaster.IndexCalculationType; + vm.elementField.IndexSortType = vm.elementFieldMaster.IndexSortType; + vm.elementField.SortOrder = vm.elementFieldMaster.SortOrder; + } + + vm.isElementFieldEdit = false; + vm.elementField = null; + vm.elementFieldMaster = null; + } + + function cancelElementItem() { + + // TODO Find a better way? + // Can't use reject changes because in 'New CMRP' case, these are newly added entities and reject changes removes them / coni2k - 23 Nov. '15 + if (!vm.isElementItemNew) { + vm.elementItem.Name = vm.elementItemMaster.Name; + } + + vm.isElementItemEdit = false; + vm.elementItem = null; + vm.elementItemMaster = null; + } + + function cancelResourcePool() { + + dataContext.rejectChanges(); + + var locationPath = vm.isNew ? '/' + dataContext.getCurrentUser().UserName : vm.resourcePool.urlView(); + + $location.url(locationPath); + } + + function editElement(element: any); + function editElement(element) { + vm.elementMaster = angular.copy(element); + vm.element = element; + vm.isElementEdit = true; + vm.isElementNew = false; + } + + function editElementCell(elementCell: any); + function editElementCell(elementCell) { + vm.elementCellMaster = angular.copy(elementCell); + vm.elementCell = elementCell; + vm.isElementCellEdit = true; + } + + function editElementField(elementField: any); + function editElementField(elementField) { + vm.elementFieldMaster = angular.copy(elementField); + vm.elementField = elementField; + vm.isElementFieldEdit = true; + vm.isElementFieldNew = false; + } + + function editElementItem(elementItem: any); + function editElementItem(elementItem) { + vm.elementItemMaster = angular.copy(elementItem); + vm.elementItem = elementItem; + vm.isElementItemEdit = true; + vm.isElementItemNew = false; + } + + function elementCellSet() { + + var elementItems = elementItemSet(); + + var list = []; + elementItems.forEach(elementItem => { + elementItem.ElementCellSet.forEach(elementCell => { + list.push(elementCell); + }); + }); + return list; + } + + function elementFieldSet() { + var list = []; + vm.resourcePool.ElementSet.forEach(element => { + element.ElementFieldSet.forEach(elementField => { + list.push(elementField); + }); + }); + return list; + } + + function elementFieldDataTypeFiltered() { + + var filtered = {}; + for (var key in vm.ElementFieldDataType) { + + // These types can be added only once at the moment + if (key === 'DirectIncome' || key === 'Multiplier') { + var exists = vm.elementField.Element.ElementFieldSet.some(fieldExists); + + if (!exists) { + filtered[key] = vm.ElementFieldDataType[key]; + } + } else if (key === 'Element') { +// Element type can only be added if there are more than one element in the pool + if (vm.elementField.Element.ResourcePool.ElementSet.length > 1) { + filtered[key] = vm.ElementFieldDataType[key]; + } + } else { + filtered[key] = vm.ElementFieldDataType[key]; + } + } + + function fieldExists(field: any); + function fieldExists(field) { + return vm.ElementFieldDataType[key] === field.ElementFieldDataType; + } + + return filtered; + } + + function elementItemSet() { + var list = []; + vm.resourcePool.ElementSet.forEach(element => { + element.ElementItemSet.forEach(elementItem => { + list.push(elementItem); + }); + }); + return list; + } + + function isSaveEnabled() { + var value = !vm.isSaving && + typeof vm.resourcePoolForm !== 'undefined' && + vm.resourcePoolForm.$valid; + + return value; + } + + function openRemoveResourcePoolModal() { + var modalInstance = $uibModal.open({ + controller: ResourcePoolRemoveController, + controllerAs: 'vm', + keyboard: false, + templateUrl: '/_system/views/resourcePool/resourcePoolRemove.html?v=0.53.0' + }); + + modalInstance.result.then(() => { + removeResourcePool(); + }, + () => {}); + } + + function removeElement(element: any); + function removeElement(element) { + resourcePoolFactory.removeElement(element); + } + + function removeElementField(elementField: any); + function removeElementField(elementField) { + resourcePoolFactory.removeElementField(elementField); + } + + function removeElementItem(elementItem: any); + function removeElementItem(elementItem) { + resourcePoolFactory.removeElementItem(elementItem); + } + + function removeResourcePool() { + + vm.isSaving = true; + + resourcePoolFactory.removeResourcePool(vm.resourcePool); + + dataContext.saveChanges() + .then(() => { + $location.url('/' + dataContext.getCurrentUser().UserName); + }) + .finally(() => { + vm.isSaving = false; + }); + } + + function saveElement() { + vm.isElementEdit = false; + vm.element = null; + vm.elementMaster = null; + } + + function saveElementCell() { + vm.isElementCellEdit = false; + vm.elementCell = null; + vm.elementCellMaster = null; + } + + function saveElementField() { + + // Fixes + // a. UseFixedValue must be null for String & Element types + if (vm.elementField.DataType === vm.ElementFieldDataType.String || + vm.elementField.DataType === vm.ElementFieldDataType.Element) { + vm.elementField.UseFixedValue = null; + } + + // b. UseFixedValue must be 'false' for Multiplier type + if (vm.elementField.DataType === vm.ElementFieldDataType.Multiplier) { + vm.elementField.UseFixedValue = false; + } + + // c. DirectIncome cannot be Use Fixed Value false at the moment + if (vm.elementField.DataType === vm.ElementFieldDataType.DirectIncome) { + vm.elementField.UseFixedValue = true; + } + + vm.isElementFieldEdit = false; + vm.elementField = null; + vm.elementFieldMaster = null; + } + + function saveElementItem() { + + if (vm.isElementItemNew) { + vm.elementItem = resourcePoolFactory.createElementItem(vm.elementItem); + } + + vm.isElementItemEdit = false; + vm.elementItem = null; + vm.elementItemMaster = null; + } + + function saveResourcePool() { + + vm.isSaving = true; + + // TODO Try to move this to a better place? + vm.resourcePool.updateCache(); + + dataContext.saveChanges() + .then(() => { + $location.url(vm.resourcePool.urlView()); + }) + .finally(() => { + vm.isSaving = false; + }); + } + } + } + + class ResourcePoolRemoveController { + + static $inject = ['$scope', '$uibModalInstance']; + + constructor($scope: any, $uibModalInstance: any) { + + var vm: any = this; + vm.cancel = cancel; + vm.remove = remove; + + function cancel() { + $uibModalInstance.dismiss('cancel'); + } + + function remove() { + $uibModalInstance.close(); + } + } + } + + angular.module('main').controller(controllerId, ResourcePoolManageController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolSearchController.js b/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolSearchController.js deleted file mode 100644 index 50c8bfef3..000000000 --- a/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolSearchController.js +++ /dev/null @@ -1,38 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'ResourcePoolSearchController'; - angular.module('main') - .controller(controllerId, ['dataContext', 'logger', 'resourcePoolFactory', '$location', '$rootScope', '$scope', ResourcePoolSearchController]); - - function ResourcePoolSearchController(dataContext, logger, resourcePoolFactory, $location, $rootScope, $scope) { - - // Logger - logger = logger.forSource(controllerId); - - var vm = this; - vm.resourcePoolSet = []; - vm.searchKey = ''; - vm.searchKeyChanged = searchKeyChanged; - vm.showResults = false; - - _init(); - - function _init() { - } - - function searchKeyChanged() { - - if (vm.searchKey.length <= 2) { - vm.showResults = false; - return; - } - - resourcePoolFactory.getResourcePoolSet(vm.searchKey) - .then(function (data) { - vm.resourcePoolSet = data; - vm.showResults = true; - }); - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolSearchController.ts b/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolSearchController.ts new file mode 100644 index 000000000..ef0b53c7d --- /dev/null +++ b/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolSearchController.ts @@ -0,0 +1,48 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'ResourcePoolSearchController'; + + export class ResourcePoolSearchController { + + static $inject = ['dataContext', 'logger', 'resourcePoolFactory', '$location', '$rootScope', '$scope']; + + constructor(dataContext: any, + logger: any, + resourcePoolFactory: any, + $location: any, + $rootScope: any, + $scope: any) { + + // Logger + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.resourcePoolSet = []; + vm.searchKey = ''; + vm.searchKeyChanged = searchKeyChanged; + vm.showResults = false; + + _init(); + + function _init() { + } + + function searchKeyChanged() { + + if (vm.searchKey.length <= 2) { + vm.showResults = false; + return; + } + + resourcePoolFactory.getResourcePoolSet(vm.searchKey) + .then(data => { + vm.resourcePoolSet = data; + vm.showResults = true; + }); + } + } + } + + angular.module('main').controller(controllerId, ResourcePoolSearchController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolViewController.js b/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolViewController.js deleted file mode 100644 index 081754b4a..000000000 --- a/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolViewController.js +++ /dev/null @@ -1,38 +0,0 @@ -(function () { - 'use strict'; - - var controllerId = 'ResourcePoolViewController'; - angular.module('main') - .controller(controllerId, ['logger', 'resourcePoolFactory', '$location', '$rootScope', '$routeParams', ResourcePoolViewController]); - - function ResourcePoolViewController(logger, resourcePoolFactory, $location, $rootScope, $routeParams) { - - // Logger - logger = logger.forSource(controllerId); - - var vm = this; - vm.editorConfig = { - resourcePoolKey: $routeParams.resourcePoolKey, - userName: $routeParams.userName - }; - - _init(); - - function _init() { - - // Title - resourcePoolFactory.getResourcePoolExpanded(vm.editorConfig) - .then(function (resourcePool) { - - // Not found, navigate to 404 - if (resourcePool === null) { - $location.url('/_system/content/notFound?url=' + $location.url()); - return; - } - - // TODO viewTitle was also set in route.js? - $rootScope.viewTitle = resourcePool.Name; - }); - } - } -})(); diff --git a/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolViewController.ts b/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolViewController.ts new file mode 100644 index 000000000..989e8d91e --- /dev/null +++ b/ngClient/_system/js/app/controllers/resourcePool/ResourcePoolViewController.ts @@ -0,0 +1,47 @@ +module Main.Controller { + 'use strict'; + + var controllerId = 'ResourcePoolViewController'; + + export class ResourcePoolViewController { + + static $inject = ['logger', 'resourcePoolFactory', '$location', '$rootScope', '$routeParams']; + + constructor(logger: any, + resourcePoolFactory: any, + $location: any, + $rootScope: any, + $routeParams: any) { + + // Logger + logger = logger.forSource(controllerId); + + var vm:any = this; + vm.editorConfig = { + resourcePoolKey: $routeParams.resourcePoolKey, + userName: $routeParams.userName + }; + + _init(); + + function _init() { + + // Title + resourcePoolFactory.getResourcePoolExpanded(vm.editorConfig) + .then(resourcePool => { + + // Not found, navigate to 404 + if (resourcePool === null) { + $location.url('/_system/content/notFound?url=' + $location.url()); + return; + } + + // TODO viewTitle was also set in route.js? + $rootScope.viewTitle = resourcePool.Name; + }); + } + } + } + + angular.module('main').controller(controllerId, ResourcePoolViewController); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/directives/resourcePoolEditor/resourcePoolEditor.html b/ngClient/_system/js/app/directives/resourcePoolEditor/resourcePoolEditor.html index 748e61600..efaf4048c 100644 --- a/ngClient/_system/js/app/directives/resourcePoolEditor/resourcePoolEditor.html +++ b/ngClient/_system/js/app/directives/resourcePoolEditor/resourcePoolEditor.html @@ -152,13 +152,6 @@
-
-
- - - -
-
diff --git a/ngClient/_system/js/app/directives/resourcePoolEditor/resourcePoolEditor.js b/ngClient/_system/js/app/directives/resourcePoolEditor/resourcePoolEditor.ts similarity index 81% rename from ngClient/_system/js/app/directives/resourcePoolEditor/resourcePoolEditor.js rename to ngClient/_system/js/app/directives/resourcePoolEditor/resourcePoolEditor.ts index afacf661f..834d2b3b6 100644 --- a/ngClient/_system/js/app/directives/resourcePoolEditor/resourcePoolEditor.js +++ b/ngClient/_system/js/app/directives/resourcePoolEditor/resourcePoolEditor.ts @@ -1,16 +1,14 @@ -(function () { +module M30 { 'use strict'; var directiveId = 'resourcePoolEditor'; - angular.module('main') - .directive(directiveId, ['dataContext', 'Enums', 'logger', 'resourcePoolFactory', '$location', '$rootScope', resourcePoolEditor]); - - function resourcePoolEditor(dataContext, Enums, logger, resourcePoolFactory, $location, $rootScope) { + function resourcePoolEditor(dataContext: any, Enums: any, logger: any, resourcePoolFactory: any, $location: any, $rootScope: any) { // Logger logger = logger.forSource(directiveId); + function link(scope: any, elm: any, attrs: any); function link(scope, elm, attrs) { // Scope variables @@ -27,18 +25,15 @@ scope.changeSelectedElement = changeSelectedElement; scope.decreaseElementCellNumericValue = decreaseElementCellNumericValue; scope.decreaseElementMultiplier = decreaseElementMultiplier; - scope.decreaseElementCellMultiplier = decreaseElementCellMultiplier; scope.decreaseIndexRating = decreaseIndexRating; scope.decreaseResourcePoolRate = decreaseResourcePoolRate; scope.editResourcePool = editResourcePool; scope.increaseElementCellNumericValue = increaseElementCellNumericValue; scope.increaseElementMultiplier = increaseElementMultiplier; - scope.increaseElementCellMultiplier = increaseElementCellMultiplier; scope.increaseIndexRating = increaseIndexRating; scope.increaseResourcePoolRate = increaseResourcePoolRate; scope.resetElementCellNumericValue = resetElementCellNumericValue; scope.resetElementMultiplier = resetElementMultiplier; - scope.resetElementCellMultiplier = resetElementCellMultiplier; scope.resetIndexRating = resetIndexRating; scope.resetResourcePoolRate = resetResourcePoolRate; scope.toggleDescription = toggleDescription; @@ -52,6 +47,7 @@ /*** Implementations ***/ + function changeSelectedElement(element: any); function changeSelectedElement(element) { scope.resourcePool.selectedElement(element); loadChartData(); @@ -64,24 +60,21 @@ initialize(dataContext.getCurrentUser(), userName, resourcePoolKey); } + function decreaseElementCellNumericValue(cell: any); function decreaseElementCellNumericValue(cell) { resourcePoolFactory.updateElementCellDecimalValue(cell, 'decrease'); $rootScope.$broadcast('resourcePoolEditor_elementCellNumericValueDecreased', cell); saveChanges(); } + function decreaseElementMultiplier(element: any); function decreaseElementMultiplier(element) { resourcePoolFactory.updateElementMultiplier(element, 'decrease'); $rootScope.$broadcast('resourcePoolEditor_elementMultiplierDecreased', element); saveChanges(); } - function decreaseElementCellMultiplier(elementCell) { - resourcePoolFactory.updateElementCellMultiplier(elementCell, 'decrease'); - $rootScope.$broadcast('resourcePoolEditor_elementCellMultiplierDecreased', element); - saveChanges(); - } - + function decreaseIndexRating(field: any); function decreaseIndexRating(field) { resourcePoolFactory.updateElementFieldIndexRating(field, 'decrease'); saveChanges(); @@ -97,24 +90,21 @@ $location.url(scope.resourcePool.urlEdit()); } + function increaseElementCellNumericValue(cell: any); function increaseElementCellNumericValue(cell) { resourcePoolFactory.updateElementCellDecimalValue(cell, 'increase'); $rootScope.$broadcast('resourcePoolEditor_elementCellNumericValueIncreased', cell); saveChanges(); } + function increaseElementMultiplier(element: any); function increaseElementMultiplier(element) { resourcePoolFactory.updateElementMultiplier(element, 'increase'); $rootScope.$broadcast('resourcePoolEditor_elementMultiplierIncreased', element); saveChanges(); } - function increaseElementCellMultiplier(elementCell) { - resourcePoolFactory.updateElementCellMultiplier(elementCell, 'increase'); - $rootScope.$broadcast('resourcePoolEditor_elementCellMultiplierIncreased', element); - saveChanges(); - } - + function increaseIndexRating(field: any); function increaseIndexRating(field) { resourcePoolFactory.updateElementFieldIndexRating(field, 'increase'); saveChanges(); @@ -125,6 +115,7 @@ saveChanges(); } + function initialize(user: any, userName: any, resourcePoolKey: any); function initialize(user, userName, resourcePoolKey) { if (scope.currentUser !== user || scope.userName !== userName || scope.resourcePoolKey !== resourcePoolKey) { @@ -179,26 +170,26 @@ // Get resource pool resourcePoolFactory.getResourcePoolExpanded(resourcePoolUniqueKey) - .then(function (resourcePool) { + .then(resourcePool => { - if (typeof resourcePool === 'undefined' || resourcePool === null) { - scope.errorMessage = 'Invalid CMRP'; - return; - } + if (typeof resourcePool === 'undefined' || resourcePool === null) { + scope.errorMessage = 'Invalid CMRP'; + return; + } - // It returns an array, set the first item in the list - scope.resourcePool = resourcePool; + // It returns an array, set the first item in the list + scope.resourcePool = resourcePool; - if (scope.resourcePool.selectedElement() !== null) { - loadChartData(); - } - }) - .catch(function () { - // TODO scope.errorMessage ? - }) - .finally(function () { - scope.chartConfig.loading = false; - }); + if (scope.resourcePool.selectedElement() !== null) { + loadChartData(); + } + }) + .catch(() => { + // TODO scope.errorMessage ? + }) + .finally(() => { + scope.chartConfig.loading = false; + }); } } @@ -228,7 +219,7 @@ scope.chartConfig.options.yAxis.title = { text: '' }; chartData = []; - element.elementFieldIndexSet().forEach(function (elementFieldIndex) { + element.elementFieldIndexSet().forEach(elementFieldIndex => { var chartItem = new ElementFieldIndexChartItem(elementFieldIndex); chartData.push(chartItem); }); @@ -245,7 +236,7 @@ scope.chartConfig.options.chart = { type: 'column' }; scope.chartConfig.options.yAxis.title = { text: 'Total Income' }; - element.ElementItemSet.forEach(function (elementItem) { + element.ElementItemSet.forEach(elementItem => { var chartItem = new ColumnChartItem(elementItem); scope.chartConfig.series.push(chartItem); }); @@ -256,8 +247,8 @@ scope.chartConfig.options.yAxis.title = { text: '' }; chartData = []; - element.ElementItemSet.forEach(function (elementItem) { - elementItem.ElementCellSet.forEach(function (elementCell) { + element.ElementItemSet.forEach(elementItem => { + elementItem.ElementCellSet.forEach(elementCell => { if (elementCell.ElementField.IndexEnabled) { var chartItem = new PieChartItem(elementCell); chartData.push(chartItem); @@ -269,24 +260,21 @@ } } + function resetElementCellNumericValue(cell: any); function resetElementCellNumericValue(cell) { resourcePoolFactory.updateElementCellDecimalValue(cell, 'reset'); - $rootScope.$broadcast('resourcePoolEditor_elementCellNumericValueReset', element); + $rootScope.$broadcast('resourcePoolEditor_elementCellNumericValueReset', cell); saveChanges(); } + function resetElementMultiplier(element: any); function resetElementMultiplier(element) { resourcePoolFactory.updateElementMultiplier(element, 'reset'); $rootScope.$broadcast('resourcePoolEditor_elementMultiplierReset', element); saveChanges(); } - function resetElementCellMultiplier(elementCell) { - resourcePoolFactory.updateElementCellMultiplier(elementCell, 'reset'); - $rootScope.$broadcast('resourcePoolEditor_elementCellMultiplierReset', element); - saveChanges(); - } - + function resetIndexRating(field: any); function resetIndexRating(field) { resourcePoolFactory.updateElementFieldIndexRating(field, 'reset'); saveChanges(); @@ -319,6 +307,7 @@ loadChartData(); } + function currentUserChanged(event: any, newUser: any); function currentUserChanged(event, newUser) { initialize(newUser, scope.userName, scope.resourcePoolKey); } @@ -327,13 +316,14 @@ // TODO Store these in a better place? // TODO Also test these better, by comparing it with resourcePool.selectedElement() property! + function ColumnChartItem(elementItem: any): void; function ColumnChartItem(elementItem) { var self = this; Object.defineProperty(self, "name", { enumerable: true, configurable: true, - get: function () { + get() { return elementItem.Name; } }); @@ -341,25 +331,26 @@ Object.defineProperty(self, "data", { enumerable: true, configurable: true, - get: function () { + get() { return [elementItem.totalIncome()]; } }); } + function ElementFieldIndexChartItem(elementFieldIndex: any): void; function ElementFieldIndexChartItem(elementFieldIndex) { var self = this; Object.defineProperty(self, "name", { enumerable: true, configurable: true, - get: function () { return elementFieldIndex.Name; } + get() { return elementFieldIndex.Name; } }); Object.defineProperty(self, "y", { enumerable: true, configurable: true, - get: function () { + get() { var indexRating = elementFieldIndex.indexRating(); // TODO Make rounding better, instead of toFixed + number return Number(indexRating.toFixed(2)); @@ -367,13 +358,14 @@ }); } + function PieChartItem(elementCell: any): void; function PieChartItem(elementCell) { var self = this; Object.defineProperty(self, "name", { enumerable: true, configurable: true, - get: function () { + get() { return elementCell.ElementItem.Name; } }); @@ -381,7 +373,7 @@ Object.defineProperty(self, "y", { enumerable: true, configurable: true, - get: function () { + get() { var numericValue = elementCell.numericValue(); // TODO Make rounding better, instead of toFixed + number return Number(numericValue.toFixed(2)); @@ -392,11 +384,13 @@ return { restrict: 'E', - templateUrl: '/_system/js/app/directives/resourcePoolEditor/resourcePoolEditor.html?v=0.58.0', + templateUrl: '/_system/js/app/directives/resourcePoolEditor/resourcePoolEditor.html?v=0.62.0', scope: { config: '=' }, link: link }; } -})(); + + angular.module('main').directive(directiveId, ['dataContext', 'Enums', 'logger', 'resourcePoolFactory', '$location', '$rootScope', resourcePoolEditor]); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/Element.js b/ngClient/_system/js/app/entities/Element.ts similarity index 86% rename from ngClient/_system/js/app/entities/Element.js rename to ngClient/_system/js/app/entities/Element.ts index a8053534a..6d1c132c6 100644 --- a/ngClient/_system/js/app/entities/Element.js +++ b/ngClient/_system/js/app/entities/Element.ts @@ -1,11 +1,9 @@ -(function () { +module Main.Entities { 'use strict'; var factoryId = 'Element'; - angular.module('main') - .factory(factoryId, ['logger', '$rootScope', elementFactory]); - function elementFactory(logger, $rootScope) { + function elementFactory(logger: any, $rootScope: any) { // Logger logger = logger.forSource(factoryId); @@ -14,8 +12,8 @@ Object.defineProperty(Element.prototype, 'IsMainElement', { enumerable: true, configurable: true, - get: function () { return this.backingFields._IsMainElement; }, - set: function (value) { + get() { return this.backingFields._IsMainElement; }, + set(value) { var self = this; @@ -23,15 +21,15 @@ self.backingFields._IsMainElement = value; // TODO When this prop set in constructor, ResourcePool is null, in such case, ignore - // However, it would be better to always have a ResourcePool? / SH - 29 Nov. '15 + // However, it would be better to always have a ResourcePool? / coni2k - 29 Nov. '15 if (typeof self.ResourcePool === 'undefined' || self.ResourcePool === null) { return; } // Main element check: If there is another element that its IsMainElement flag is true, make it false if (value) { - self.ResourcePool.ElementSet.forEach(function (element) { - if (element !== self && element.IsMainElement) { + self.ResourcePool.ElementSet.forEach(element => { + if (element !== this && element.IsMainElement) { element.IsMainElement = false; } }); @@ -105,7 +103,7 @@ // TODO Check totalIncome notes var value = 0; - self.ElementItemSet.forEach(function (item) { + self.ElementItemSet.forEach(item => { value += item.directIncome(); }); @@ -127,7 +125,7 @@ // TODO Check totalIncome notes var value = 0; - self.ElementItemSet.forEach(function (item) { + self.ElementItemSet.forEach(item => { value += item.directIncomeIncludingResourcePoolAmount(); }); @@ -157,13 +155,13 @@ return (self.ElementFieldSet.length > 4) || self.elementFieldIndexSet().length > 2; } - function getElementFieldIndexSet(element) { + function getElementFieldIndexSet(element: any) { - var sortedElementFieldSet = element.ElementFieldSet.sort(function (a, b) { return a.SortOrder - b.SortOrder; }); + var sortedElementFieldSet = element.ElementFieldSet.sort((a, b) => (a.SortOrder - b.SortOrder)); var indexSet = []; // Validate - sortedElementFieldSet.forEach(function (field) { + sortedElementFieldSet.forEach(field => { if (field.IndexEnabled) { indexSet.push(field); } @@ -171,7 +169,7 @@ if (field.DataType === 6 && field.SelectedElement !== null) { var childIndexSet = getElementFieldIndexSet(field.SelectedElement); - childIndexSet.forEach(function (childIndex) { + childIndexSet.forEach(childIndex => { indexSet.push(childIndex); }); } @@ -194,7 +192,7 @@ // TODO Check totalIncome notes var value = 0; - self.ElementItemSet.forEach(function (item) { + self.ElementItemSet.forEach(item => { value += item.multiplier(); }); @@ -226,7 +224,7 @@ // TODO Check totalIncome notes var value = 0; - self.ElementItemSet.forEach(function (item) { + self.ElementItemSet.forEach(item => { value += item.resourcePoolAmount(); }); @@ -234,9 +232,7 @@ } function setDirectIncomeField() { - var result = self.ElementFieldSet.filter(function (field) { - return field.DataType === 11; - }); + var result = self.ElementFieldSet.filter(field => (field.DataType === 11)); if (result.length > 0) { self.backingFields._directIncomeField = result[0]; @@ -260,13 +256,13 @@ // TODO At the moment it's only upwards, later include children? } - function setIndexRating(updateRelated) { + function setIndexRating(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var indexSet = self.elementFieldIndexSet(); var value = 0; - indexSet.forEach(function (index) { + indexSet.forEach(index => { value += index.indexRating(); }); @@ -275,7 +271,7 @@ // Update related if (updateRelated) { - self.elementFieldIndexSet().forEach(function (index) { + self.elementFieldIndexSet().forEach(index => { index.setIndexRatingPercentage(); }); } @@ -283,9 +279,7 @@ } function setMultiplierField() { - var result = self.ElementFieldSet.filter(function (field) { - return field.DataType === 12; - }); + var result = self.ElementFieldSet.filter(field => (field.DataType === 12)); if (result.length > 0) { self.backingFields._multiplierField = result[0]; @@ -303,7 +297,7 @@ // TODO Check totalIncome notes var value = 0; - self.ElementItemSet.forEach(function (item) { + self.ElementItemSet.forEach(item => { value += item.totalDirectIncome(); }); @@ -315,7 +309,7 @@ // TODO Check totalIncome notes var value = 0; - self.ElementItemSet.forEach(function (item) { + self.ElementItemSet.forEach(item => { value += item.totalDirectIncomeIncludingResourcePoolAmount(); }); @@ -327,7 +321,7 @@ // TODO If elementItems could set their parent element's totalIncome when their totalIncome changes, it wouldn't be necessary to sum this result everytime? var value = 0; - self.ElementItemSet.forEach(function (item) { + self.ElementItemSet.forEach(item => { value += item.totalIncome(); }); @@ -355,7 +349,7 @@ value = self.ResourcePool.InitialValue; - self.ElementItemSet.forEach(function (item) { + self.ElementItemSet.forEach(item => { value += item.totalResourcePoolAmount(); }); @@ -372,7 +366,7 @@ //logger.log('TRPA-B ' + value.toFixed(2)); - self.elementFieldIndexSet().forEach(function (field) { + self.elementFieldIndexSet().forEach(field => { // TODO How about this check? // if (field.DataType === 11) { - field.setIndexIncome(); @@ -384,4 +378,8 @@ } } } -})(); \ No newline at end of file + + elementFactory.$inject = ['logger', '$rootScope']; + + angular.module('main').factory(factoryId, elementFactory); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/ElementCell.js b/ngClient/_system/js/app/entities/ElementCell.ts similarity index 78% rename from ngClient/_system/js/app/entities/ElementCell.js rename to ngClient/_system/js/app/entities/ElementCell.ts index e0a49d604..cc312a5c5 100644 --- a/ngClient/_system/js/app/entities/ElementCell.js +++ b/ngClient/_system/js/app/entities/ElementCell.ts @@ -1,11 +1,9 @@ -(function () { +module Main.Entities { 'use strict'; var factoryId = 'ElementCell'; - angular.module('main') - .factory(factoryId, ['logger', elementCellFactory]); - function elementCellFactory(logger) { + function elementCellFactory(logger: any) { // Logger logger = logger.forSource(factoryId); @@ -165,7 +163,7 @@ } // TODO Since this is a fixed value based on NumericValueCount & current user's rate, - // it could be calculated on server, check it later again / SH - 03 Aug. '15 + // it could be calculated on server, check it later again / coni2k - 03 Aug. '15 function otherUsersNumericValueCount() { // Set other users' value on the initial call @@ -177,7 +175,7 @@ } // TODO Since this is a fixed value based on NumericValueTotal & current user's rate, - // it could be calculated on server, check it later again / SH - 03 Aug. '15 + // it could be calculated on server, check it later again / coni2k - 03 Aug. '15 function otherUsersNumericValueTotal() { // Set other users' value on the initial call @@ -215,21 +213,21 @@ } // TODO Currently updateRelated is always 'false'? - function setAggressiveRating(updateRelated) { + function setAggressiveRating(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = 0; // Default value? if (self.ElementField.IndexEnabled && self.ElementField.referenceRatingMultiplied() > 0) { switch (self.ElementField.IndexSortType) { - case 1: { // HighestToLowest (High rating is better) - value = (1 - self.numericValueMultipliedPercentage()) / self.ElementField.referenceRatingMultiplied(); - break; - } - case 2: { // LowestToHighest (Low rating is better) - value = self.numericValueMultiplied() / self.ElementField.referenceRatingMultiplied(); - break; - } + case 1: { // HighestToLowest (High rating is better) + value = (1 - self.numericValueMultipliedPercentage()) / self.ElementField.referenceRatingMultiplied(); + break; + } + case 2: { // LowestToHighest (Low rating is better) + value = self.numericValueMultiplied() / self.ElementField.referenceRatingMultiplied(); + break; + } } if (!self.ElementField.referenceRatingAllEqualFlag()) { @@ -247,24 +245,24 @@ } } - function setCurrentUserNumericValue(updateRelated) { + function setCurrentUserNumericValue(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value; var userCell = self.currentUserCell(); switch (self.ElementField.DataType) { - case 2: { value = userCell !== null ? userCell.BooleanValue : 0; break; } - case 3: { value = userCell !== null ? userCell.IntegerValue : 0; break; } - case 4: { value = userCell !== null ? userCell.DecimalValue : 50; /* Default value? */ break; } - // TODO 5 (DateTime?) - case 11: { - // DirectIncome: No need to try user's cell, always return all users', which will be CMRP owner's value - value = self.NumericValueTotal !== null ? self.NumericValueTotal : 0; - break; - } - case 12: { value = userCell !== null ? userCell.DecimalValue : 0; /* Default value? */ break; } - // default: { throw 'currentUserNumericValue() - Not supported element field type: ' + self.ElementField.DataType; } + case 2: { value = userCell !== null ? userCell.BooleanValue : 0; break; } + case 3: { value = userCell !== null ? userCell.IntegerValue : 0; break; } + case 4: { value = userCell !== null ? userCell.DecimalValue : 50; /* Default value? */ break; } + // TODO 5 (DateTime?) + case 11: { + // DirectIncome: No need to try user's cell, always return all users', which will be CMRP owner's value + value = self.NumericValueTotal !== null ? self.NumericValueTotal : 0; + break; + } + case 12: { value = userCell !== null ? userCell.DecimalValue : 0; /* Default value? */ break; } + // default: { throw 'currentUserNumericValue() - Not supported element field type: ' + self.ElementField.DataType; } } if (self.backingFields._currentUserNumericValue !== value) { @@ -277,7 +275,7 @@ } } - function setIndexIncome(updateRelated) { + function setIndexIncome(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = 0; // Default value? @@ -300,15 +298,15 @@ } } - function setNumericValue(updateRelated) { + function setNumericValue(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value; if (typeof self.ElementField !== 'undefined') { switch (self.ElementField.Element.ResourcePool.RatingMode) { - case 1: { value = self.currentUserNumericValue(); break; } // Current user's - case 2: { value = self.numericValueAverage(); break; } // All + case 1: { value = self.currentUserNumericValue(); break; } // Current user's + case 2: { value = self.numericValueAverage(); break; } // All } } @@ -329,7 +327,7 @@ } } - function setNumericValueMultiplied(updateRelated) { + function setNumericValueMultiplied(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value; @@ -358,12 +356,12 @@ // which meanwhile will call referenceRatingMultiplied() method anyway. So it becomes redundant. // This code block could possibly be improved with a IndexSortType switch case, // but it seems it would be bit overkill. - // Still something to think about it later? / SH - 22 Oct. '15 + // Still something to think about it later? / coni2k - 22 Oct. '15 //self.ElementField.setReferenceRatingMultiplied(); } } - function setNumericValueMultipliedPercentage(updateRelated) { + function setNumericValueMultipliedPercentage(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = 0; @@ -403,22 +401,22 @@ var userValue = 0; switch (self.ElementField.DataType) { // TODO Check bool to decimal conversion? - case 2: { userValue = self.UserElementCellSet[0].BooleanValue; break; } - case 3: { userValue = self.UserElementCellSet[0].IntegerValue; break; } - case 4: { userValue = self.UserElementCellSet[0].DecimalValue; break; } - // TODO 5 - DateTime? - case 11: { userValue = self.UserElementCellSet[0].DecimalValue; break; } - // TODO 12 - Multiplier? - //default: { - // throw 'setOtherUsersNumericValueTotal - Not supported element field type: ' + self.ElementField.DataType; - //} + case 2: { userValue = self.UserElementCellSet[0].BooleanValue; break; } + case 3: { userValue = self.UserElementCellSet[0].IntegerValue; break; } + case 4: { userValue = self.UserElementCellSet[0].DecimalValue; break; } + // TODO 5 - DateTime? + case 11: { userValue = self.UserElementCellSet[0].DecimalValue; break; } + // TODO 12 - Multiplier? + //default: { + // throw 'setOtherUsersNumericValueTotal - Not supported element field type: ' + self.ElementField.DataType; + //} } self.backingFields._otherUsersNumericValueTotal -= userValue; } } - function setPassiveRating(updateRelated) { + function setPassiveRating(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = 0; @@ -426,16 +424,16 @@ if (self.ElementField.IndexEnabled) { switch (self.ElementField.IndexSortType) { - case 1: { // HightestToLowest (High rating is better) - value = self.numericValueMultipliedPercentage(); - break; - } - case 2: { // LowestToHighest (Low rating is better) - if (self.ElementField.passiveRating() > 0) { - value = (1 - self.numericValueMultipliedPercentage()) / self.ElementField.passiveRating(); - } - break; + case 1: { // HightestToLowest (High rating is better) + value = self.numericValueMultipliedPercentage(); + break; + } + case 2: { // LowestToHighest (Low rating is better) + if (self.ElementField.passiveRating() > 0) { + value = (1 - self.numericValueMultipliedPercentage()) / self.ElementField.passiveRating(); } + break; + } } } @@ -449,7 +447,7 @@ } } - function setRating(updateRelated) { + function setRating(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = 0; @@ -459,16 +457,16 @@ value = 1; } else { switch (self.ElementField.IndexCalculationType) { - case 1: // Aggressive rating - { - value = self.aggressiveRating(); - break; - } - case 2: // Passive rating - { - value = self.passiveRating(); - break; - } + case 1: // Aggressive rating + { + value = self.aggressiveRating(); + break; + } + case 2: // Passive rating + { + value = self.passiveRating(); + break; + } } } @@ -482,7 +480,7 @@ } } - function setRatingPercentage(updateRelated) { + function setRatingPercentage(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = 0; @@ -509,42 +507,46 @@ // : null; switch (self.ElementField.DataType) { - case 1: { - if (self.UserElementCellSet.length > 0) { - value = self.UserElementCellSet[0].StringValue; - } - break; + case 1: { + if (self.UserElementCellSet.length > 0) { + value = self.UserElementCellSet[0].StringValue; } - case 2: { - if (self.UserElementCellSet.length > 0) { - value = self.UserElementCellSet[0].BooleanValue ? 'True' : 'False'; - } - break; + break; + } + case 2: { + if (self.UserElementCellSet.length > 0) { + value = self.UserElementCellSet[0].BooleanValue ? 'True' : 'False'; } - case 3: { - if (self.UserElementCellSet.length > 0) { - value = self.UserElementCellSet[0].IntegerValue; - } - break; + break; + } + case 3: { + if (self.UserElementCellSet.length > 0) { + value = self.UserElementCellSet[0].IntegerValue; } - // TODO 5 (DateTime?) - case 4: - case 11: - case 12: { - if (self.UserElementCellSet.length > 0) { - value = self.UserElementCellSet[0].DecimalValue; - } - break; + break; + } + // TODO 5 (DateTime?) + case 4: + case 11: + case 12: { + if (self.UserElementCellSet.length > 0) { + value = self.UserElementCellSet[0].DecimalValue; } - case 6: { - if (self.SelectedElementItem !== null) { - value = self.SelectedElementItem.Name; - } + break; + } + case 6: { + if (self.SelectedElementItem !== null) { + value = self.SelectedElementItem.Name; } } + } return value; } } } -})(); \ No newline at end of file + + elementCellFactory.$inject = ['logger']; + + angular.module('main').factory(factoryId, ['logger', elementCellFactory]); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/ElementField.js b/ngClient/_system/js/app/entities/ElementField.ts similarity index 84% rename from ngClient/_system/js/app/entities/ElementField.js rename to ngClient/_system/js/app/entities/ElementField.ts index f688d31c9..c121099c7 100644 --- a/ngClient/_system/js/app/entities/ElementField.js +++ b/ngClient/_system/js/app/entities/ElementField.ts @@ -1,11 +1,9 @@ -(function () { +module Main.Entities { 'use strict'; var factoryId = 'ElementField'; - angular.module('main') - .factory(factoryId, ['logger', '$rootScope', elementFieldFactory]); - function elementFieldFactory(logger, $rootScope) { + function elementFieldFactory(logger: any, $rootScope: any) { // Logger logger = logger.forSource(factoryId); @@ -14,8 +12,8 @@ Object.defineProperty(ElementField.prototype, 'DataType', { enumerable: true, configurable: true, - get: function () { return this.backingFields._dataType; }, - set: function (value) { + get() { return this.backingFields._dataType; }, + set(value) { var self = this; if (self.backingFields._dataType !== value) { @@ -31,8 +29,8 @@ Object.defineProperty(ElementField.prototype, 'IndexEnabled', { enumerable: true, configurable: true, - get: function () { return this.backingFields._indexEnabled; }, - set: function (value) { + get() { return this.backingFields._indexEnabled; }, + set(value) { if (this.backingFields._indexEnabled !== value) { this.backingFields._indexEnabled = value; @@ -217,7 +215,7 @@ } // TODO Since this is a fixed value based on IndexRatingCount & current user's rate, - // it could be calculated on server, check it later again / SH - 03 Aug. '15 + // it could be calculated on server, check it later again / coni2k - 03 Aug. '15 function otherUsersIndexRatingCount() { // Set other users' value on the initial call @@ -229,7 +227,7 @@ } // TODO Since this is a fixed value based on IndexRatingTotal & current user's rate, - // it could be calculated on server, check it later again / SH - 03 Aug. '15 + // it could be calculated on server, check it later again / coni2k - 03 Aug. '15 function otherUsersIndexRatingTotal() { // Set other users' value on the initial call @@ -258,7 +256,7 @@ return self.backingFields._rating; } - function referenceRatingAllEqualFlag(value) { + function referenceRatingAllEqualFlag(value: any) { return self.backingFields._referenceRatingAllEqualFlag; } @@ -271,7 +269,7 @@ return self.backingFields._referenceRatingMultiplied; } - function setCurrentUserIndexRating(updateRelated) { + function setCurrentUserIndexRating(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = self.currentUserElementField() !== null ? @@ -288,7 +286,7 @@ } } - function setIndexIncome(updateRelated) { + function setIndexIncome(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = self.Element.totalResourcePoolAmount() * self.indexRatingPercentage(); @@ -302,21 +300,21 @@ // Update related if (updateRelated) { - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { cell.setIndexIncome(); }); } } } - function setIndexRating(updateRelated) { + function setIndexRating(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = 0; // Default value? switch (self.Element.ResourcePool.RatingMode) { - case 1: { value = self.currentUserIndexRating(); break; } // Current user's - case 2: { value = self.indexRatingAverage(); break; } // All + case 1: { value = self.currentUserIndexRating(); break; } // Current user's + case 2: { value = self.indexRatingAverage(); break; } // All } //logger.log(self.Name[0] + ' IR ' + value.toFixed(2)); @@ -331,7 +329,7 @@ } } - function setIndexRatingPercentage(updateRelated) { + function setIndexRatingPercentage(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = 0; // Default value? @@ -356,7 +354,7 @@ } } - function setNumericValueMultiplied(updateRelated) { + function setNumericValueMultiplied(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = 0; // Default value? @@ -365,7 +363,7 @@ if (self.ElementCellSet.length === 0) { value = 0; // ? } else { - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { value += cell.numericValueMultiplied(); //logger.log(self.Name[0] + '-' + cell.ElementItem.Name[0] + ' NVMA ' + cell.numericValueMultiplied()); }); @@ -379,35 +377,35 @@ // Update related? if (updateRelated && self.IndexEnabled) { - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { cell.setNumericValueMultipliedPercentage(false); }); self.setPassiveRating(false); - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { cell.setPassiveRating(false); }); self.setReferenceRatingMultiplied(false); - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { cell.setAggressiveRating(false); }); - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { cell.setRating(false); }); self.setRating(false); - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { cell.setRatingPercentage(false); }); //self.setIndexIncome(false); - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { cell.setIndexIncome(false); }); } @@ -434,12 +432,12 @@ } } - function setPassiveRating(updateRelated) { + function setPassiveRating(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = 0; - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { value += 1 - cell.numericValueMultipliedPercentage(); }); @@ -452,13 +450,13 @@ } } - function setRating(updateRelated) { + function setRating(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = 0; // Default value? // Validate - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { value += cell.rating(); }); @@ -472,7 +470,7 @@ if (updateRelated) { // Update related - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { cell.setRatingPercentage(false); }); @@ -481,7 +479,7 @@ } } - function setReferenceRatingAllEqualFlag(value) { + function setReferenceRatingAllEqualFlag(value: any) { if (self.backingFields._referenceRatingAllEqualFlag !== value) { self.backingFields._referenceRatingAllEqualFlag = value; @@ -491,7 +489,7 @@ } // TODO Currently updateRelated is always 'false'? - function setReferenceRatingMultiplied(updateRelated) { + function setReferenceRatingMultiplied(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = null; @@ -502,47 +500,47 @@ value = 0; // ? } else { - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { if (value === null) { switch (self.IndexSortType) { - case 1: { // HighestToLowest (High number is better) - value = (1 - cell.numericValueMultipliedPercentage()); - break; - } - case 2: { // LowestToHighest (Low number is better) - value = cell.numericValueMultiplied(); - break; - } + case 1: { // HighestToLowest (High number is better) + value = (1 - cell.numericValueMultipliedPercentage()); + break; + } + case 2: { // LowestToHighest (Low number is better) + value = cell.numericValueMultiplied(); + break; + } } } else { switch (self.IndexSortType) { - case 1: { // HighestToLowest (High number is better) - - if (1 - cell.numericValueMultipliedPercentage() !== value) { - allEqualFlag = false; - } + case 1: { // HighestToLowest (High number is better) - if (1 - cell.numericValueMultipliedPercentage() > value) { - value = 1 - cell.numericValueMultipliedPercentage(); - } - break; + if (1 - cell.numericValueMultipliedPercentage() !== value) { + allEqualFlag = false; } - case 2: { // LowestToHighest (Low number is better) - if (cell.numericValueMultiplied() !== value) { - allEqualFlag = false; - } + if (1 - cell.numericValueMultipliedPercentage() > value) { + value = 1 - cell.numericValueMultipliedPercentage(); + } + break; + } + case 2: { // LowestToHighest (Low number is better) - if (cell.numericValueMultiplied() > value) { - value = cell.numericValueMultiplied(); - } + if (cell.numericValueMultiplied() !== value) { + allEqualFlag = false; + } - break; + if (cell.numericValueMultiplied() > value) { + value = cell.numericValueMultiplied(); } + + break; + } } } }); @@ -568,7 +566,7 @@ // TODO ?! - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { cell.setAggressiveRating(false); }); @@ -578,4 +576,8 @@ } } -})(); \ No newline at end of file + + elementFieldFactory.$inject = ['logger', '$rootScope']; + + angular.module('main').factory(factoryId, elementFieldFactory); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/ElementItem.js b/ngClient/_system/js/app/entities/ElementItem.ts similarity index 89% rename from ngClient/_system/js/app/entities/ElementItem.js rename to ngClient/_system/js/app/entities/ElementItem.ts index af0f47f28..8cc402be1 100644 --- a/ngClient/_system/js/app/entities/ElementItem.js +++ b/ngClient/_system/js/app/entities/ElementItem.ts @@ -1,11 +1,9 @@ -(function () { +module Main.Entities { 'use strict'; var factoryId = 'ElementItem'; - angular.module('main') - .factory(factoryId, ['logger', elementItemFactory]); - function elementItemFactory(logger) { + function elementItemFactory(logger: any) { // Logger logger = logger.forSource(factoryId); @@ -80,14 +78,12 @@ return self.backingFields._elementCellIndexSet; } - function getElementCellIndexSet(elementItem) { + function getElementCellIndexSet(elementItem: any) { var indexSet = []; - var sortedElementCellSet = elementItem.ElementCellSet.sort(function (a, b) { - return a.ElementField.SortOrder - b.ElementField.SortOrder; - }); + var sortedElementCellSet = elementItem.ElementCellSet.sort((a, b) => (a.ElementField.SortOrder - b.ElementField.SortOrder)); - sortedElementCellSet.forEach(function (cell) { + sortedElementCellSet.forEach(cell => { if (cell.ElementField.IndexEnabled) { indexSet.push(cell); @@ -138,15 +134,13 @@ return self.backingFields._resourcePoolAmount; } - function setDirectIncome(updateRelated) { + function setDirectIncome(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; // First, find direct income cell var directIncomeCell = null; - var result = self.ElementCellSet.filter(function (elementCell) { - return elementCell.ElementField.DataType === 11; - }); + var result = self.ElementCellSet.filter(elementCell => (elementCell.ElementField.DataType === 11)); if (result.length > 0) { directIncomeCell = result[0]; @@ -174,15 +168,13 @@ self.backingFields._elementCellIndexSet = getElementCellIndexSet(self); } - function setMultiplier(updateRelated) { + function setMultiplier(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; // First, find the multiplier cell var multiplierCell = null; - var result = self.ElementCellSet.filter(function(elementCell) { - return elementCell.ElementField.DataType === 12; - }); + var result = self.ElementCellSet.filter(elementCell => (elementCell.ElementField.DataType === 12)); if (result.length > 0) { multiplierCell = result[0]; @@ -214,7 +206,7 @@ } } - function setResourcePoolAmount(updateRelated) { + function setResourcePoolAmount(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = self.directIncome() * self.Element.ResourcePool.resourcePoolRatePercentage(); @@ -229,7 +221,7 @@ } } - function setTotalDirectIncome(updateRelated) { + function setTotalDirectIncome(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = self.directIncome() * self.multiplier(); @@ -244,7 +236,7 @@ } } - function setTotalResourcePoolAmount(updateRelated) { + function setTotalResourcePoolAmount(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = self.resourcePoolAmount() * self.multiplier(); @@ -292,7 +284,7 @@ var value = 0; - self.ElementCellSet.forEach(function (cell) { + self.ElementCellSet.forEach(cell => { value += cell.indexIncome(); }); @@ -301,7 +293,7 @@ // Update related // TODO Is this correct? It looks like it didn't affect anything? - self.ParentCellSet.forEach(function (parentCell) { + self.ParentCellSet.forEach(parentCell => { parentCell.setIndexIncome(); }); } @@ -311,4 +303,8 @@ } } -})(); \ No newline at end of file + + elementItemFactory.$inject = ['logger']; + + angular.module('main').factory(factoryId, elementItemFactory); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/Enums.js b/ngClient/_system/js/app/entities/Enums.ts similarity index 88% rename from ngClient/_system/js/app/entities/Enums.js rename to ngClient/_system/js/app/entities/Enums.ts index 45425fab5..946103d14 100644 --- a/ngClient/_system/js/app/entities/Enums.js +++ b/ngClient/_system/js/app/entities/Enums.ts @@ -1,16 +1,19 @@ -(function () { +module Main.Entities { 'use strict'; var factoryId = 'Enums'; - angular.module('main') - .factory(factoryId, ['logger', enumsFactory]); - function enumsFactory(logger) { + function enumsFactory(logger: any) { // Logger logger = logger.forSource(factoryId); - var self = {}; + var self = { + ElementFieldDataType: {}, + ElementFieldIndexCalculationType: {}, + ElementFieldIndexSortType: {}, + getEnumKey: getEnumKey + }; self.ElementFieldDataType = { @@ -73,7 +76,7 @@ 'Lowest': 2 }; - self.getEnumKey = function (enumTableKey, value) { + function getEnumKey(enumTableKey: any, value: any) { for (var tableKey in self) { // Ignore these tables @@ -90,8 +93,12 @@ } } } - }; + } return self; } -})(); + + enumsFactory.$inject = ['logger']; + + angular.module('main').factory(factoryId, enumsFactory); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/ResourcePool.js b/ngClient/_system/js/app/entities/ResourcePool.ts similarity index 76% rename from ngClient/_system/js/app/entities/ResourcePool.js rename to ngClient/_system/js/app/entities/ResourcePool.ts index a1f93a1d5..0f07eb408 100644 --- a/ngClient/_system/js/app/entities/ResourcePool.js +++ b/ngClient/_system/js/app/entities/ResourcePool.ts @@ -1,11 +1,9 @@ -(function () { +module Main.Entities { 'use strict'; var factoryId = 'ResourcePool'; - angular.module('main') - .factory(factoryId, ['logger', resourcePoolFactory]); - function resourcePoolFactory(logger) { + function resourcePoolFactory(logger: any) { // Logger logger = logger.forSource(factoryId); @@ -14,10 +12,10 @@ Object.defineProperty(ResourcePool.prototype, 'Name', { enumerable: true, configurable: true, - get: function () { + get() { return this.backingFields._name; }, - set: function (value) { + set(value) { var oldStripped = this.stripInvalidChars(this.backingFields._name); @@ -35,10 +33,10 @@ Object.defineProperty(ResourcePool.prototype, 'Key', { enumerable: true, configurable: true, - get: function () { + get() { return this.backingFields._key; }, - set: function (value) { + set(value) { var newValue = this.stripInvalidChars(value); @@ -51,8 +49,8 @@ Object.defineProperty(ResourcePool.prototype, 'UseFixedResourcePoolRate', { enumerable: true, configurable: true, - get: function () { return this.backingFields._useFixedResourcePoolRate; }, - set: function (value) { + get() { return this.backingFields._useFixedResourcePoolRate; }, + set(value) { if (this.backingFields._useFixedResourcePoolRate !== value) { this.backingFields._useFixedResourcePoolRate = value; @@ -66,16 +64,16 @@ Object.defineProperty(ResourcePool.prototype, 'RatingMode', { enumerable: true, configurable: true, - get: function () { return this.backingFields._ratingMode; }, - set: function (value) { + get() { return this.backingFields._ratingMode; }, + set(value) { if (this.backingFields._ratingMode !== value) { this.backingFields._ratingMode = value; this.setResourcePoolRate(); - this.ElementSet.forEach(function (element) { + this.ElementSet.forEach(element => { - element.ElementFieldSet.forEach(function (field) { + element.ElementFieldSet.forEach(field => { // Field calculations if (field.IndexEnabled) { @@ -83,19 +81,19 @@ } if (!field.UseFixedValue) { - field.ElementCellSet.forEach(function (cell) { + field.ElementCellSet.forEach(cell => { // Cell calculations switch (field.DataType) { - case 2: - case 3: - case 4: - // TODO 5 (DateTime?) - case 11: - case 12: { - cell.setNumericValue(); - break; - } + case 2: + case 3: + case 4: + // TODO 5 (DateTime?) + case 11: + case 12: { + cell.setNumericValue(); + break; + } } }); } @@ -171,7 +169,7 @@ /*** Implementations ***/ // Should be called after createEntity or retrieving it from server - function _init(setComputedFields) { + function _init(setComputedFields: any) { setComputedFields = typeof setComputedFields !== 'undefined' ? setComputedFields : false; // Set initial values of computed fields @@ -180,7 +178,7 @@ var userRatings = []; // ResourcePool - self.UserResourcePoolSet.forEach(function (userResourcePool) { + self.UserResourcePoolSet.forEach(userResourcePool => { self.ResourcePoolRateTotal += userResourcePool.ResourcePoolRate; self.ResourcePoolRateCount += 1; @@ -190,9 +188,9 @@ }); // Fields - self.ElementSet.forEach(function (element) { - element.ElementFieldSet.forEach(function (elementField) { - elementField.UserElementFieldSet.forEach(function (userElementField) { + self.ElementSet.forEach(element => { + element.ElementFieldSet.forEach(elementField => { + elementField.UserElementFieldSet.forEach(userElementField => { elementField.IndexRatingTotal += userElementField.IndexRating; elementField.IndexRatingCount += 1; @@ -202,8 +200,8 @@ }); // Cells - elementField.ElementCellSet.forEach(function (elementCell) { - elementCell.UserElementCellSet.forEach(function (userElementCell) { + elementField.ElementCellSet.forEach(elementCell => { + elementCell.UserElementCellSet.forEach(userElementCell => { elementCell.StringValue = ''; // TODO ? elementCell.NumericValueTotal += userElementCell.DecimalValue; // TODO Correct approach? elementCell.NumericValueCount += 1; @@ -228,18 +226,18 @@ // Elements if (typeof self.ElementSet !== 'undefined') { - self.ElementSet.forEach(function (element) { + self.ElementSet.forEach(element => { // Fields if (typeof element.ElementFieldSet !== 'undefined') { - element.ElementFieldSet.forEach(function (field) { + element.ElementFieldSet.forEach(field => { field.setOtherUsersIndexRatingTotal(); field.setOtherUsersIndexRatingCount(); // Cells if (typeof field.ElementCellSet !== 'undefined') { - field.ElementCellSet.forEach(function (cell) { + field.ElementCellSet.forEach(cell => { cell.setOtherUsersNumericValueTotal(); cell.setOtherUsersNumericValueCount(); @@ -301,15 +299,13 @@ } function mainElement() { - var result = self.ElementSet.filter(function (element) { - return element.IsMainElement; - }); + var result = self.ElementSet.filter(element => element.IsMainElement); return result.length > 0 ? result[0] : null; } // TODO Since this is a fixed value based on ResourcePoolRateCount & current user's rate, - // it could be calculated on server, check it later again / SH - 03 Aug. '15 + // it could be calculated on server, check it later again / coni2k - 03 Aug. '15 function otherUsersResourcePoolRateCount() { // Set other users' value on the initial call @@ -321,7 +317,7 @@ } // TODO Since this is a fixed value based on ResourcePoolRateTotal & current user's rate, - // it could be calculated on server, check it later again / SH - 03 Aug. '15 + // it could be calculated on server, check it later again / coni2k - 03 Aug. '15 function otherUsersResourcePoolRateTotal() { // Set other users' value on the initial call @@ -377,7 +373,7 @@ self.otherUsersResourcePoolRateTotal() + self.currentUserResourcePoolRate(); } - function selectedElement(value) { + function selectedElement(value: any) { // Set new value if (typeof value !== 'undefined' && self.backingFields._selectedElement !== value) { @@ -392,7 +388,7 @@ return self.backingFields._selectedElement; } - function setCurrentUserResourcePoolRate(updateRelated) { + function setCurrentUserResourcePoolRate(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = self.currentUserResourcePool() !== null ? @@ -430,7 +426,7 @@ } } - function setResourcePoolRate(updateRelated) { + function setResourcePoolRate(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value; @@ -439,8 +435,8 @@ value = self.resourcePoolRateAverage(); } else { switch (self.RatingMode) { - case 1: { value = self.currentUserResourcePoolRate(); break; } // Current user's - case 2: { value = self.resourcePoolRateAverage(); break; } // All + case 1: { value = self.currentUserResourcePoolRate(); break; } // Current user's + case 2: { value = self.resourcePoolRateAverage(); break; } // All } } @@ -454,7 +450,7 @@ } } - function setResourcePoolRatePercentage(updateRelated) { + function setResourcePoolRatePercentage(updateRelated: any) { updateRelated = typeof updateRelated === 'undefined' ? true : updateRelated; var value = self.resourcePoolRate() === 0 ? @@ -466,9 +462,9 @@ // Update related if (updateRelated) { - self.ElementSet.forEach(function (element) { + self.ElementSet.forEach(element => { - element.ElementItemSet.forEach(function (item) { + element.ElementItemSet.forEach(item => { item.setResourcePoolAmount(); }); }); @@ -476,7 +472,7 @@ } } - function stripInvalidChars(value) { + function stripInvalidChars(value: string) { // Trim, remove special chars and replace space with dash if (value !== null) { @@ -493,7 +489,7 @@ } // TODO Most of these functions are related with userService.js - updateX functions - // Try to merge these two - Actually try to handle these actions within the related entity / SH - 27 Nov. '15 + // Try to merge these two - Actually try to handle these actions within the related entity / coni2k - 27 Nov. '15 function updateCache() { var isUnchanged = false; @@ -502,73 +498,73 @@ // Elements if (typeof self.ElementSet !== 'undefined') { - self.ElementSet.forEach(function (element) { + self.ElementSet.forEach(element => { - // TODO Review this later / SH - 24 Nov. '15 + // TODO Review this later / coni2k - 24 Nov. '15 element.setElementFieldIndexSet(); // Fields if (typeof element.ElementFieldSet !== 'undefined') { - element.ElementFieldSet.forEach(function (field) { + element.ElementFieldSet.forEach(field => { if (field.IndexEnabled) { // TODO Actually index rating can't be set through resourcePoolEdit page and no need to update this cache - // But still keep it as a reminder? / SH - 29 Nov. '15 + // But still keep it as a reminder? / coni2k - 29 Nov. '15 field.setCurrentUserIndexRating(); } // Cells if (typeof field.ElementCellSet !== 'undefined') { - field.ElementCellSet.forEach(function (cell) { + field.ElementCellSet.forEach(cell => { switch (cell.ElementField.DataType) { - case 1: { - // TODO Again what a mess! - // StringValue is a computed value, it should normally come from the server - // But in case resource pool was just created, then it should be directly set like this. - // Otherwise, it doesn't show its value on editor. - // And on top of it, since it changes, breeze thinks that 'cell' is modified and tries to send it server - // which results an error. So that's why modified check & acceptChanges parts were added. - // SH - 01 Dec. '15 - if (cell.UserElementCellSet.length > 0) { - isUnchanged = cell.entityAspect.entityState.isUnchanged(); - cell.StringValue = cell.UserElementCellSet[0].StringValue; - if (isUnchanged) { cell.entityAspect.acceptChanges(); } - } + case 1: { + // TODO Again what a mess! + // StringValue is a computed value, it should normally come from the server + // But in case resource pool was just created, then it should be directly set like this. + // Otherwise, it doesn't show its value on editor. + // And on top of it, since it changes, breeze thinks that 'cell' is modified and tries to send it server + // which results an error. So that's why modified check & acceptChanges parts were added. + // coni2k - 01 Dec. '15 + if (cell.UserElementCellSet.length > 0) { + isUnchanged = cell.entityAspect.entityState.isUnchanged(); + cell.StringValue = cell.UserElementCellSet[0].StringValue; + if (isUnchanged) { cell.entityAspect.acceptChanges(); } + } + break; + } + case 2: + case 3: + case 4: + // TODO DateTime? + { + cell.setCurrentUserNumericValue(); break; } - case 2: - case 3: - case 4: - // TODO DateTime? - { - cell.setCurrentUserNumericValue(); - break; - } - case 11: - { - // TODO DirectIncome is always calculated from NumericValueTotal - // Which is actually not correct but till that its fixed, update it like this / SH - 29 Nov. '15 - // Also check 'What a mess' of StringValue - if (cell.UserElementCellSet.length > 0) { - isUnchanged = cell.entityAspect.entityState.isUnchanged(); - cell.NumericValueTotal = cell.UserElementCellSet[0].DecimalValue; - if (isUnchanged) { cell.entityAspect.acceptChanges(); } - } - - cell.setCurrentUserNumericValue(); - break; - } - case 12: - { - cell.ElementItem.setMultiplier(); - - if (cell.ElementField.IndexEnabled) { - cell.setNumericValueMultiplied(); - } - - break; - } + case 11: + { + // TODO DirectIncome is always calculated from NumericValueTotal + // Which is actually not correct but till that its fixed, update it like this / coni2k - 29 Nov. '15 + // Also check 'What a mess' of StringValue + if (cell.UserElementCellSet.length > 0) { + isUnchanged = cell.entityAspect.entityState.isUnchanged(); + cell.NumericValueTotal = cell.UserElementCellSet[0].DecimalValue; + if (isUnchanged) { cell.entityAspect.acceptChanges(); } + } + + cell.setCurrentUserNumericValue(); + break; + } + case 12: + { + cell.ElementItem.setMultiplier(); + + if (cell.ElementField.IndexEnabled) { + cell.setNumericValueMultiplied(); + } + + break; + } } }); } @@ -587,4 +583,8 @@ } } } -})(); \ No newline at end of file + + resourcePoolFactory.$inject = ['logger']; + + angular.module('main').factory(factoryId, resourcePoolFactory); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/User.js b/ngClient/_system/js/app/entities/User.js deleted file mode 100644 index e28624ba7..000000000 --- a/ngClient/_system/js/app/entities/User.js +++ /dev/null @@ -1,56 +0,0 @@ -(function () { - 'use strict'; - - var factoryId = 'User'; - angular.module('main') - .factory(factoryId, ['logger', userFactory]); - - function userFactory(logger) { - - // Logger - logger = logger.forSource(factoryId); - - // Return - return User; - - function User() { - - var self = this; - - // Server-side - self.Id = 0; - self.Email = ''; - self.EmailConfirmed = false; - self.IsAnonymous = false; - self.UserName = ''; - self.SingleUseToken = null; - self.HasPassword = false; - self.FirstName = ''; - self.MiddleName = ''; - self.LastName = ''; - self.PhoneNumber = ''; - self.PhoneNumberConfirmed = false; - self.TwoFactorEnabled = false; - self.AccessFailedCount = 0; - self.LockoutEnabled = false; - self.LockoutEndDateUtc = null; - self.Notes = ''; - self.CreatedOn = new Date(); - self.ModifiedOn = new Date(); - self.DeletedOn = null; - // TODO breezejs - Cannot assign a navigation property in an entity ctor - //self.Claims = null; - //self.Logins = []; - //self.Roles = []; - - // Functions - self.isAuthenticated = isAuthenticated; - - /*** Implementations ***/ - - function isAuthenticated() { - return self.Id > 0; - } - } - } -})(); \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/User.ts b/ngClient/_system/js/app/entities/User.ts new file mode 100644 index 000000000..abd5c7f70 --- /dev/null +++ b/ngClient/_system/js/app/entities/User.ts @@ -0,0 +1,37 @@ +module Main.Entities { + 'use strict'; + + export class User { + + // Server-side + Id = 0; + Email = ''; + EmailConfirmed = false; + IsAnonymous = false; + UserName = ''; + SingleUseToken = null; + HasPassword = false; + FirstName = ''; + MiddleName = ''; + LastName = ''; + PhoneNumber = ''; + PhoneNumberConfirmed = false; + TwoFactorEnabled = false; + AccessFailedCount = 0; + LockoutEnabled = false; + LockoutEndDateUtc = null; + Notes = ''; + CreatedOn = new Date(); + ModifiedOn = new Date(); + DeletedOn = null; + // TODO breezejs - Cannot assign a navigation property in an entity ctor + //Claims = null; + //Logins = []; + //Roles = []; + + // Functions + isAuthenticated() { + return this.Id > 0; + } + } +} \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/UserElementCell.js b/ngClient/_system/js/app/entities/UserElementCell.js deleted file mode 100644 index 13e8b0300..000000000 --- a/ngClient/_system/js/app/entities/UserElementCell.js +++ /dev/null @@ -1,47 +0,0 @@ -(function () { - 'use strict'; - - var factoryId = 'UserElementCell'; - angular.module('main') - .factory(factoryId, ['logger', userElementCellFactory]); - - function userElementCellFactory(logger) { - - // Logger - logger = logger.forSource(factoryId); - - // Properties - Object.defineProperty(UserElementCell.prototype, 'DecimalValue', { - enumerable: true, - configurable: true, - get: function () { return this.backingFields._DecimalValue; }, - set: function (value) { - if (this.backingFields._DecimalValue !== value) { - this.backingFields._DecimalValue = value; - } - } - }); - - // Return - return UserElementCell; - - function UserElementCell() { - - var self = this; - - // Server-side - self.UserId = 0; - self.ElementCellId = 0; - self.StringValue = null; - self.BooleanValue = null; - self.IntegerValue = null; - // - self.DateTimeValue = null; - - // Local variables - self.backingFields = { - _DecimalValue: null - }; - } - } -})(); \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/UserElementCell.ts b/ngClient/_system/js/app/entities/UserElementCell.ts new file mode 100644 index 000000000..14a65cc69 --- /dev/null +++ b/ngClient/_system/js/app/entities/UserElementCell.ts @@ -0,0 +1,64 @@ +module Main.Entities { + 'use strict'; + + export class UserElementCell { + + // Server-side + UserId = 0; + ElementCellId = 0; + StringValue = null; + BooleanValue = null; + IntegerValue = null; + DateTimeValue = null; + DecimalValue = null; + } + + //angular.module('main').controller('x', UserElementCell); + //angular.module('main').controller(controllerId, AccountController); + + //var factoryId = 'UserElementCell'; + + //function userElementCellFactory(logger: any) { + + // // Logger + // logger = logger.forSource(factoryId); + + // // Properties + // Object.defineProperty(UserElementCellx.prototype, 'DecimalValue', { + // enumerable: true, + // configurable: true, + // get() { return this.backingFields._DecimalValue; }, + // set(value) { + // if (this.backingFields._DecimalValue !== value) { + // this.backingFields._DecimalValue = value; + // } + // } + // }); + + // // Return + // return UserElementCellx; + + // function UserElementCellx() { + + // var self = this; + + // // Server-side + // self.UserId = 0; + // self.ElementCellId = 0; + // self.StringValue = null; + // self.BooleanValue = null; + // self.IntegerValue = null; + // // + // self.DateTimeValue = null; + + // // Local variables + // self.backingFields = { + // _DecimalValue: null + // }; + // } + //} + + //// userElementCellFactory.$inject = ['logger']; + + //// angular.module('main').factory(factoryId, userElementCellFactory); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/UserElementField.js b/ngClient/_system/js/app/entities/UserElementField.js deleted file mode 100644 index dd4c901ea..000000000 --- a/ngClient/_system/js/app/entities/UserElementField.js +++ /dev/null @@ -1,26 +0,0 @@ -(function () { - 'use strict'; - - var factoryId = 'UserElementField'; - angular.module('main') - .factory(factoryId, ['logger', userElementFieldFactory]); - - function userElementFieldFactory(logger) { - - // Logger - logger = logger.forSource(factoryId); - - // Return - return UserElementField; - - function UserElementField() { - - var self = this; - - // Server-side - self.UserId = 0; - self.ElementFieldId = 0; - self.Rating = 0; - } - } -})(); \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/UserElementField.ts b/ngClient/_system/js/app/entities/UserElementField.ts new file mode 100644 index 000000000..b5f6fbf4d --- /dev/null +++ b/ngClient/_system/js/app/entities/UserElementField.ts @@ -0,0 +1,36 @@ +module Main.Entities { + 'use strict'; + + export class UserElementField { + + // Server-side + UserId: number; + UserElementFieldId: number; + Rating: number; + } + + //var factoryId = 'UserElementField'; + + //function userElementFieldFactory(logger: any) { + + // // Logger + // logger = logger.forSource(factoryId); + + // // Return + // return UserElementFieldX; + + // function UserElementFieldX() { + + // var self = this; + + // // Server-side + // self.UserId = 0; + // self.ElementFieldId = 0; + // self.Rating = 0; + // } + //} + + //userElementFieldFactory.$inject = ['logger']; + + //angular.module('main').factory(factoryId, userElementFieldFactory); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/UserResourcePool.js b/ngClient/_system/js/app/entities/UserResourcePool.js deleted file mode 100644 index f8c834794..000000000 --- a/ngClient/_system/js/app/entities/UserResourcePool.js +++ /dev/null @@ -1,26 +0,0 @@ -(function () { - 'use strict'; - - var factoryId = 'UserResourcePool'; - angular.module('main') - .factory(factoryId, ['logger', userResourcePoolFactory]); - - function userResourcePoolFactory(logger) { - - // Logger - logger = logger.forSource(factoryId); - - // Return - return UserResourcePool; - - function UserResourcePool() { - - var self = this; - - // Server-side - self.UserId = 0; - self.ResourcePoolId = 0; - self.ResourcePoolRate = 0; - } - } -})(); \ No newline at end of file diff --git a/ngClient/_system/js/app/entities/UserResourcePool.ts b/ngClient/_system/js/app/entities/UserResourcePool.ts new file mode 100644 index 000000000..790945288 --- /dev/null +++ b/ngClient/_system/js/app/entities/UserResourcePool.ts @@ -0,0 +1,35 @@ +module Main.Entities { + 'use strict'; + + export class UserResourcePool { + + UserId: number; + ResourcePoolId: number; + ResourcePoolRate: number; + } + + //var factoryId = 'UserResourcePool'; + + //function userResourcePoolFactory(logger: any) { + + // // Logger + // logger = logger.forSource(factoryId); + + // // Return + // return UserResourcePoolX; + + // function UserResourcePoolX() { + + // var self = this; + + // // Server-side + // self.UserId = 0; + // self.ResourcePoolId = 0; + // self.ResourcePoolRate = 0; + // } + //} + + //userResourcePoolFactory.$inject = ['logger']; + + //angular.module('main').factory(factoryId, userResourcePoolFactory); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/factories/applicationFactory.js b/ngClient/_system/js/app/factories/applicationFactory.ts similarity index 74% rename from ngClient/_system/js/app/factories/applicationFactory.js rename to ngClient/_system/js/app/factories/applicationFactory.ts index 424ea8e77..f93ba6577 100644 --- a/ngClient/_system/js/app/factories/applicationFactory.js +++ b/ngClient/_system/js/app/factories/applicationFactory.ts @@ -1,11 +1,9 @@ -(function () { +module Main.Factories { 'use strict'; var factoryId = 'applicationFactory'; - angular.module('main') - .factory(factoryId, ['logger', 'serviceAppUrl', '$http', '$q', applicationFactory]); - function applicationFactory(logger, serviceAppUrl, $http, $q) { + export function applicationFactory(logger: any, serviceAppUrl: any, $http: any, $q: any) { logger = logger.forSource(factoryId); var applicationInfoUrl = serviceAppUrl + '/api/Application/ApplicationInfo'; @@ -29,11 +27,11 @@ } else { $http.get(applicationInfoUrl) - .success(function (data) { + .success(data => { applicationInfo = data; deferred.resolve(applicationInfo); }) - .error(function (data, status, headers, config) { + .error((data, status, headers, config) => { // TODO Check this approach? - Just return 'Something went wrong'? deferred.reject({ data: data, status: status, headers: headers, config: config }); }); @@ -42,4 +40,8 @@ return deferred.promise; } } -})(); + + applicationFactory.$inject = ['logger', 'serviceAppUrl', '$http', '$q']; + + angular.module('main').factory(factoryId, applicationFactory); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/factories/dataContext.js b/ngClient/_system/js/app/factories/dataContext.ts similarity index 86% rename from ngClient/_system/js/app/factories/dataContext.js rename to ngClient/_system/js/app/factories/dataContext.ts index 03faaff81..a07b78e1c 100644 --- a/ngClient/_system/js/app/factories/dataContext.js +++ b/ngClient/_system/js/app/factories/dataContext.ts @@ -5,14 +5,19 @@ * using BreezeJS. * ***/ -(function () { +module Main.Factories { 'use strict'; var factoryId = 'dataContext'; - angular.module('main') - .factory(factoryId, ['entityManagerFactory', 'logger', 'serviceAppUrl', '$http', '$q', '$rootScope', '$timeout', '$window', dataContext]); - function dataContext(entityManagerFactory, logger, serviceAppUrl, $http, $q, $rootScope, $timeout, $window) { + export function dataContext(entityManagerFactory: any, + logger: any, + serviceAppUrl: any, + $http: any, + $q: any, + $rootScope: any, + $timeout: any, + $window: any) { // Logger logger = logger.forSource(factoryId); @@ -80,9 +85,9 @@ manager = entityManagerFactory.newManager(); } - function addPassword(addPasswordBindingModel) { + function addPassword(addPasswordBindingModel: any) { return $http.post(addPasswordUrl, addPasswordBindingModel) - .success(function (updatedUser) { + .success(updatedUser => { currentUser.HasPassword = null; @@ -94,9 +99,9 @@ .error(handleErrorResult); } - function changeEmail(changeEmailBindingModel) { + function changeEmail(changeEmailBindingModel: any) { return $http.post(changeEmailUrl, changeEmailBindingModel) - .success(function (updatedUser) { + .success(updatedUser => { currentUser.Email = updatedUser.Email; currentUser.EmailConfirmed = false; @@ -113,9 +118,9 @@ .error(handleErrorResult); } - function changePassword(changePasswordBindingModel) { + function changePassword(changePasswordBindingModel: any) { return $http.post(changePasswordUrl, changePasswordBindingModel) - .success(function (updatedUser) { + .success(updatedUser => { // Sync RowVersion fields syncRowVersion(currentUser, updatedUser); @@ -125,9 +130,9 @@ .error(handleErrorResult); } - function changeUserName(changeUserNameBindingModel) { + function changeUserName(changeUserNameBindingModel: any) { return $http.post(changeUserNameUrl, changeUserNameBindingModel) - .success(function (updatedUser) { + .success(updatedUser => { currentUser.UserName = updatedUser.UserName; @@ -144,9 +149,9 @@ .error(handleErrorResult); } - function confirmEmail(confirmEmailBindingModel) { + function confirmEmail(confirmEmailBindingModel: any) { return $http.post(confirmEmailUrl, confirmEmailBindingModel) - .success(function (updatedUser) { + .success(updatedUser => { currentUser.EmailConfirmed = true; @@ -158,7 +163,7 @@ .error(handleErrorResult); } - function createEntity(entityType, initialValues, entityState, mergeStrategy) { + function createEntity(entityType, initialValues, entityState?, mergeStrategy?) { return manager.createEntity(entityType, initialValues, entityState, mergeStrategy); } @@ -175,15 +180,15 @@ return user; } - function executeQuery(query) { + function executeQuery(query: any) { return manager.executeQuery(query); } - function fetchEntityByKey(typeName, keyValues, checkLocalCacheFirst) { + function fetchEntityByKey(typeName: any, keyValues: any, checkLocalCacheFirst: any) { return manager.fetchEntityByKey(typeName, keyValues, checkLocalCacheFirst); } - function getChanges(entityTypeName, entityState) { + function getChanges(entityTypeName?: any, entityState?: any) { entityTypeName = typeof entityTypeName !== 'undefined' ? entityTypeName : null; entityState = typeof entityState !== 'undefined' ? entityState : null; @@ -191,9 +196,9 @@ var changes = []; // Filters - all.forEach(function (change) { + all.forEach(change => { if ((entityTypeName === null || change.entityType.shortName === entityTypeName) && - (entityState === null || change.entityAspect.entityState === entityState)) { + (entityState === null || change.entityAspect.entityState === entityState)) { changes.push(change); } }); @@ -211,15 +216,15 @@ return currentUser; } - function getEntities(entityTypes, entityStates) { + function getEntities(entityTypes: any, entityStates: any) { return manager.getEntities(entityTypes, entityStates); } - function getEntityByKey(entityType, entityKey) { + function getEntityByKey(entityType: any, entityKey: any) { return manager.getEntityByKey(entityType, entityKey); } - function getToken(userName, password, rememberMe, singleUseToken) { + function getToken(userName, password, rememberMe, singleUseToken?) { var deferred = $q.defer(); @@ -230,13 +235,13 @@ '&singleUseToken=' + singleUseToken; $http.post(tokenUrl, tokenData, { 'Content-Type': 'application/x-www-form-urlencoded' }) - .success(function (token) { + .success(token => { // Set token to the session $window.localStorage.setItem('token', angular.toJson(token)); deferred.resolve(); }) - .error(function (data, status, headers, config) { + .error((data, status, headers, config) => { handleErrorResult(data, status, headers, config); deferred.reject(data); }); @@ -261,12 +266,10 @@ return 'guest' + year + month + day + hour + minute + second; } - function getUser(userName) { + function getUser(userName: any) { // Already fetched, then query locally - var alreadyFetched = fetchedUsers.some(function (fetched) { - return userName === fetched; - }); + var alreadyFetched = fetchedUsers.some(fetched => (userName === fetched)); var query = breeze.EntityQuery .from('Users') @@ -284,6 +287,7 @@ .then(success) .catch(failed); + function success(response: any); function success(response) { // If there is no result @@ -299,13 +303,14 @@ return user; } + function failed(error: any); function failed(error) { var message = error.message || 'ResourcePool query failed'; logger.logError(message, error, true); } } - function handleErrorResult(data, status, headers, config) { + function handleErrorResult(data: any, status: any, headers: any, config: any) { // TODO Can this be done on a higher level? var message = ''; @@ -317,7 +322,7 @@ } } - function addErrorMessage(error) { + function addErrorMessage(error: any) { message += error + '
'; } @@ -338,7 +343,7 @@ } // Returns either unauthenticated or logged in user - function initializeCurrentUser(resetPromise) { + function initializeCurrentUser(resetPromise: any) { resetPromise = typeof resetPromise !== 'undefined' ? resetPromise : false; if (initializeCurrentUserPromise === null || resetPromise) { @@ -349,12 +354,12 @@ if ($window.localStorage.getItem('token') === null) { metadataReady() - .then(function () { + .then(() => { currentUser = createGuestUser(); $rootScope.$broadcast('dataContext_currentUserChanged', currentUser); deferred.resolve(currentUser); }) - .catch(function () { + .catch(() => { // TODO Handle? deferred.reject(); }); @@ -377,7 +382,7 @@ return initializeCurrentUserPromise; - function success(response) { + function success(response: any) { // If the response has an entity, use that, otherwise create an anonymous user if (response.results.length > 0) { @@ -394,7 +399,7 @@ deferred.resolve(currentUser); } - function failed(error) { + function failed(error: any) { var message = error.message || 'User query failed'; // TODO Handle this case better! deferred.reject(message); @@ -402,10 +407,10 @@ } } - function login(userName, password, rememberMe, singleUseToken) { + function login(userName: any, password: any, rememberMe: any, singleUseToken: any) { return getToken(userName, password, rememberMe, singleUseToken) - .then(function () { + .then(() => { // Clear breeze's metadata store etc. manager.clear(); @@ -438,12 +443,12 @@ if (manager.metadataStore.isEmpty()) { manager.fetchMetadata() - .then(function () { - deferred.resolve(); - }, - function (error) { - deferred.reject(error); - }); + .then(() => { + deferred.resolve(); + }, + error => { + deferred.reject(error); + }); } else { deferred.resolve(); } @@ -452,12 +457,12 @@ return metadataReadyPromise; } - function register(registerBindingModel, rememberMe) { + function register(registerBindingModel: any, rememberMe: any) { var deferred = $q.defer(); $http.post(registerUrl, registerBindingModel, rememberMe) - .success(function (updatedUser) { + .success(updatedUser => { // breeze context user entity fix-up! // TODO Try to make this part better, use OData method? @@ -474,22 +479,22 @@ currentUser.entityAspect.acceptChanges(); getToken(registerBindingModel.UserName, registerBindingModel.Password, rememberMe) - .then(function () { + .then(() => { // Save the changes that's been done before the registration saveChanges() - .then(function () { + .then(() => { deferred.resolve(); }) - .catch(function () { + .catch(() => { deferred.reject(); }); }) - .catch(function () { + .catch(() => { deferred.reject(); }); }) - .error(function (data, status, headers, config) { + .error((data, status, headers, config) => { handleErrorResult(data, status, headers, config); deferred.reject(data); }); @@ -497,12 +502,12 @@ return deferred.promise; } - function registerAnonymous(registerAnonymousBindingModel, rememberMe) { + function registerAnonymous(registerAnonymousBindingModel: any, rememberMe: any) { var deferred = $q.defer(); $http.post(registerAnonymousUrl, registerAnonymousBindingModel) - .success(function (updatedUser) { + .success(updatedUser => { // breeze context user entity fix-up! // TODO Try to make this part better, use OData method? @@ -519,22 +524,22 @@ currentUser.entityAspect.acceptChanges(); getToken('', '', rememberMe, updatedUser.SingleUseToken) - .then(function () { + .then(() => { // Save the changes that's been done before the registration saveChanges() - .then(function () { + .then(() => { deferred.resolve(); }) - .catch(function () { + .catch(() => { deferred.reject(); }); }) - .catch(function () { + .catch(() => { deferred.reject(); }); }) - .error(function (data, status, headers, config) { + .error((data, status, headers, config) => { handleErrorResult(data, status, headers, config); deferred.reject(data); }); @@ -550,9 +555,9 @@ return $http.post(resendConfirmationEmailUrl).error(handleErrorResult); } - function resetPassword(resetPasswordBindingModel) { + function resetPassword(resetPasswordBindingModel: any) { return $http.post(resetPasswordUrl, resetPasswordBindingModel) - .success(function (updatedUser) { + .success(updatedUser => { // Sync RowVersion fields syncRowVersion(currentUser, updatedUser); @@ -562,7 +567,7 @@ .error(handleErrorResult); } - function resetPasswordRequest(resetPasswordRequestBindingModel) { + function resetPasswordRequest(resetPasswordRequestBindingModel: any) { return $http.post(resetPasswordRequestUrl, resetPasswordRequestBindingModel).error(handleErrorResult); } @@ -581,11 +586,11 @@ }; registerAnonymous(bindingModel, true) - .then(function () { + .then(() => { $rootScope.$broadcast('guestAccountCreated'); deferred.resolve(); }) - .catch(function () { + .catch(() => { deferred.reject(); }); } @@ -593,7 +598,7 @@ return deferred.promise; } - function saveChanges(delay) { + function saveChanges(delay?) { delay = typeof delay !== 'undefined' ? delay : 0; // Cancel existing timers (delay the save) @@ -605,7 +610,7 @@ if (delay === 0) { return saveChangesInternal(); } else { - saveTimer = $timeout(function () { + saveTimer = $timeout(() => { saveChangesInternal(); }, delay); return saveTimer; @@ -626,12 +631,12 @@ function saveChangesInternal() { return ensureAuthenticatedUser() - .then(function () { + .then(() => { var promise = null; var count = getChangesCount(); var saveBatches = prepareSaveBatches(); - saveBatches.forEach(function (batch) { + saveBatches.forEach(batch => { // ignore empty batches (except 'null' which means "save everything else") if (batch === null || batch.length > 0) { @@ -640,7 +645,7 @@ $rootScope.$broadcast('saveChangesStart'); promise = promise ? - promise.then(function () { return manager.saveChanges(batch); }) : + promise.then(() => manager.saveChanges(batch)) : manager.saveChanges(batch); } }); @@ -652,12 +657,12 @@ return promise.then(success).catch(failed).finally(completed); - function success(result) { + function success(result: any) { logger.logSuccess('Saved ' + count + ' change(s)'); return result; } - function failed(error, status, headers, config) { + function failed(error: any, status: any, headers: any, config: any) { //console.log('error', error); //for (var keyx in error) { @@ -703,7 +708,7 @@ // RowVersion fix // TODO How about Deleted state? var modifiedEntities = getChanges(null, breeze.EntityState.Modified); - modifiedEntities.forEach(function (entity) { + modifiedEntities.forEach(entity => { var rowVersion = entity.RowVersion; entity.RowVersion = ''; entity.RowVersion = rowVersion; @@ -756,10 +761,14 @@ // When an entity gets updated through angular, unlike breeze updates, it doesn't sync RowVersion automatically // After each update, call this function to sync the entities RowVersion with the server's. Otherwise it'll get Conflict error - // SH - 05 Jan. '16 - function syncRowVersion(oldEntity, newEntity) { + // coni2k - 05 Jan. '16 + function syncRowVersion(oldEntity: any, newEntity: any) { // TODO Validations? oldEntity.RowVersion = newEntity.RowVersion; } } -})(); + + dataContext.$inject = ['entityManagerFactory', 'logger', 'serviceAppUrl', '$http', '$q', '$rootScope', '$timeout', '$window']; + + angular.module('main').factory(factoryId, dataContext); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/factories/entityManagerFactory.js b/ngClient/_system/js/app/factories/entityManagerFactory.ts similarity index 52% rename from ngClient/_system/js/app/factories/entityManagerFactory.js rename to ngClient/_system/js/app/factories/entityManagerFactory.ts index 6691ce24d..49edc8d2d 100644 --- a/ngClient/_system/js/app/factories/entityManagerFactory.js +++ b/ngClient/_system/js/app/factories/entityManagerFactory.ts @@ -5,39 +5,19 @@ * BreezeJS EntityManager for use in a 'dataContext' service * ***/ -(function () { +module Main.Factories { 'use strict'; var factoryId = 'entityManagerFactory'; - angular.module('main') - .factory(factoryId, ['breeze', - 'Element', - 'ElementCell', - 'ElementField', - 'ElementItem', - 'logger', - 'ResourcePool', - 'serviceAppUrl', - 'User', - 'UserElementCell', - 'UserElementField', - 'UserResourcePool', - '$rootScope', - entityManagerFactory]); - function entityManagerFactory(breeze, - Element, - ElementCell, - ElementField, - ElementItem, - logger, - ResourcePool, - serviceAppUrl, - User, - UserElementCell, - UserElementField, - UserResourcePool, - $rootScope) { + export function entityManagerFactory(breeze: any, + Element: any, + ElementCell: any, + ElementField: any, + ElementItem: any, + logger: any, + ResourcePool: any, + serviceAppUrl: any) { // Logger logger = logger.forSource(factoryId); @@ -61,12 +41,24 @@ store.registerEntityTypeCtor('ElementField', ElementField); store.registerEntityTypeCtor('ElementItem', ElementItem); store.registerEntityTypeCtor('ResourcePool', ResourcePool); - store.registerEntityTypeCtor('User', User); - store.registerEntityTypeCtor('UserElementCell', UserElementCell); - store.registerEntityTypeCtor('UserElementField', UserElementField); - store.registerEntityTypeCtor('UserResourcePool', UserResourcePool); + + store.registerEntityTypeCtor('User', Entities.User); + store.registerEntityTypeCtor('UserElementCell', Entities.UserElementCell); + store.registerEntityTypeCtor('UserElementField', Entities.UserElementField); + store.registerEntityTypeCtor('UserResourcePool', Entities.UserResourcePool); return manager; } } -})(); \ No newline at end of file + + entityManagerFactory.$inject = ['breeze', + 'Element', + 'ElementCell', + 'ElementField', + 'ElementItem', + 'logger', + 'ResourcePool', + 'serviceAppUrl']; + + angular.module('main').factory(factoryId, entityManagerFactory); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/factories/locationHistory.js b/ngClient/_system/js/app/factories/locationHistory.ts similarity index 64% rename from ngClient/_system/js/app/factories/locationHistory.js rename to ngClient/_system/js/app/factories/locationHistory.ts index e1ade0da6..e560f4f36 100644 --- a/ngClient/_system/js/app/factories/locationHistory.js +++ b/ngClient/_system/js/app/factories/locationHistory.ts @@ -1,11 +1,11 @@ -(function () { +module Main.Factories { 'use strict'; var factoryId = 'locationHistory'; - angular.module('main') - .factory(factoryId, ['logger', locationHistory]); - function locationHistory(logger) { + angular.module('main').factory(factoryId, ['logger', locationHistory]); + + export function locationHistory(logger: any) { // Logger logger = logger.forSource(factoryId); @@ -26,7 +26,7 @@ /*** Implementations ***/ - function createItem($location, $routeCurrent) { + function createItem($location: any, $routeCurrent: any) { var itemUrl = $location.url(); var accessType = $routeCurrent.accessType; @@ -47,20 +47,23 @@ for (var i = self.history.length - 2; i >= 0; i--) { return self.history[i]; } + + return null; } + } - function LocationItem(itemUrl, accessType) { - itemUrl = typeof itemUrl !== 'undefined' ? itemUrl : ''; - accessType = typeof accessType !== 'undefined' ? accessType : 'undefined'; + class LocationItem { - var self = this; - self.itemUrl = itemUrl; - self.accessType = accessType; - self.url = url; + itemUrl: string; + accessType: any; - function url() { - return self.itemUrl; - } + constructor(itemUrl: any, accessType?: any) { + this.itemUrl = typeof itemUrl !== 'undefined' ? itemUrl : ''; + this.accessType = typeof accessType !== 'undefined' ? accessType : 'undefined'; + } + + url() { + return this.itemUrl; } } -})(); \ No newline at end of file +} \ No newline at end of file diff --git a/ngClient/_system/js/app/factories/logger.js b/ngClient/_system/js/app/factories/logger.js deleted file mode 100644 index 2214cf18e..000000000 --- a/ngClient/_system/js/app/factories/logger.js +++ /dev/null @@ -1,93 +0,0 @@ -/*** - * Service: logger - * - * Provides semantic logging services with help of - * Angular's $log service that writes to the console and - * John Papa's 'toastr.js': https://github.com/CodeSeven/toastr - * - ***/ -(function () { - 'use strict'; - - angular.module('main') - .factory('logger', ['$log', logger]); - - function logger($log) { - configureToastr(); - - var factory = { - forSource: forSource, - log: log, - logError: logError, - logInfo: logInfo, - logSuccess: logSuccess, - logWarning: logWarning - }; - - return factory; - - function configureToastr() { - toastr.options = { - "positionClass": "toast-bottom-right" - }; - } - - function forSource(src) { - return { - log: function (m, d, s, t, o) { return log(m, d, src, s, t, o); }, - logError: function (m, d, s, t, o) { return logError(m, d, src, s, t, o); }, - logInfo: function (m, d, s, t, o) { return logInfo(m, d, src, s, t, o); }, - logSuccess: function (m, d, s, t, o) { return logSuccess(m, d, src, s, t, o); }, - logWarning: function (m, d, s, t, o) { return logWarning(m, d, src, s, t, o); }, - }; - } - - function log(message, data, source, showToast, title, optionsOverride) { - return logIt(message, data, source, showToast, title, optionsOverride, 'debug'); - } - - function logError(message, data, source, showToast, title, optionsOverride) { - return logIt(message, data, source, showToast, title, optionsOverride, 'error'); - } - - function logInfo(message, data, source, showToast, title, optionsOverride) { - return logIt(message, data, source, showToast, title, optionsOverride, 'info'); - } - - function logSuccess(message, data, source, showToast, title, optionsOverride) { - return logIt(message, data, source, showToast, title, optionsOverride, 'success'); - } - - function logWarning(message, data, source, showToast, title, optionsOverride) { - return logIt(message, data, source, showToast, title, optionsOverride, 'warning'); - } - - function logIt(message, data, source, showToast, title, optionsOverride, toastType) { - showToast = typeof showToast === 'undefined' ? false : showToast; - var currentDateTime = new Date().getHours() + ':' + - new Date().getMinutes() + ':' + - new Date().getSeconds(); - source = source ? '[' + source + '] ' : ''; - var write; - switch (toastType) { - case 'debug': write = $log.debug; break; - case 'error': write = $log.error; break; - case 'info': write = $log.info; break; - case 'success': write = $log.log; break; - case 'warning': write = $log.warn; break; - } - write(currentDateTime, source, message, data); - var toast = null; - if (showToast) { - switch (toastType) { - case 'debug': toast = toastr.info(message, title, optionsOverride); break; - case 'error': toast = toastr.error(message, title, optionsOverride); break; - case 'info': toast = toastr.info(message, title, optionsOverride); break; - case 'success': toast = toastr.success(message, title, optionsOverride); break; - case 'warning': toast = toastr.warning(message, title, optionsOverride); break; - } - } - return toast; - } - } -})(); \ No newline at end of file diff --git a/ngClient/_system/js/app/factories/logger.ts b/ngClient/_system/js/app/factories/logger.ts new file mode 100644 index 000000000..2e08579e2 --- /dev/null +++ b/ngClient/_system/js/app/factories/logger.ts @@ -0,0 +1,92 @@ +/*** + * Service: logger + * + * Provides semantic logging services with help of + * Angular's $log service that writes to the console and + * John Papa's 'toastr.js': https://github.com/CodeSeven/toastr + * + ***/ +module Main.Factories { + 'use strict'; + + angular.module('main').factory('logger', ['$log', logger]); + + function logger($log: any) { + configureToastr(); + + var factory = { + forSource: forSource, + log: log, + logError: logError, + logInfo: logInfo, + logSuccess: logSuccess, + logWarning: logWarning + }; + + return factory; + + function configureToastr() { + toastr.options = { + "positionClass": "toast-bottom-right" + }; + } + + function forSource(src: any) { + return { + log(m, d, s, t, o) { return log(m, d, src, s, t, o); }, + logError(m, d, s, t, o) { return logError(m, d, src, s, t, o); }, + logInfo(m, d, s, t, o) { return logInfo(m, d, src, s, t, o); }, + logSuccess(m, d, s, t, o) { return logSuccess(m, d, src, s, t, o); }, + logWarning(m, d, s, t, o) { return logWarning(m, d, src, s, t, o); }, + }; + } + + function log(message: any, data: any, source: any, showToast: any, title: any, optionsOverride: any) { + return logIt(message, data, source, showToast, title, optionsOverride, 'debug'); + } + + function logError(message: any, data: any, source: any, showToast: any, title: any, optionsOverride: any) { + return logIt(message, data, source, showToast, title, optionsOverride, 'error'); + } + + function logInfo(message: any, data: any, source: any, showToast: any, title: any, optionsOverride: any) { + return logIt(message, data, source, showToast, title, optionsOverride, 'info'); + } + + function logSuccess(message: any, data: any, source: any, showToast: any, title: any, optionsOverride: any) { + return logIt(message, data, source, showToast, title, optionsOverride, 'success'); + } + + function logWarning(message: any, data: any, source: any, showToast: any, title: any, optionsOverride: any) { + return logIt(message, data, source, showToast, title, optionsOverride, 'warning'); + } + + function logIt(message: any, data: any, source: any, showToast: any, title: any, optionsOverride: any, toastType: any) { + showToast = typeof showToast === 'undefined' ? false : showToast; + var currentDateTime = new Date().getHours() + ':' + + new Date().getMinutes() + ':' + + new Date().getSeconds(); + source = source ? '[' + source + '] ' : ''; + var write; + switch (toastType) { + case 'debug': write = $log.debug; break; + case 'error': write = $log.error; break; + case 'info': write = $log.info; break; + case 'success': write = $log.log; break; + case 'warning': write = $log.warn; break; + } + write(currentDateTime, source, message, data); + var toast = null; + if (showToast) { + switch (toastType) { + case 'debug': toast = toastr.info(message, title, optionsOverride); break; + case 'error': toast = toastr.error(message, title, optionsOverride); break; + case 'info': toast = toastr.info(message, title, optionsOverride); break; + case 'success': toast = toastr.success(message, title, optionsOverride); break; + case 'warning': toast = toastr.warning(message, title, optionsOverride); break; + } + } + return toast; + } + } +} \ No newline at end of file diff --git a/ngClient/_system/js/app/factories/resourcePoolFactory.js b/ngClient/_system/js/app/factories/resourcePoolFactory.ts similarity index 70% rename from ngClient/_system/js/app/factories/resourcePoolFactory.js rename to ngClient/_system/js/app/factories/resourcePoolFactory.ts index 198adf80c..13918eff1 100644 --- a/ngClient/_system/js/app/factories/resourcePoolFactory.js +++ b/ngClient/_system/js/app/factories/resourcePoolFactory.ts @@ -1,11 +1,12 @@ -(function () { +module Main.Factories { 'use strict'; var factoryId = 'resourcePoolFactory'; + angular.module('main') .factory(factoryId, ['dataContext', 'Element', 'logger', 'ResourcePool', '$rootScope', resourcePoolFactory]); - function resourcePoolFactory(dataContext, Element, logger, ResourcePool, $rootScope) { + function resourcePoolFactory(dataContext: any, Element: any, logger: any, ResourcePool: any, $rootScope: any) { // Logger logger = logger.forSource(factoryId); @@ -36,7 +37,7 @@ var fetchFromServer = true; // Events - $rootScope.$on('dataContext_currentUserChanged', function () { + $rootScope.$on('dataContext_currentUserChanged', () => { fetchedList = []; fetchFromServer = true; }); @@ -51,11 +52,11 @@ // TODO } - function createElement(element) { + function createElement(element: any) { return dataContext.createEntity('Element', element); } - function createElementCell(elementCellInitial) { + function createElementCell(elementCellInitial: any) { var elementCell = dataContext.createEntity('ElementCell', elementCellInitial); @@ -67,7 +68,7 @@ return elementCell; } - function createElementField(elementField) { + function createElementField(elementField: any) { elementField = dataContext.createEntity('ElementField', elementField); @@ -77,7 +78,7 @@ } // Related cells - elementField.Element.ElementItemSet.forEach(function (elementItem) { + elementField.Element.ElementItemSet.forEach(elementItem => { createElementCell({ ElementField: elementField, ElementItem: elementItem @@ -87,12 +88,12 @@ return elementField; } - function createElementItem(elementItem) { + function createElementItem(elementItem: any) { elementItem = dataContext.createEntity('ElementItem', elementItem); // Related cells - elementItem.Element.ElementFieldSet.forEach(function (elementField) { + elementItem.Element.ElementFieldSet.forEach(elementField => { createElementCell({ ElementField: elementField, ElementItem: elementItem @@ -102,7 +103,7 @@ return elementItem; } - function createResourcePoolBasic(initializeResourcePool) { + function createResourcePoolBasic(initializeResourcePool?) { initializeResourcePool = typeof initializeResourcePool !== 'undefined' ? initializeResourcePool : false; var currentUser = dataContext.getCurrentUser(); @@ -157,7 +158,7 @@ return resourcePool; } - function createResourcePoolDirectIncomeAndMultiplier(initializeResourcePool) { + function createResourcePoolDirectIncomeAndMultiplier(initializeResourcePool: any) { initializeResourcePool = typeof initializeResourcePool !== 'undefined' ? initializeResourcePool : false; var resourcePool = createResourcePoolBasic(); @@ -187,7 +188,7 @@ return resourcePool; } - function createResourcePoolTwoElements(initializeResourcePool) { + function createResourcePoolTwoElements(initializeResourcePool: any) { initializeResourcePool = typeof initializeResourcePool !== 'undefined' ? initializeResourcePool : false; var resourcePool = createResourcePoolBasic(); @@ -241,7 +242,7 @@ return resourcePool; } - function createUserElementCell(elementCell, value, updateCache) { + function createUserElementCell(elementCell, value, updateCache?) { updateCache = typeof updateCache !== 'undefined' ? updateCache : true; var currentUser = dataContext.getCurrentUser(); @@ -258,13 +259,13 @@ } switch (elementCell.ElementField.DataType) { - case 1: { userElementCell.StringValue = value !== null ? value : ''; break; } - case 2: { userElementCell.BooleanValue = value !== null ? value : false; break; } - case 3: { userElementCell.IntegerValue = value !== null ? value : 0; break; } - case 4: { userElementCell.DecimalValue = value !== null ? value : 50; break; } - case 6: { break; } - case 11: { userElementCell.DecimalValue = value !== null ? value : 100; break; } - case 12: { userElementCell.DecimalValue = value !== null ? value : 0; break; } + case 1: { userElementCell.StringValue = value !== null ? value : ''; break; } + case 2: { userElementCell.BooleanValue = value !== null ? value : false; break; } + case 3: { userElementCell.IntegerValue = value !== null ? value : 0; break; } + case 4: { userElementCell.DecimalValue = value !== null ? value : 50; break; } + case 6: { break; } + case 11: { userElementCell.DecimalValue = value !== null ? value : 100; break; } + case 12: { userElementCell.DecimalValue = value !== null ? value : 0; break; } } } else { @@ -275,13 +276,13 @@ }; switch (elementCell.ElementField.DataType) { - case 1: { userElementCell.StringValue = value !== null ? value : ''; break; } - case 2: { userElementCell.BooleanValue = value !== null ? value : false; break; } - case 3: { userElementCell.IntegerValue = value !== null ? value : 0; break; } - case 4: { userElementCell.DecimalValue = value !== null ? value : 50; break; } - case 6: { break; } - case 11: { userElementCell.DecimalValue = value !== null ? value : 100; break; } - case 12: { userElementCell.DecimalValue = value !== null ? value : 0; break; } + case 1: { userElementCell.StringValue = value !== null ? value : ''; break; } + case 2: { userElementCell.BooleanValue = value !== null ? value : false; break; } + case 3: { userElementCell.IntegerValue = value !== null ? value : 0; break; } + case 4: { userElementCell.DecimalValue = value !== null ? value : 50; break; } + case 6: { break; } + case 11: { userElementCell.DecimalValue = value !== null ? value : 100; break; } + case 12: { userElementCell.DecimalValue = value !== null ? value : 0; break; } } userElementCell = dataContext.createEntity('UserElementCell', userElementCell); @@ -295,7 +296,7 @@ return userElementCell; } - function createUserElementField(elementField, rating) { + function createUserElementField(elementField, rating?) { rating = typeof rating !== 'undefined' ? rating : 50; var currentUser = dataContext.getCurrentUser(); @@ -330,7 +331,7 @@ return userElementField; } - function createUserResourcePool(resourcePool, resourcePoolRate) { + function createUserResourcePool(resourcePool, resourcePoolRate?) { resourcePoolRate = typeof resourcePoolRate !== 'undefined' ? resourcePoolRate : 10; var currentUser = dataContext.getCurrentUser(); @@ -365,10 +366,10 @@ return userResourcePool; } - function elementField_DataTypeChanged(event, elementField) { + function elementField_DataTypeChanged(event: any, elementField: any) { // Related element cells: Clear old values and set default values if necessary - elementField.ElementCellSet.forEach(function (elementCell) { + elementField.ElementCellSet.forEach(elementCell => { elementCell.SelectedElementItemId = null; @@ -380,7 +381,7 @@ }); } - function elementField_IndexEnabledChanged(event, elementField) { + function elementField_IndexEnabledChanged(event: any, elementField: any) { if (elementField.Element === null) { return; @@ -394,7 +395,7 @@ } } - function getResourcePoolExpanded(resourcePoolUniqueKey) { + function getResourcePoolExpanded(resourcePoolUniqueKey: any) { // TODO Validations? @@ -403,9 +404,7 @@ var fetchedEarlier = false; // If it's not newly created, check the fetched list - fetchedEarlier = fetchedList.some(function (fetched) { - return resourcePoolUniqueKey === fetched; - }); + fetchedEarlier = fetchedList.some(fetched => (resourcePoolUniqueKey === fetched)); // Prepare the query var query = breeze.EntityQuery.from('ResourcePool'); @@ -433,7 +432,7 @@ .then(success) .catch(failed); - function success(response) { + function success(response: any) { // If there is no cmrp with this Id, return null if (response.results.length === 0) { @@ -454,18 +453,18 @@ return resourcePool; } - function failed(error) { + function failed(error: any) { var message = error.message || 'ResourcePool query failed'; logger.logError(message, error, true); } } - function getResourcePoolSet(searchKey) { + function getResourcePoolSet(searchKey: any) { searchKey = typeof searchKey !== 'undefined' ? searchKey : ''; var query = breeze.EntityQuery - .from('ResourcePool') - .expand(['User']); + .from('ResourcePool') + .expand(['User']); if (searchKey !== '') { var resourcePoolNamePredicate = new breeze.Predicate('Name', 'contains', searchKey); @@ -475,27 +474,27 @@ // Prepare the query //if (fetchFromServer) { // From remote - query = query.using(breeze.FetchStrategy.FromServer); + query = query.using(breeze.FetchStrategy.FromServer); // fetchFromServer = false; // Do it only once per user //} //else { // From local - //query = query.using(breeze.FetchStrategy.FromLocalCache); + //query = query.using(breeze.FetchStrategy.FromLocalCache); //} return dataContext.executeQuery(query) .then(success).catch(failed); - function success(response) { + function success(response: any) { return response.results; } - function failed(error) { + function failed(error: any) { var message = error.message || 'ResourcePool query failed'; logger.logError(message, error, true); } } - function removeElement(element) { + function removeElement(element: any) { // Remove from selectedElement if (element.ResourcePool.selectedElement() === element) { @@ -504,20 +503,20 @@ // Related items var elementItemSet = element.ElementItemSet.slice(); - elementItemSet.forEach(function (elementItem) { + elementItemSet.forEach(elementItem => { removeElementItem(elementItem); }); // Related fields var elementFieldSet = element.ElementFieldSet.slice(); - elementFieldSet.forEach(function (elementField) { + elementFieldSet.forEach(elementField => { removeElementField(elementField); }); element.entityAspect.setDeleted(); } - function removeElementCell(elementCell) { + function removeElementCell(elementCell: any) { // Related user cells removeUserElementCell(elementCell); @@ -525,11 +524,11 @@ elementCell.entityAspect.setDeleted(); } - function removeElementField(elementField) { + function removeElementField(elementField: any) { // Related cells var elementCellSet = elementField.ElementCellSet.slice(); - elementCellSet.forEach(function (elementCell) { + elementCellSet.forEach(elementCell => { removeElementCell(elementCell); }); @@ -539,22 +538,22 @@ elementField.entityAspect.setDeleted(); } - function removeElementItem(elementItem) { + function removeElementItem(elementItem: any) { // Related cells var elementCellSet = elementItem.ElementCellSet.slice(); - elementCellSet.forEach(function (elementCell) { + elementCellSet.forEach(elementCell => { removeElementCell(elementCell); }); elementItem.entityAspect.setDeleted(); } - function removeResourcePool(resourcePool) { + function removeResourcePool(resourcePool: any) { // Related elements var elementSet = resourcePool.ElementSet.slice(); - elementSet.forEach(function (element) { + elementSet.forEach(element => { removeElement(element); }); @@ -564,7 +563,7 @@ resourcePool.entityAspect.setDeleted(); } - function removeUserElementCell(elementCell, updateCache) { + function removeUserElementCell(elementCell, updateCache?) { updateCache = typeof updateCache !== 'undefined' ? updateCache : true; var currentUserElementCell = elementCell.currentUserCell(); @@ -578,7 +577,7 @@ } } - function removeUserElementField(elementField) { + function removeUserElementField(elementField: any) { var currentUserElementField = elementField.currentUserElementField(); @@ -590,7 +589,7 @@ } } - function removeUserResourcePool(resourcePool) { + function removeUserResourcePool(resourcePool: any) { var currentUserResourcePool = resourcePool.currentUserResourcePool(); @@ -604,8 +603,8 @@ // When an entity gets updated through angular, unlike breeze updates, it doesn't sync RowVersion automatically // After each update, call this function to sync the entities RowVersion with the server's. Otherwise it'll get Conflict error - // SH - 05 Jan. '16 - function syncRowVersion(oldEntity, newEntity) { + // coni2k - 05 Jan. '16 + function syncRowVersion(oldEntity: any, newEntity: any) { // TODO Validations? oldEntity.RowVersion = newEntity.RowVersion; } @@ -613,51 +612,51 @@ // These 'updateX' functions were defined in their related entities (user.js). // Only because they had to use createEntity() on dataContext, it was moved to this service. // Try do handle them in a better way, maybe by using broadcast? - function updateElementCellDecimalValue(elementCell, updateType) { + function updateElementCellDecimalValue(elementCell: any, updateType: any) { switch (updateType) { - case 'increase': - case 'decrease': { - - var userElementCell = elementCell.currentUserCell(); + case 'increase': + case 'decrease': { - if (userElementCell === null) { // If there is no item, create it + var userElementCell = elementCell.currentUserCell(); - var decimalValue = updateType === 'increase' ? 55 : 45; - createUserElementCell(elementCell, decimalValue); + if (userElementCell === null) { // If there is no item, create it - } else { // If there is an item, update DecimalValue, but cannot be smaller than zero and cannot be bigger than 100 + var decimalValue = updateType === 'increase' ? 55 : 45; + createUserElementCell(elementCell, decimalValue); - userElementCell.DecimalValue = updateType === 'increase' ? - userElementCell.DecimalValue + 5 > 100 ? 100 : userElementCell.DecimalValue + 5 : - userElementCell.DecimalValue - 5 < 0 ? 0 : userElementCell.DecimalValue - 5; + } else { // If there is an item, update DecimalValue, but cannot be smaller than zero and cannot be bigger than 100 - // Update the cache - elementCell.setCurrentUserNumericValue(); - } + userElementCell.DecimalValue = updateType === 'increase' ? + userElementCell.DecimalValue + 5 > 100 ? 100 : userElementCell.DecimalValue + 5 : + userElementCell.DecimalValue - 5 < 0 ? 0 : userElementCell.DecimalValue - 5; - break; + // Update the cache + elementCell.setCurrentUserNumericValue(); } - case 'reset': { - removeUserElementCell(elementCell); - break; - } + break; + } + case 'reset': { + + removeUserElementCell(elementCell); + break; + } } } - function updateElementCellMultiplier(elementCell, updateType) { + function updateElementCellMultiplier(elementCell: any, updateType: any) { updateElementCellMultiplierInternal(elementCell, updateType); // Update items - elementCell.ElementField.Element.ElementItemSet.forEach(function (item) { + elementCell.ElementField.Element.ElementItemSet.forEach(item => { item.setMultiplier(); }); if (elementCell.ElementField.IndexEnabled) { // Update numeric value cells - elementCell.ElementField.ElementCellSet.forEach(function (cell) { + elementCell.ElementField.ElementCellSet.forEach(cell => { cell.setNumericValueMultiplied(false); }); @@ -666,74 +665,74 @@ } } - function updateElementCellMultiplierInternal(elementCell, updateType) { + function updateElementCellMultiplierInternal(elementCell: any, updateType: any) { switch (updateType) { - case 'increase': - case 'decrease': { + case 'increase': + case 'decrease': { - var userElementCell = elementCell.currentUserCell(); + var userElementCell = elementCell.currentUserCell(); - if (userElementCell === null) { // If there is no item, create it + if (userElementCell === null) { // If there is no item, create it - var decimalValue = updateType === 'increase' ? 1 : 0; - createUserElementCell(elementCell, decimalValue, false); + var decimalValue = updateType === 'increase' ? 1 : 0; + createUserElementCell(elementCell, decimalValue, false); - } else { // If there is an item, update DecimalValue, but cannot be lower than zero - - userElementCell.DecimalValue = updateType === 'increase' ? - userElementCell.DecimalValue + 1 : - userElementCell.DecimalValue - 1 < 0 ? 0 : userElementCell.DecimalValue - 1; - } + } else { // If there is an item, update DecimalValue, but cannot be lower than zero - break; + userElementCell.DecimalValue = updateType === 'increase' ? + userElementCell.DecimalValue + 1 : + userElementCell.DecimalValue - 1 < 0 ? 0 : userElementCell.DecimalValue - 1; } - case 'reset': { - removeUserElementCell(elementCell, false); - break; - } + break; + } + case 'reset': { + + removeUserElementCell(elementCell, false); + break; + } } } - function updateElementFieldIndexRating(elementField, updateType) { + function updateElementFieldIndexRating(elementField: any, updateType: any) { switch (updateType) { - case 'increase': - case 'decrease': { + case 'increase': + case 'decrease': { - var userElementField = elementField.currentUserElementField(); + var userElementField = elementField.currentUserElementField(); - // If there is no item, create it - if (userElementField === null) { + // If there is no item, create it + if (userElementField === null) { - var rating = updateType === 'increase' ? 55 : 45; - createUserElementField(elementField, rating); + var rating = updateType === 'increase' ? 55 : 45; + createUserElementField(elementField, rating); - } else { // If there is an item, update Rating, but cannot be smaller than zero and cannot be bigger than 100 + } else { // If there is an item, update Rating, but cannot be smaller than zero and cannot be bigger than 100 - userElementField.Rating = updateType === 'increase' ? - userElementField.Rating + 5 > 100 ? 100 : userElementField.Rating + 5 : - userElementField.Rating - 5 < 0 ? 0 : userElementField.Rating - 5; - - // Update the cache - elementField.setCurrentUserIndexRating(); - } + userElementField.Rating = updateType === 'increase' ? + userElementField.Rating + 5 > 100 ? 100 : userElementField.Rating + 5 : + userElementField.Rating - 5 < 0 ? 0 : userElementField.Rating - 5; - break; + // Update the cache + elementField.setCurrentUserIndexRating(); } - case 'reset': { - removeUserElementField(elementField); - break; - } + break; + } + case 'reset': { + + removeUserElementField(elementField); + break; + } } } - function updateElementMultiplier(element, updateType) { + function updateElementMultiplier(element: any, updateType: any) { // Find user element cell - element.ElementItemSet.forEach(function (item) { + element.ElementItemSet.forEach(item => { var multiplierCell; for (var cellIndex = 0; cellIndex < item.ElementCellSet.length; cellIndex++) { @@ -750,15 +749,15 @@ // Update related // Update items - element.ElementItemSet.forEach(function (item) { + element.ElementItemSet.forEach(item => { item.setMultiplier(); }); - element.ElementFieldSet.forEach(function (field) { + element.ElementFieldSet.forEach(field => { if (field.IndexEnabled) { // Update numeric value cells - field.ElementCellSet.forEach(function (cell) { + field.ElementCellSet.forEach(cell => { cell.setNumericValueMultiplied(false); }); @@ -768,38 +767,38 @@ }); } - function updateResourcePoolRate(resourcePool, updateType) { + function updateResourcePoolRate(resourcePool: any, updateType: any) { switch (updateType) { - case 'increase': - case 'decrease': { - - var userResourcePool = resourcePool.currentUserResourcePool(); + case 'increase': + case 'decrease': { - // If there is no item, create it - if (userResourcePool === null) { + var userResourcePool = resourcePool.currentUserResourcePool(); - var resourcePoolRate = updateType === 'increase' ? 15 : 5; - createUserResourcePool(resourcePool, resourcePoolRate); + // If there is no item, create it + if (userResourcePool === null) { - } else { // If there is an item, update Rating, but cannot be smaller than zero and cannot be bigger than 1000 + var resourcePoolRate = updateType === 'increase' ? 15 : 5; + createUserResourcePool(resourcePool, resourcePoolRate); - userResourcePool.ResourcePoolRate = updateType === 'increase' ? - userResourcePool.ResourcePoolRate + 5 > 1000 ? 1000 : userResourcePool.ResourcePoolRate + 5 : - userResourcePool.ResourcePoolRate - 5 < 0 ? 0 : userResourcePool.ResourcePoolRate - 5; + } else { // If there is an item, update Rating, but cannot be smaller than zero and cannot be bigger than 1000 - // Update the cache - resourcePool.setCurrentUserResourcePoolRate(); - } + userResourcePool.ResourcePoolRate = updateType === 'increase' ? + userResourcePool.ResourcePoolRate + 5 > 1000 ? 1000 : userResourcePool.ResourcePoolRate + 5 : + userResourcePool.ResourcePoolRate - 5 < 0 ? 0 : userResourcePool.ResourcePoolRate - 5; - break; + // Update the cache + resourcePool.setCurrentUserResourcePoolRate(); } - case 'reset': { - removeUserResourcePool(resourcePool); - break; - } + break; + } + case 'reset': { + + removeUserResourcePool(resourcePool); + break; + } } } } -})(); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/filters/ngEnum.js b/ngClient/_system/js/app/filters/enumConverter.ts similarity index 57% rename from ngClient/_system/js/app/filters/ngEnum.js rename to ngClient/_system/js/app/filters/enumConverter.ts index 33148b06a..23c360ea9 100644 --- a/ngClient/_system/js/app/filters/ngEnum.js +++ b/ngClient/_system/js/app/filters/enumConverter.ts @@ -1,18 +1,14 @@ /*** - * Filter: ngEnum + * Filter: enumConverter * * Converts the enum value to its key by searching through tables in Enums.js * ***/ -(function () { +module Main.Filters { 'use strict'; - angular.module('main') - .filter('ngEnum', ['Enums', 'logger', ngEnum]); - - function ngEnum(Enums, logger) { - - return function (input, enumTableKey) { + function enumConverter(Enums: any, logger: any) { + return (input, enumTableKey) => { if (typeof input === 'undefined' || typeof enumTableKey === 'undefined' || enumTableKey === '') { return null; @@ -21,4 +17,8 @@ return Enums.getEnumKey(enumTableKey, input); }; } -})(); + + enumConverter.$inject = ['Enums', 'logger']; + + angular.module('main').filter('enumConverter', enumConverter); +} diff --git a/ngClient/_system/js/app/filters/numberSymbol.js b/ngClient/_system/js/app/filters/numberSymbol.ts similarity index 78% rename from ngClient/_system/js/app/filters/numberSymbol.js rename to ngClient/_system/js/app/filters/numberSymbol.ts index ea9cddccd..bd55ff4f8 100644 --- a/ngClient/_system/js/app/filters/numberSymbol.js +++ b/ngClient/_system/js/app/filters/numberSymbol.ts @@ -4,14 +4,12 @@ * Convert the number to a short format with symbol format. * ***/ -(function () { +module Main.Filters { 'use strict'; - angular.module('main') - .filter('numberSymbol', ['logger', '$filter', numberSymbol]); - function numberSymbol(logger, $filter) { - return function (input, decimals) { + + return (input, decimals) => { if (typeof input === 'undefined') return null; @@ -19,7 +17,7 @@ decimals = typeof decimals === 'undefined' ? 0 : decimals; var number = Number(input); - number = decimals > 0 ? number.toFixed(decimals) : number; + number = decimals > 0 ? Number(number.toFixed(decimals)) : number; var symbol = ''; if (number / Math.pow(10, 12) >= 1) { // Trillion @@ -34,11 +32,13 @@ } else if (number / Math.pow(10, 3) >= 1) { // Thousand number = number / Math.pow(10, 3); symbol = 'K'; - } else { - number = number; } return $filter('number')(number, decimals) + symbol; }; } -})(); + + numberSymbol.$inject = ['logger', '$filter']; + + angular.module('main').filter('numberSymbol', numberSymbol); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/filters/percentage.js b/ngClient/_system/js/app/filters/percentage.js deleted file mode 100644 index 10b340bf9..000000000 --- a/ngClient/_system/js/app/filters/percentage.js +++ /dev/null @@ -1,19 +0,0 @@ -/*** - * Filter: percentage - * - * Convert the number to a percentage format. - * - ***/ -(function () { - 'use strict'; - - angular.module('main') - .filter('percentage', ['$filter', percentage]); - - function percentage($filter) { - return function (input, decimals) { - // TODO Whether Percentage symbol should be in front or behind of the value differs based on cultural settings - return $filter('number')(input * 100, decimals) + '%'; - }; - } -})(); diff --git a/ngClient/_system/js/app/filters/percentage.ts b/ngClient/_system/js/app/filters/percentage.ts new file mode 100644 index 000000000..89dfda8d6 --- /dev/null +++ b/ngClient/_system/js/app/filters/percentage.ts @@ -0,0 +1,17 @@ +/*** + * Filter: percentage + * + * Convert the number to a percentage format. + * + ***/ +module Main.Filters { + 'use strict'; + + function percentage($filter) { + return (input, decimals) => ($filter('number')(input * 100, decimals) + '%'); + } + + percentage.$inject = ['$filter']; + + angular.module('main').filter('percentage', percentage); +} \ No newline at end of file diff --git a/ngClient/_system/js/app/main.js b/ngClient/_system/js/app/main.ts similarity index 60% rename from ngClient/_system/js/app/main.js rename to ngClient/_system/js/app/main.ts index f9d2eefb1..12370c210 100644 --- a/ngClient/_system/js/app/main.js +++ b/ngClient/_system/js/app/main.ts @@ -1,10 +1,16 @@ -/*** +/// +/// +/// +/// + +/*** * App module: main * * Bootstrap the app. * ***/ -(function () { + +module Main { 'use strict'; angular.module('main', [ @@ -18,12 +24,6 @@ 'ngSanitize', 'ui.bootstrap' ]); +} - angular.module('main') - .run(['logger', mainRun]); - - function mainRun(logger) { - logger = logger.forSource('mainRun'); - } -})(); diff --git a/ngClient/_system/js/lib/angularjs/angular.d.ts b/ngClient/_system/js/lib/angularjs/angular.d.ts new file mode 100644 index 000000000..15e9ec204 --- /dev/null +++ b/ngClient/_system/js/lib/angularjs/angular.d.ts @@ -0,0 +1,1961 @@ +// Type definitions for Angular JS 1.5 +// Project: http://angularjs.org +// Definitions by: Diego Vilar +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// + +declare var angular: angular.IAngularStatic; + +// Support for painless dependency injection +interface Function { + $inject?: string[]; +} + +// Collapse angular into ng +import ng = angular; +// Support AMD require +declare module 'angular' { + export = angular; +} + +/////////////////////////////////////////////////////////////////////////////// +// ng module (angular.js) +/////////////////////////////////////////////////////////////////////////////// +declare namespace angular { + + // not directly implemented, but ensures that constructed class implements $get + interface IServiceProviderClass { + new (...args: any[]): IServiceProvider; + } + + interface IServiceProviderFactory { + (...args: any[]): IServiceProvider; + } + + // All service providers extend this interface + interface IServiceProvider { + $get: any; + } + + interface IAngularBootstrapConfig { + strictDi?: boolean; + debugInfoEnabled?: boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // AngularStatic + // see http://docs.angularjs.org/api + /////////////////////////////////////////////////////////////////////////// + interface IAngularStatic { + bind(context: any, fn: Function, ...args: any[]): Function; + + /** + * Use this function to manually start up angular application. + * + * @param element DOM element which is the root of angular application. + * @param modules An array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a config block. + * @param config an object for defining configuration options for the application. The following keys are supported: + * - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code. + */ + bootstrap(element: string|Element|JQuery|Document, modules?: (string|Function|any[])[], config?: IAngularBootstrapConfig): auto.IInjectorService; + + /** + * Creates a deep copy of source, which should be an object or an array. + * + * - If no destination is supplied, a copy of the object or array is created. + * - If a destination is provided, all of its elements (for array) or properties (for objects) are deleted and then all elements/properties from the source are copied to it. + * - If source is not an object or array (inc. null and undefined), source is returned. + * - If source is identical to 'destination' an exception will be thrown. + * + * @param source The source that will be used to make a copy. Can be any type, including primitives, null, and undefined. + * @param destination Destination into which the source is copied. If provided, must be of the same type as source. + */ + copy(source: T, destination?: T): T; + + /** + * Wraps a raw DOM element or HTML string as a jQuery element. + * + * If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." + */ + element: JQueryStatic; + equals(value1: any, value2: any): boolean; + extend(destination: any, ...sources: any[]): any; + + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: T[], iterator: (value: T, key: number) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any; + /** + * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional. + * + * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method. + * + * @param obj Object to iterate over. + * @param iterator Iterator function. + * @param context Object to become context (this) for the iterator function. + */ + forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any; + + fromJson(json: string): any; + identity(arg?: T): T; + injector(modules?: any[], strictDi?: boolean): auto.IInjectorService; + isArray(value: any): boolean; + isDate(value: any): boolean; + isDefined(value: any): boolean; + isElement(value: any): boolean; + isFunction(value: any): boolean; + isNumber(value: any): boolean; + isObject(value: any): boolean; + isString(value: any): boolean; + isUndefined(value: any): boolean; + lowercase(str: string): string; + + /** + * Deeply extends the destination object dst by copying own enumerable properties from the src object(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular.merge({}, object1, object2). + * + * Unlike extend(), merge() recursively descends into object properties of source objects, performing a deep copy. + * + * @param dst Destination object. + * @param src Source object(s). + */ + merge(dst: any, ...src: any[]): any; + + /** + * The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism. + * + * When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved. + * + * @param name The name of the module to create or retrieve. + * @param requires The names of modules this module depends on. If specified then new module is being created. If unspecified then the module is being retrieved for further configuration. + * @param configFn Optional configuration function for the module. + */ + module( + name: string, + requires?: string[], + configFn?: Function): IModule; + + noop(...args: any[]): void; + reloadWithDebugInfo(): void; + toJson(obj: any, pretty?: boolean | number): string; + uppercase(str: string): string; + version: { + full: string; + major: number; + minor: number; + dot: number; + codeName: string; + }; + + /** + * If window.name contains prefix NG_DEFER_BOOTSTRAP! when angular.bootstrap is called, the bootstrap process will be paused until angular.resumeBootstrap() is called. + * @param extraModules An optional array of modules that should be added to the original list of modules that the app was about to be bootstrapped with. + */ + resumeBootstrap?(extraModules?: string[]): ng.auto.IInjectorService; + } + + /////////////////////////////////////////////////////////////////////////// + // Module + // see http://docs.angularjs.org/api/angular.Module + /////////////////////////////////////////////////////////////////////////// + interface IModule { + /** + * Use this method to register a component. + * + * @param name The name of the component. + * @param options A definition object passed into the component. + */ + component(name: string, options: IComponentOptions): IModule; + /** + * Use this method to register work which needs to be performed on module loading. + * + * @param configFn Execute this function on module load. Useful for service configuration. + */ + config(configFn: Function): IModule; + /** + * Use this method to register work which needs to be performed on module loading. + * + * @param inlineAnnotatedFunction Execute this function on module load. Useful for service configuration. + */ + config(inlineAnnotatedFunction: any[]): IModule; + config(object: Object): IModule; + /** + * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. + * + * @param name The name of the constant. + * @param value The constant value. + */ + constant(name: string, value: T): IModule; + constant(object: Object): IModule; + /** + * The $controller service is used by Angular to create new controllers. + * + * This provider allows controller registration via the register method. + * + * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. + * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). + */ + controller(name: string, controllerConstructor: Function): IModule; + /** + * The $controller service is used by Angular to create new controllers. + * + * This provider allows controller registration via the register method. + * + * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors. + * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation). + */ + controller(name: string, inlineAnnotatedConstructor: any[]): IModule; + controller(object: Object): IModule; + /** + * Register a new directive with the compiler. + * + * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind) + * @param directiveFactory An injectable directive factory function. + */ + directive(name: string, directiveFactory: IDirectiveFactory): IModule; + /** + * Register a new directive with the compiler. + * + * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind) + * @param directiveFactory An injectable directive factory function. + */ + directive(name: string, inlineAnnotatedFunction: any[]): IModule; + directive(object: Object): IModule; + /** + * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. + * + * @param name The name of the instance. + * @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). + */ + factory(name: string, $getFn: Function): IModule; + /** + * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider. + * + * @param name The name of the instance. + * @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}). + */ + factory(name: string, inlineAnnotatedFunction: any[]): IModule; + factory(object: Object): IModule; + filter(name: string, filterFactoryFunction: Function): IModule; + filter(name: string, inlineAnnotatedFunction: any[]): IModule; + filter(object: Object): IModule; + provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule; + provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule; + provider(name: string, inlineAnnotatedConstructor: any[]): IModule; + provider(name: string, providerObject: IServiceProvider): IModule; + provider(object: Object): IModule; + /** + * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. + */ + run(initializationFunction: Function): IModule; + /** + * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests. + */ + run(inlineAnnotatedFunction: any[]): IModule; + /** + * Register a service constructor, which will be invoked with new to create the service instance. This is short for registering a service where its provider's $get property is a factory function that returns an instance instantiated by the injector from the service constructor function. + * + * @param name The name of the instance. + * @param serviceConstructor An injectable class (constructor function) that will be instantiated. + */ + service(name: string, serviceConstructor: Function): IModule; + /** + * Register a service constructor, which will be invoked with new to create the service instance. This is short for registering a service where its provider's $get property is a factory function that returns an instance instantiated by the injector from the service constructor function. + * + * @param name The name of the instance. + * @param inlineAnnotatedConstructor An injectable class (constructor function) that will be instantiated. + */ + service(name: string, inlineAnnotatedConstructor: any[]): IModule; + service(object: Object): IModule; + /** + * Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service. + + Value services are similar to constant services, except that they cannot be injected into a module configuration function (see config) but they can be overridden by an Angular decorator. + * + * @param name The name of the instance. + * @param value The value. + */ + value(name: string, value: T): IModule; + value(object: Object): IModule; + + /** + * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. + * @param name The name of the service to decorate + * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. + */ + decorator(name:string, decoratorConstructor: Function): IModule; + decorator(name:string, inlineAnnotatedConstructor: any[]): IModule; + + // Properties + name: string; + requires: string[]; + } + + /////////////////////////////////////////////////////////////////////////// + // Attributes + // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes + /////////////////////////////////////////////////////////////////////////// + interface IAttributes { + /** + * this is necessary to be able to access the scoped attributes. it's not very elegant + * because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way + * this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656 + */ + [name: string]: any; + + /** + * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with x- or data-) to its normalized, camelCase form. + * + * Also there is special case for Moz prefix starting with upper case letter. + * + * For further information check out the guide on @see https://docs.angularjs.org/guide/directive#matching-directives + */ + $normalize(name: string): string; + + /** + * Adds the CSS class value specified by the classVal parameter to the + * element. If animations are enabled then an animation will be triggered + * for the class addition. + */ + $addClass(classVal: string): void; + + /** + * Removes the CSS class value specified by the classVal parameter from the + * element. If animations are enabled then an animation will be triggered for + * the class removal. + */ + $removeClass(classVal: string): void; + + /** + * Adds and removes the appropriate CSS class values to the element based on the difference between + * the new and old CSS class values (specified as newClasses and oldClasses). + */ + $updateClass(newClasses: string, oldClasses: string): void; + + /** + * Set DOM element attribute value. + */ + $set(key: string, value: any): void; + + /** + * Observes an interpolated attribute. + * The observer function will be invoked once during the next $digest + * following compilation. The observer is then invoked whenever the + * interpolated value changes. + */ + $observe(name: string, fn: (value?: T) => any): Function; + + /** + * A map of DOM element attribute names to the normalized name. This is needed + * to do reverse lookup from normalized name back to actual name. + */ + $attr: Object; + } + + /** + * form.FormController - type in module ng + * see https://docs.angularjs.org/api/ng/type/form.FormController + */ + interface IFormController { + + /** + * Indexer which should return ng.INgModelController for most properties but cannot because of "All named properties must be assignable to string indexer type" constraint - see https://github.com/Microsoft/TypeScript/issues/272 + */ + [name: string]: any; + + $pristine: boolean; + $dirty: boolean; + $valid: boolean; + $invalid: boolean; + $submitted: boolean; + $error: any; + $pending: any; + $addControl(control: INgModelController | IFormController): void; + $removeControl(control: INgModelController | IFormController): void; + $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController | IFormController): void; + $setDirty(): void; + $setPristine(): void; + $commitViewValue(): void; + $rollbackViewValue(): void; + $setSubmitted(): void; + $setUntouched(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // NgModelController + // see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController + /////////////////////////////////////////////////////////////////////////// + interface INgModelController { + $render(): void; + $setValidity(validationErrorKey: string, isValid: boolean): void; + // Documentation states viewValue and modelValue to be a string but other + // types do work and it's common to use them. + $setViewValue(value: any, trigger?: string): void; + $setPristine(): void; + $setDirty(): void; + $validate(): void; + $setTouched(): void; + $setUntouched(): void; + $rollbackViewValue(): void; + $commitViewValue(): void; + $isEmpty(value: any): boolean; + + $viewValue: any; + + $modelValue: any; + + $parsers: IModelParser[]; + $formatters: IModelFormatter[]; + $viewChangeListeners: IModelViewChangeListener[]; + $error: any; + $name: string; + + $touched: boolean; + $untouched: boolean; + + $validators: IModelValidators; + $asyncValidators: IAsyncModelValidators; + + $pending: any; + $pristine: boolean; + $dirty: boolean; + $valid: boolean; + $invalid: boolean; + } + + //Allows tuning how model updates are done. + //https://docs.angularjs.org/api/ng/directive/ngModelOptions + interface INgModelOptions { + updateOn?: string; + debounce?: any; + allowInvalid?: boolean; + getterSetter?: boolean; + timezone?: string; + } + + interface IModelValidators { + /** + * viewValue is any because it can be an object that is called in the view like $viewValue.name:$viewValue.subName + */ + [index: string]: (modelValue: any, viewValue: any) => boolean; + } + + interface IAsyncModelValidators { + [index: string]: (modelValue: any, viewValue: any) => IPromise; + } + + interface IModelParser { + (value: any): any; + } + + interface IModelFormatter { + (value: any): any; + } + + interface IModelViewChangeListener { + (): void; + } + + /** + * $rootScope - $rootScopeProvider - service in module ng + * see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and https://docs.angularjs.org/api/ng/service/$rootScope + */ + interface IRootScopeService { + [index: string]: any; + + $apply(): any; + $apply(exp: string): any; + $apply(exp: (scope: IScope) => any): any; + + $applyAsync(): any; + $applyAsync(exp: string): any; + $applyAsync(exp: (scope: IScope) => any): any; + + /** + * Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners. + * + * The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled. + * + * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. + * + * @param name Event name to broadcast. + * @param args Optional one or more arguments which will be passed onto the event listeners. + */ + $broadcast(name: string, ...args: any[]): IAngularEvent; + $destroy(): void; + $digest(): void; + /** + * Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners. + * + * The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it. + * + * Any exception emitted from the listeners will be passed onto the $exceptionHandler service. + * + * @param name Event name to emit. + * @param args Optional one or more arguments which will be passed onto the event listeners. + */ + $emit(name: string, ...args: any[]): IAngularEvent; + + $eval(): any; + $eval(expression: string, locals?: Object): any; + $eval(expression: (scope: IScope) => any, locals?: Object): any; + + $evalAsync(): void; + $evalAsync(expression: string): void; + $evalAsync(expression: (scope: IScope) => any): void; + + // Defaults to false by the implementation checking strategy + $new(isolate?: boolean, parent?: IScope): IScope; + + /** + * Listens on events of a given type. See $emit for discussion of event life cycle. + * + * The event listener function format is: function(event, args...). + * + * @param name Event name to listen on. + * @param listener Function to call when the event is emitted. + */ + $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): () => void; + + $watch(watchExpression: string, listener?: string, objectEquality?: boolean): () => void; + $watch(watchExpression: string, listener?: (newValue: T, oldValue: T, scope: IScope) => any, objectEquality?: boolean): () => void; + $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: boolean): () => void; + $watch(watchExpression: (scope: IScope) => T, listener?: (newValue: T, oldValue: T, scope: IScope) => any, objectEquality?: boolean): () => void; + + $watchCollection(watchExpression: string, listener: (newValue: T, oldValue: T, scope: IScope) => any): () => void; + $watchCollection(watchExpression: (scope: IScope) => T, listener: (newValue: T, oldValue: T, scope: IScope) => any): () => void; + + $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void; + $watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void; + + $parent: IScope; + $root: IRootScopeService; + $id: number; + + // Hidden members + $$isolateBindings: any; + $$phase: any; + } + + interface IScope extends IRootScopeService { } + + /** + * $scope for ngRepeat directive. + * see https://docs.angularjs.org/api/ng/directive/ngRepeat + */ + interface IRepeatScope extends IScope { + + /** + * iterator offset of the repeated element (0..length-1). + */ + $index: number; + + /** + * true if the repeated element is first in the iterator. + */ + $first: boolean; + + /** + * true if the repeated element is between the first and last in the iterator. + */ + $middle: boolean; + + /** + * true if the repeated element is last in the iterator. + */ + $last: boolean; + + /** + * true if the iterator position $index is even (otherwise false). + */ + $even: boolean; + + /** + * true if the iterator position $index is odd (otherwise false). + */ + $odd: boolean; + + } + + interface IAngularEvent { + /** + * the scope on which the event was $emit-ed or $broadcast-ed. + */ + targetScope: IScope; + /** + * the scope that is currently handling the event. Once the event propagates through the scope hierarchy, this property is set to null. + */ + currentScope: IScope; + /** + * name of the event. + */ + name: string; + /** + * calling stopPropagation function will cancel further event propagation (available only for events that were $emit-ed). + */ + stopPropagation?: Function; + /** + * calling preventDefault sets defaultPrevented flag to true. + */ + preventDefault: Function; + /** + * true if preventDefault was called. + */ + defaultPrevented: boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // WindowService + // see http://docs.angularjs.org/api/ng.$window + /////////////////////////////////////////////////////////////////////////// + interface IWindowService extends Window { + [key: string]: any; + } + + /////////////////////////////////////////////////////////////////////////// + // TimeoutService + // see http://docs.angularjs.org/api/ng.$timeout + /////////////////////////////////////////////////////////////////////////// + interface ITimeoutService { + (delay?: number, invokeApply?: boolean): IPromise; + (fn: (...args: any[]) => T, delay?: number, invokeApply?: boolean, ...args: any[]): IPromise; + cancel(promise?: IPromise): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // IntervalService + // see http://docs.angularjs.org/api/ng.$interval + /////////////////////////////////////////////////////////////////////////// + interface IIntervalService { + (func: Function, delay: number, count?: number, invokeApply?: boolean, ...args: any[]): IPromise; + cancel(promise: IPromise): boolean; + } + + /** + * $filter - $filterProvider - service in module ng + * + * Filters are used for formatting data displayed to the user. + * + * see https://docs.angularjs.org/api/ng/service/$filter + */ + interface IFilterService { + (name: 'filter'): IFilterFilter; + (name: 'currency'): IFilterCurrency; + (name: 'number'): IFilterNumber; + (name: 'date'): IFilterDate; + (name: 'json'): IFilterJson; + (name: 'lowercase'): IFilterLowercase; + (name: 'uppercase'): IFilterUppercase; + (name: 'limitTo'): IFilterLimitTo; + (name: 'orderBy'): IFilterOrderBy; + /** + * Usage: + * $filter(name); + * + * @param name Name of the filter function to retrieve + */ + (name: string): T; + } + + interface IFilterFilter { + (array: T[], expression: string | IFilterFilterPatternObject | IFilterFilterPredicateFunc, comparator?: IFilterFilterComparatorFunc|boolean): T[]; + } + + interface IFilterFilterPatternObject { + [name: string]: any; + } + + interface IFilterFilterPredicateFunc { + (value: T, index: number, array: T[]): boolean; + } + + interface IFilterFilterComparatorFunc { + (actual: T, expected: T): boolean; + } + + interface IFilterCurrency { + /** + * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default symbol for current locale is used. + * @param amount Input to filter. + * @param symbol Currency symbol or identifier to be displayed. + * @param fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale + * @return Formatted number + */ + (amount: number, symbol?: string, fractionSize?: number): string; + } + + interface IFilterNumber { + /** + * Formats a number as text. + * @param number Number to format. + * @param fractionSize Number of decimal places to round the number to. If this is not provided then the fraction size is computed from the current locale's number formatting pattern. In the case of the default locale, it will be 3. + * @return Number rounded to decimalPlaces and places a “,” after each third digit. + */ + (value: number|string, fractionSize?: number|string): string; + } + + interface IFilterDate { + /** + * Formats date to a string based on the requested format. + * + * @param date Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone. + * @param format Formatting rules (see Description). If not specified, mediumDate is used. + * @param timezone Timezone to be used for formatting. It understands UTC/GMT and the continental US time zone abbreviations, but for general use, use a time zone offset, for example, '+0430' (4 hours, 30 minutes east of the Greenwich meridian) If not specified, the timezone of the browser will be used. + * @return Formatted string or the input if input is not recognized as date/millis. + */ + (date: Date | number | string, format?: string, timezone?: string): string; + } + + interface IFilterJson { + /** + * Allows you to convert a JavaScript object into JSON string. + * @param object Any JavaScript object (including arrays and primitive types) to filter. + * @param spacing The number of spaces to use per indentation, defaults to 2. + * @return JSON string. + */ + (object: any, spacing?: number): string; + } + + interface IFilterLowercase { + /** + * Converts string to lowercase. + */ + (value: string): string; + } + + interface IFilterUppercase { + /** + * Converts string to uppercase. + */ + (value: string): string; + } + + interface IFilterLimitTo { + /** + * Creates a new array containing only a specified number of elements. The elements are taken from either the beginning or the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit. + * @param input Source array to be limited. + * @param limit The length of the returned array. If the limit number is positive, limit number of items from the beginning of the source array/string are copied. If the number is negative, limit number of items from the end of the source array are copied. The limit will be trimmed if it exceeds array.length. If limit is undefined, the input will be returned unchanged. + * @param begin Index at which to begin limitation. As a negative index, begin indicates an offset from the end of input. Defaults to 0. + * @return A new sub-array of length limit or less if input array had less than limit elements. + */ + (input: T[], limit: string|number, begin?: string|number): T[]; + /** + * Creates a new string containing only a specified number of elements. The elements are taken from either the beginning or the end of the source string or number, as specified by the value and sign (positive or negative) of limit. If a number is used as input, it is converted to a string. + * @param input Source string or number to be limited. + * @param limit The length of the returned string. If the limit number is positive, limit number of items from the beginning of the source string are copied. If the number is negative, limit number of items from the end of the source string are copied. The limit will be trimmed if it exceeds input.length. If limit is undefined, the input will be returned unchanged. + * @param begin Index at which to begin limitation. As a negative index, begin indicates an offset from the end of input. Defaults to 0. + * @return A new substring of length limit or less if input had less than limit elements. + */ + (input: string|number, limit: string|number, begin?: string|number): string; + } + + interface IFilterOrderBy { + /** + * Orders a specified array by the expression predicate. It is ordered alphabetically for strings and numerically for numbers. Note: if you notice numbers are not being sorted as expected, make sure they are actually being saved as numbers and not strings. + * @param array The array to sort. + * @param expression A predicate to be used by the comparator to determine the order of elements. + * @param reverse Reverse the order of the array. + * @return Reverse the order of the array. + */ + (array: T[], expression: string|((value: T) => any)|(((value: T) => any)|string)[], reverse?: boolean): T[]; + } + + /** + * $filterProvider - $filter - provider in module ng + * + * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To achieve this a filter definition consists of a factory function which is annotated with dependencies and is responsible for creating a filter function. + * + * see https://docs.angularjs.org/api/ng/provider/$filterProvider + */ + interface IFilterProvider extends IServiceProvider { + /** + * register(name); + * + * @param name Name of the filter function, or an object map of filters where the keys are the filter names and the values are the filter factories. Note: Filter names must be valid angular Expressions identifiers, such as uppercase or orderBy. Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace your filters, then you can use capitalization (myappSubsectionFilterx) or underscores (myapp_subsection_filterx). + */ + register(name: string | {}): IServiceProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // LocaleService + // see http://docs.angularjs.org/api/ng.$locale + /////////////////////////////////////////////////////////////////////////// + interface ILocaleService { + id: string; + + // These are not documented + // Check angular's i18n files for exemples + NUMBER_FORMATS: ILocaleNumberFormatDescriptor; + DATETIME_FORMATS: ILocaleDateTimeFormatDescriptor; + pluralCat: (num: any) => string; + } + + interface ILocaleNumberFormatDescriptor { + DECIMAL_SEP: string; + GROUP_SEP: string; + PATTERNS: ILocaleNumberPatternDescriptor[]; + CURRENCY_SYM: string; + } + + interface ILocaleNumberPatternDescriptor { + minInt: number; + minFrac: number; + maxFrac: number; + posPre: string; + posSuf: string; + negPre: string; + negSuf: string; + gSize: number; + lgSize: number; + } + + interface ILocaleDateTimeFormatDescriptor { + MONTH: string[]; + SHORTMONTH: string[]; + DAY: string[]; + SHORTDAY: string[]; + AMPMS: string[]; + medium: string; + short: string; + fullDate: string; + longDate: string; + mediumDate: string; + shortDate: string; + mediumTime: string; + shortTime: string; + } + + /////////////////////////////////////////////////////////////////////////// + // LogService + // see http://docs.angularjs.org/api/ng.$log + // see http://docs.angularjs.org/api/ng.$logProvider + /////////////////////////////////////////////////////////////////////////// + interface ILogService { + debug: ILogCall; + error: ILogCall; + info: ILogCall; + log: ILogCall; + warn: ILogCall; + } + + interface ILogProvider extends IServiceProvider { + debugEnabled(): boolean; + debugEnabled(enabled: boolean): ILogProvider; + } + + // We define this as separate interface so we can reopen it later for + // the ngMock module. + interface ILogCall { + (...args: any[]): void; + } + + /////////////////////////////////////////////////////////////////////////// + // ParseService + // see http://docs.angularjs.org/api/ng.$parse + // see http://docs.angularjs.org/api/ng.$parseProvider + /////////////////////////////////////////////////////////////////////////// + interface IParseService { + (expression: string): ICompiledExpression; + } + + interface IParseProvider { + logPromiseWarnings(): boolean; + logPromiseWarnings(value: boolean): IParseProvider; + + unwrapPromises(): boolean; + unwrapPromises(value: boolean): IParseProvider; + + /** + * Configure $parse service to add literal values that will be present as literal at expressions. + * + * @param literalName Token for the literal value. The literal name value must be a valid literal name. + * @param literalValue Value for this literal. All literal values must be primitives or `undefined`. + **/ + addLiteral(literalName: string, literalValue: any): void; + + /** + * Allows defining the set of characters that are allowed in Angular expressions. The function identifierStart will get called to know if a given character is a valid character to be the first character for an identifier. The function identifierContinue will get called to know if a given character is a valid character to be a follow-up identifier character. The functions identifierStart and identifierContinue will receive as arguments the single character to be identifier and the character code point. These arguments will be string and numeric. Keep in mind that the string parameter can be two characters long depending on the character representation. It is expected for the function to return true or false, whether that character is allowed or not. + * Since this function will be called extensivelly, keep the implementation of these functions fast, as the performance of these functions have a direct impact on the expressions parsing speed. + * + * @param identifierStart The function that will decide whether the given character is a valid identifier start character. + * @param identifierContinue The function that will decide whether the given character is a valid identifier continue character. + **/ + setIdentifierFns(identifierStart?: (character: string, codePoint: number) => boolean, + identifierContinue?: (character: string, codePoint: number) => boolean): void; + } + + interface ICompiledExpression { + (context: any, locals?: any): any; + + literal: boolean; + constant: boolean; + + // If value is not provided, undefined is gonna be used since the implementation + // does not check the parameter. Let's force a value for consistency. If consumer + // whants to undefine it, pass the undefined value explicitly. + assign(context: any, value: any): any; + } + + /** + * $location - $locationProvider - service in module ng + * see https://docs.angularjs.org/api/ng/service/$location + */ + interface ILocationService { + absUrl(): string; + hash(): string; + hash(newHash: string): ILocationService; + host(): string; + + /** + * Return path of current url + */ + path(): string; + + /** + * Change path when called with parameter and return $location. + * Note: Path should always begin with forward slash (/), this method will add the forward slash if it is missing. + * + * @param path New path + */ + path(path: string): ILocationService; + + port(): number; + protocol(): string; + replace(): ILocationService; + + /** + * Return search part (as object) of current url + */ + search(): any; + + /** + * Change search part when called with parameter and return $location. + * + * @param search When called with a single argument the method acts as a setter, setting the search component of $location to the specified value. + * + * If the argument is a hash object containing an array of values, these values will be encoded as duplicate search parameters in the url. + */ + search(search: any): ILocationService; + + /** + * Change search part when called with parameter and return $location. + * + * @param search New search params + * @param paramValue If search is a string or a Number, then paramValue will override only a single search property. If paramValue is null, the property specified via the first argument will be deleted. If paramValue is an array, it will override the property of the search component of $location specified via the first argument. If paramValue is true, the property specified via the first argument will be added with no value nor trailing equal sign. + */ + search(search: string, paramValue: string|number|string[]|boolean): ILocationService; + + state(): any; + state(state: any): ILocationService; + url(): string; + url(url: string): ILocationService; + } + + interface ILocationProvider extends IServiceProvider { + hashPrefix(): string; + hashPrefix(prefix: string): ILocationProvider; + html5Mode(): boolean; + + // Documentation states that parameter is string, but + // implementation tests it as boolean, which makes more sense + // since this is a toggler + html5Mode(active: boolean): ILocationProvider; + html5Mode(mode: { enabled?: boolean; requireBase?: boolean; rewriteLinks?: boolean; }): ILocationProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // DocumentService + // see http://docs.angularjs.org/api/ng.$document + /////////////////////////////////////////////////////////////////////////// + interface IDocumentService extends JQuery {} + + /////////////////////////////////////////////////////////////////////////// + // ExceptionHandlerService + // see http://docs.angularjs.org/api/ng.$exceptionHandler + /////////////////////////////////////////////////////////////////////////// + interface IExceptionHandlerService { + (exception: Error, cause?: string): void; + } + + /////////////////////////////////////////////////////////////////////////// + // RootElementService + // see http://docs.angularjs.org/api/ng.$rootElement + /////////////////////////////////////////////////////////////////////////// + interface IRootElementService extends JQuery {} + + interface IQResolveReject { + (): void; + (value: T): void; + } + /** + * $q - service in module ng + * A promise/deferred implementation inspired by Kris Kowal's Q. + * See http://docs.angularjs.org/api/ng/service/$q + */ + interface IQService { + new (resolver: (resolve: IQResolveReject) => any): IPromise; + new (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; + (resolver: (resolve: IQResolveReject) => any): IPromise; + (resolver: (resolve: IQResolveReject, reject: IQResolveReject) => any): IPromise; + + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * + * Returns a single promise that will be resolved with an array of values, each value corresponding to the promise at the same index in the promises array. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises An array of promises. + */ + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise, T7 | IPromise, T8 | IPromise, T9 | IPromise, T10 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise, T7 | IPromise, T8 | IPromise, T9 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise, T7 | IPromise, T8 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6, T7, T8]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise, T7 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6, T7]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise, T6 | IPromise]): IPromise<[T1, T2, T3, T4, T5, T6]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise , T5 | IPromise]): IPromise<[T1, T2, T3, T4, T5]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise, T4 | IPromise ]): IPromise<[T1, T2, T3, T4]>; + all(values: [T1 | IPromise, T2 | IPromise, T3 | IPromise]): IPromise<[T1, T2, T3]>; + all(values: [T1 | IPromise, T2 | IPromise]): IPromise<[T1, T2]>; + all(promises: IPromise[]): IPromise; + /** + * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved. + * + * Returns a single promise that will be resolved with a hash of values, each value corresponding to the promise at the same key in the promises hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value. + * + * @param promises A hash of promises. + */ + all(promises: { [id: string]: IPromise; }): IPromise<{ [id: string]: any; }>; + all(promises: { [id: string]: IPromise; }): IPromise; + /** + * Creates a Deferred object which represents a task which will finish in the future. + */ + defer(): IDeferred; + /** + * Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it. + * + * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you "catch" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to "rethrow" the error by returning a rejection constructed via reject. + * + * @param reason Constant, message, exception or an object representing the rejection reason. + */ + reject(reason?: any): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ + resolve(value: IPromise|T): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + */ + resolve(): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + * + * @param value Value or a promise + */ + when(value: IPromise|T): IPromise; + /** + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted. + */ + when(): IPromise; + } + + interface IPromise { + /** + * Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected. + * The successCallBack may return IPromise for when a $q.reject() needs to be returned + * This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method. + */ + then(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + + /** + * Shorthand for promise.then(null, errorCallback) + */ + catch(onRejected: (reason: any) => IPromise|TResult): IPromise; + + /** + * Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information. + * + * Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible. + */ + finally(finallyCallback: () => any): IPromise; + } + + interface IDeferred { + resolve(value?: T|IPromise): void; + reject(reason?: any): void; + notify(state?: any): void; + promise: IPromise; + } + + /////////////////////////////////////////////////////////////////////////// + // AnchorScrollService + // see http://docs.angularjs.org/api/ng.$anchorScroll + /////////////////////////////////////////////////////////////////////////// + interface IAnchorScrollService { + (): void; + (hash: string): void; + yOffset: any; + } + + interface IAnchorScrollProvider extends IServiceProvider { + disableAutoScrolling(): void; + } + + /** + * $cacheFactory - service in module ng + * + * Factory that constructs Cache objects and gives access to them. + * + * see https://docs.angularjs.org/api/ng/service/$cacheFactory + */ + interface ICacheFactoryService { + /** + * Factory that constructs Cache objects and gives access to them. + * + * @param cacheId Name or id of the newly created cache. + * @param optionsMap Options object that specifies the cache behavior. Properties: + * + * capacity — turns the cache into LRU cache. + */ + (cacheId: string, optionsMap?: { capacity?: number; }): ICacheObject; + + /** + * Get information about all the caches that have been created. + * @returns key-value map of cacheId to the result of calling cache#info + */ + info(): any; + + /** + * Get access to a cache object by the cacheId used when it was created. + * + * @param cacheId Name or id of a cache to access. + */ + get(cacheId: string): ICacheObject; + } + + /** + * $cacheFactory.Cache - type in module ng + * + * A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data. + * + * see https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache + */ + interface ICacheObject { + /** + * Retrieve information regarding a particular Cache. + */ + info(): { + /** + * the id of the cache instance + */ + id: string; + + /** + * the number of entries kept in the cache instance + */ + size: number; + + //...: any additional properties from the options object when creating the cache. + }; + + /** + * Inserts a named entry into the Cache object to be retrieved later, and incrementing the size of the cache if the key was not already present in the cache. If behaving like an LRU cache, it will also remove stale entries from the set. + * + * It will not insert undefined values into the cache. + * + * @param key the key under which the cached data is stored. + * @param value the value to store alongside the key. If it is undefined, the key will not be stored. + */ + put(key: string, value?: T): T; + + /** + * Retrieves named data stored in the Cache object. + * + * @param key the key of the data to be retrieved + */ + get(key: string): T; + + /** + * Removes an entry from the Cache object. + * + * @param key the key of the entry to be removed + */ + remove(key: string): void; + + /** + * Clears the cache object of any entries. + */ + removeAll(): void; + + /** + * Destroys the Cache object entirely, removing it from the $cacheFactory set. + */ + destroy(): void; + } + + /////////////////////////////////////////////////////////////////////////// + // CompileService + // see http://docs.angularjs.org/api/ng.$compile + // see http://docs.angularjs.org/api/ng.$compileProvider + /////////////////////////////////////////////////////////////////////////// + interface ICompileService { + (element: string, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: Element, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + (element: JQuery, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction; + } + + interface ICompileProvider extends IServiceProvider { + directive(name: string, directiveFactory: Function): ICompileProvider; + directive(directivesMap: Object, directiveFactory: Function): ICompileProvider; + directive(name: string, inlineAnnotatedFunction: any[]): ICompileProvider; + directive(directivesMap: Object, inlineAnnotatedFunction: any[]): ICompileProvider; + + // Undocumented, but it is there... + directive(directivesMap: any): ICompileProvider; + + component(name: string, options: IComponentOptions): ICompileProvider; + + aHrefSanitizationWhitelist(): RegExp; + aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider; + + imgSrcSanitizationWhitelist(): RegExp; + imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider; + + debugInfoEnabled(enabled?: boolean): any; + } + + interface ICloneAttachFunction { + // Let's hint but not force cloneAttachFn's signature + (clonedElement?: JQuery, scope?: IScope): any; + } + + // This corresponds to the "publicLinkFn" returned by $compile. + interface ITemplateLinkingFunction { + (scope: IScope, cloneAttachFn?: ICloneAttachFunction): JQuery; + } + + // This corresponds to $transclude (and also the transclude function passed to link). + interface ITranscludeFunction { + // If the scope is provided, then the cloneAttachFn must be as well. + (scope: IScope, cloneAttachFn: ICloneAttachFunction): JQuery; + // If one argument is provided, then it's assumed to be the cloneAttachFn. + (cloneAttachFn?: ICloneAttachFunction): JQuery; + } + + /////////////////////////////////////////////////////////////////////////// + // ControllerService + // see http://docs.angularjs.org/api/ng.$controller + // see http://docs.angularjs.org/api/ng.$controllerProvider + /////////////////////////////////////////////////////////////////////////// + interface IControllerService { + // Although the documentation doesn't state this, locals are optional + (controllerConstructor: new (...args: any[]) => T, locals?: any, later?: boolean, ident?: string): T; + (controllerConstructor: Function, locals?: any, later?: boolean, ident?: string): T; + (controllerName: string, locals?: any, later?: boolean, ident?: string): T; + } + + interface IControllerProvider extends IServiceProvider { + register(name: string, controllerConstructor: Function): void; + register(name: string, dependencyAnnotatedConstructor: any[]): void; + allowGlobals(): void; + } + + /** + * xhrFactory + * Replace or decorate this service to create your own custom XMLHttpRequest objects. + * see https://docs.angularjs.org/api/ng/service/$xhrFactory + */ + interface IXhrFactory { + (method: string, url: string): T; + } + + /** + * HttpService + * see http://docs.angularjs.org/api/ng/service/$http + */ + interface IHttpService { + /** + * Object describing the request to be made and how it should be processed. + */ + (config: IRequestConfig): IHttpPromise; + + /** + * Shortcut method to perform GET request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + get(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform DELETE request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + delete(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform HEAD request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + head(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform JSONP request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param config Optional configuration object + */ + jsonp(url: string, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform POST request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + post(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform PUT request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + put(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Shortcut method to perform PATCH request. + * + * @param url Relative or absolute URL specifying the destination of the request + * @param data Request content + * @param config Optional configuration object + */ + patch(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise; + + /** + * Runtime equivalent of the $httpProvider.defaults property. Allows configuration of default headers, withCredentials as well as request and response transformations. + */ + defaults: IHttpProviderDefaults; + + /** + * Array of config objects for currently pending requests. This is primarily meant to be used for debugging purposes. + */ + pendingRequests: IRequestConfig[]; + } + + /** + * Object describing the request to be made and how it should be processed. + * see http://docs.angularjs.org/api/ng/service/$http#usage + */ + interface IRequestShortcutConfig extends IHttpProviderDefaults { + /** + * {Object.} + * Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified. + */ + params?: any; + + /** + * {string|Object} + * Data to be sent as the request message data. + */ + data?: any; + + /** + * Timeout in milliseconds, or promise that should abort the request when resolved. + */ + timeout?: number|IPromise; + + /** + * See [XMLHttpRequest.responseType]https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype + */ + responseType?: string; + } + + /** + * Object describing the request to be made and how it should be processed. + * see http://docs.angularjs.org/api/ng/service/$http#usage + */ + interface IRequestConfig extends IRequestShortcutConfig { + /** + * HTTP method (e.g. 'GET', 'POST', etc) + */ + method: string; + /** + * Absolute or relative URL of the resource that is being requested. + */ + url: string; + } + + interface IHttpHeadersGetter { + (): { [name: string]: string; }; + (headerName: string): string; + } + + interface IHttpPromiseCallback { + (data: T, status: number, headers: IHttpHeadersGetter, config: IRequestConfig): void; + } + + interface IHttpPromiseCallbackArg { + data?: T; + status?: number; + headers?: IHttpHeadersGetter; + config?: IRequestConfig; + statusText?: string; + } + + interface IHttpPromise extends IPromise> { + /** + * The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. + * If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error. + * @deprecated + */ + success?(callback: IHttpPromiseCallback): IHttpPromise; + /** + * The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. + * If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error. + * @deprecated + */ + error?(callback: IHttpPromiseCallback): IHttpPromise; + } + + // See the jsdoc for transformData() at https://github.com/angular/angular.js/blob/master/src/ng/http.js#L228 + interface IHttpRequestTransformer { + (data: any, headersGetter: IHttpHeadersGetter): any; + } + + // The definition of fields are the same as IHttpPromiseCallbackArg + interface IHttpResponseTransformer { + (data: any, headersGetter: IHttpHeadersGetter, status: number): any; + } + + type HttpHeaderType = {[requestType: string]:string|((config:IRequestConfig) => string)}; + + interface IHttpRequestConfigHeaders { + [requestType: string]: any; + common?: any; + get?: any; + post?: any; + put?: any; + patch?: any; + } + + /** + * Object that controls the defaults for $http provider. Not all fields of IRequestShortcutConfig can be configured + * via defaults and the docs do not say which. The following is based on the inspection of the source code. + * https://docs.angularjs.org/api/ng/service/$http#defaults + * https://docs.angularjs.org/api/ng/service/$http#usage + * https://docs.angularjs.org/api/ng/provider/$httpProvider The properties section + */ + interface IHttpProviderDefaults { + /** + * {boolean|Cache} + * If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching. + */ + cache?: any; + + /** + * Transform function or an array of such functions. The transform function takes the http request body and + * headers and returns its transformed (typically serialized) version. + * @see {@link https://docs.angularjs.org/api/ng/service/$http#transforming-requests-and-responses} + */ + transformRequest?: IHttpRequestTransformer |IHttpRequestTransformer[]; + + /** + * Transform function or an array of such functions. The transform function takes the http response body and + * headers and returns its transformed (typically deserialized) version. + */ + transformResponse?: IHttpResponseTransformer | IHttpResponseTransformer[]; + + /** + * Map of strings or functions which return strings representing HTTP headers to send to the server. If the + * return value of a function is null, the header will not be sent. + * The key of the map is the request verb in lower case. The "common" key applies to all requests. + * @see {@link https://docs.angularjs.org/api/ng/service/$http#setting-http-headers} + */ + headers?: IHttpRequestConfigHeaders; + + /** Name of HTTP header to populate with the XSRF token. */ + xsrfHeaderName?: string; + + /** Name of cookie containing the XSRF token. */ + xsrfCookieName?: string; + + /** + * whether to to set the withCredentials flag on the XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 for more information. + */ + withCredentials?: boolean; + + /** + * A function used to the prepare string representation of request parameters (specified as an object). If + * specified as string, it is interpreted as a function registered with the $injector. Defaults to + * $httpParamSerializer. + */ + paramSerializer?: string | ((obj: any) => string); + } + + interface IHttpInterceptor { + request?: (config: IRequestConfig) => IRequestConfig|IPromise; + requestError?: (rejection: any) => any; + response?: (response: IHttpPromiseCallbackArg) => IPromise>|IHttpPromiseCallbackArg; + responseError?: (rejection: any) => any; + } + + interface IHttpInterceptorFactory { + (...args: any[]): IHttpInterceptor; + } + + interface IHttpProvider extends IServiceProvider { + defaults: IHttpProviderDefaults; + + /** + * Register service factories (names or implementations) for interceptors which are called before and after + * each request. + */ + interceptors: (string|IHttpInterceptorFactory|(string|IHttpInterceptorFactory)[])[]; + useApplyAsync(): boolean; + useApplyAsync(value: boolean): IHttpProvider; + + /** + * + * @param {boolean=} value If true, `$http` will return a normal promise without the `success` and `error` methods. + * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. + * otherwise, returns the current configured value. + */ + useLegacyPromiseExtensions(value:boolean) : boolean | IHttpProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // HttpBackendService + // see http://docs.angularjs.org/api/ng.$httpBackend + // You should never need to use this service directly. + /////////////////////////////////////////////////////////////////////////// + interface IHttpBackendService { + // XXX Perhaps define callback signature in the future + (method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: boolean): void; + } + + /////////////////////////////////////////////////////////////////////////// + // InterpolateService + // see http://docs.angularjs.org/api/ng.$interpolate + // see http://docs.angularjs.org/api/ng.$interpolateProvider + /////////////////////////////////////////////////////////////////////////// + interface IInterpolateService { + (text: string, mustHaveExpression?: boolean, trustedContext?: string, allOrNothing?: boolean): IInterpolationFunction; + endSymbol(): string; + startSymbol(): string; + } + + interface IInterpolationFunction { + (context: any): string; + } + + interface IInterpolateProvider extends IServiceProvider { + startSymbol(): string; + startSymbol(value: string): IInterpolateProvider; + endSymbol(): string; + endSymbol(value: string): IInterpolateProvider; + } + + /////////////////////////////////////////////////////////////////////////// + // TemplateCacheService + // see http://docs.angularjs.org/api/ng.$templateCache + /////////////////////////////////////////////////////////////////////////// + interface ITemplateCacheService extends ICacheObject {} + + /////////////////////////////////////////////////////////////////////////// + // SCEService + // see http://docs.angularjs.org/api/ng.$sce + /////////////////////////////////////////////////////////////////////////// + interface ISCEService { + getTrusted(type: string, mayBeTrusted: any): any; + getTrustedCss(value: any): any; + getTrustedHtml(value: any): any; + getTrustedJs(value: any): any; + getTrustedResourceUrl(value: any): any; + getTrustedUrl(value: any): any; + parse(type: string, expression: string): (context: any, locals: any) => any; + parseAsCss(expression: string): (context: any, locals: any) => any; + parseAsHtml(expression: string): (context: any, locals: any) => any; + parseAsJs(expression: string): (context: any, locals: any) => any; + parseAsResourceUrl(expression: string): (context: any, locals: any) => any; + parseAsUrl(expression: string): (context: any, locals: any) => any; + trustAs(type: string, value: any): any; + trustAsHtml(value: any): any; + trustAsJs(value: any): any; + trustAsResourceUrl(value: any): any; + trustAsUrl(value: any): any; + isEnabled(): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // SCEProvider + // see http://docs.angularjs.org/api/ng.$sceProvider + /////////////////////////////////////////////////////////////////////////// + interface ISCEProvider extends IServiceProvider { + enabled(value: boolean): void; + } + + /////////////////////////////////////////////////////////////////////////// + // SCEDelegateService + // see http://docs.angularjs.org/api/ng.$sceDelegate + /////////////////////////////////////////////////////////////////////////// + interface ISCEDelegateService { + getTrusted(type: string, mayBeTrusted: any): any; + trustAs(type: string, value: any): any; + valueOf(value: any): any; + } + + + /////////////////////////////////////////////////////////////////////////// + // SCEDelegateProvider + // see http://docs.angularjs.org/api/ng.$sceDelegateProvider + /////////////////////////////////////////////////////////////////////////// + interface ISCEDelegateProvider extends IServiceProvider { + resourceUrlBlacklist(blacklist: any[]): void; + resourceUrlWhitelist(whitelist: any[]): void; + resourceUrlBlacklist(): any[]; + resourceUrlWhitelist(): any[]; + } + + /** + * $templateRequest service + * see http://docs.angularjs.org/api/ng/service/$templateRequest + */ + interface ITemplateRequestService { + /** + * Downloads a template using $http and, upon success, stores the + * contents inside of $templateCache. + * + * If the HTTP request fails or the response data of the HTTP request is + * empty then a $compile error will be thrown (unless + * {ignoreRequestError} is set to true). + * + * @param tpl The template URL. + * @param ignoreRequestError Whether or not to ignore the exception + * when the request fails or the template is + * empty. + * + * @return A promise whose value is the template content. + */ + (tpl: string, ignoreRequestError?: boolean): IPromise; + /** + * total amount of pending template requests being downloaded. + * @type {number} + */ + totalPendingRequests: number; + } + + /////////////////////////////////////////////////////////////////////////// + // Component + // see http://angularjs.blogspot.com.br/2015/11/angularjs-15-beta2-and-14-releases.html + // and http://toddmotto.com/exploring-the-angular-1-5-component-method/ + /////////////////////////////////////////////////////////////////////////// + /** + * Component definition object (a simplified directive definition object) + */ + interface IComponentOptions { + /** + * Controller constructor function that should be associated with newly created scope or the name of a registered + * controller if passed as a string. Empty function by default. + * Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection) + */ + controller?: string | Function | (string | Function)[] | IComponentController; + /** + * An identifier name for a reference to the controller. If present, the controller will be published to scope under + * the controllerAs name. If not present, this will default to be the same as the component name. + * @default "$ctrl" + */ + controllerAs?: string; + /** + * html template as a string or a function that returns an html template as a string which should be used as the + * contents of this component. Empty string by default. + * If template is a function, then it is injected with the following locals: + * $element - Current element + * $attrs - Current attributes object for the element + * Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection) + */ + template?: string | Function | (string | Function)[]; + /** + * path or function that returns a path to an html template that should be used as the contents of this component. + * If templateUrl is a function, then it is injected with the following locals: + * $element - Current element + * $attrs - Current attributes object for the element + * Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection) + */ + templateUrl?: string | Function | (string | Function)[]; + /** + * Define DOM attribute binding to component properties. Component properties are always bound to the component + * controller and not to the scope. + */ + bindings?: {[binding: string]: string}; + /** + * Whether transclusion is enabled. Enabled by default. + */ + transclude?: boolean | string | {[slot: string]: string}; + require?: {[controller: string]: string}; + } + + interface IComponentTemplateFn { + ( $element?: JQuery, $attrs?: IAttributes ): string; + } + + /** + * Components have a well-defined lifecycle Each component can implement "lifecycle hooks". These are methods that + * will be called at certain points in the life of the component. + * @url https://docs.angularjs.org/guide/component + */ + interface IComponentController { + /** + * Called on each controller after all the controllers on an element have been constructed and had their bindings + * initialized (and before the pre & post linking functions for the directives on this element). This is a good + * place to put initialization code for your controller. + */ + $onInit?(): void; + /** + * Called whenever one-way bindings are updated. The changesObj is a hash whose keys are the names of the bound + * properties that have changed, and the values are an {@link IChangesObject} object of the form + * { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component such as + * cloning the bound value to prevent accidental mutation of the outer value. + */ + $onChanges?(changesObj: {[property:string]: IChangesObject}): void; + /** + * Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources, + * watches and event handlers. + */ + $onDestroy?(): void; + /** + * Called after this controller's element and its children have been linked. Similar to the post-link function this + * hook can be used to set up DOM event handlers and do direct DOM manipulation. Note that child elements that contain + * templateUrl directives will not have been compiled and linked since they are waiting for their template to load + * asynchronously and their own compilation and linking has been suspended until that occurs. This hook can be considered + * analogous to the ngAfterViewInit and ngAfterContentInit hooks in Angular 2. Since the compilation process is rather + * different in Angular 1 there is no direct mapping and care should be taken when upgrading. + */ + $postLink?(): void; + } + + interface IChangesObject { + currentValue: any; + previousValue: any; + isFirstChange(): boolean; + } + + /////////////////////////////////////////////////////////////////////////// + // Directive + // see http://docs.angularjs.org/api/ng.$compileProvider#directive + // and http://docs.angularjs.org/guide/directive + /////////////////////////////////////////////////////////////////////////// + + interface IDirectiveFactory { + (...args: any[]): IDirective; + } + + interface IDirectiveLinkFn { + ( + scope: IScope, + instanceElement: JQuery, + instanceAttributes: IAttributes, + controller: {}, + transclude: ITranscludeFunction + ): void; + } + + interface IDirectivePrePost { + pre?: IDirectiveLinkFn; + post?: IDirectiveLinkFn; + } + + interface IDirectiveCompileFn { + ( + templateElement: JQuery, + templateAttributes: IAttributes, + /** + * @deprecated + * Note: The transclude function that is passed to the compile function is deprecated, + * as it e.g. does not know about the right outer scope. Please use the transclude function + * that is passed to the link function instead. + */ + transclude: ITranscludeFunction + ): void | IDirectivePrePost; + } + + interface IDirective { + compile?: IDirectiveCompileFn; + controller?: any; + controllerAs?: string; + /** + * @deprecated + * Deprecation warning: although bindings for non-ES6 class controllers are currently bound to this before + * the controller constructor is called, this use is now deprecated. Please place initialization code that + * relies upon bindings inside a $onInit method on the controller, instead. + */ + bindToController?: boolean | Object; + link?: IDirectiveLinkFn | IDirectivePrePost; + multiElement?: boolean; + name?: string; + priority?: number; + /** + * @deprecated + */ + replace?: boolean; + require?: string | string[] | {[controller: string]: string}; + restrict?: string; + scope?: boolean | Object; + template?: string | Function; + templateNamespace?: string; + templateUrl?: string | Function; + terminal?: boolean; + transclude?: boolean | string | {[slot: string]: string}; + } + + /** + * These interfaces are kept for compatibility with older versions of these type definitions. + * Actually, Angular doesn't create a special subclass of jQuery objects. It extends jQuery.prototype + * like jQuery plugins do, that's why all jQuery objects have these Angular-specific methods, not + * only those returned from angular.element. + * See: http://docs.angularjs.org/api/angular.element + */ + interface IAugmentedJQueryStatic extends JQueryStatic {} + interface IAugmentedJQuery extends JQuery {} + + /////////////////////////////////////////////////////////////////////////// + // AUTO module (angular.js) + /////////////////////////////////////////////////////////////////////////// + export module auto { + + /////////////////////////////////////////////////////////////////////// + // InjectorService + // see http://docs.angularjs.org/api/AUTO.$injector + /////////////////////////////////////////////////////////////////////// + interface IInjectorService { + annotate(fn: Function, strictDi?: boolean): string[]; + annotate(inlineAnnotatedFunction: any[]): string[]; + get(name: string, caller?: string): T; + get(name: '$anchorScroll'): IAnchorScrollService + get(name: '$cacheFactory'): ICacheFactoryService + get(name: '$compile'): ICompileService + get(name: '$controller'): IControllerService + get(name: '$document'): IDocumentService + get(name: '$exceptionHandler'): IExceptionHandlerService + get(name: '$filter'): IFilterService + get(name: '$http'): IHttpService + get(name: '$httpBackend'): IHttpBackendService + get(name: '$httpParamSerializer'): IHttpParamSerializer + get(name: '$httpParamSerializerJQLike'): IHttpParamSerializer + get(name: '$interpolate'): IInterpolateService + get(name: '$interval'): IIntervalService + get(name: '$locale'): ILocaleService + get(name: '$location'): ILocationService + get(name: '$log'): ILogService + get(name: '$parse'): IParseService + get(name: '$q'): IQService + get(name: '$rootElement'): IRootElementService + get(name: '$rootScope'): IRootScopeService + get(name: '$sce'): ISCEService + get(name: '$sceDelegate'): ISCEDelegateService + get(name: '$templateCache'): ITemplateCacheService + get(name: '$templateRequest'): ITemplateRequestService + get(name: '$timeout'): ITimeoutService + get(name: '$window'): IWindowService + get(name: '$xhrFactory'): IXhrFactory + has(name: string): boolean; + instantiate(typeConstructor: Function, locals?: any): T; + invoke(inlineAnnotatedFunction: any[]): any; + invoke(func: Function, context?: any, locals?: any): any; + strictDi: boolean; + } + + /////////////////////////////////////////////////////////////////////// + // ProvideService + // see http://docs.angularjs.org/api/AUTO.$provide + /////////////////////////////////////////////////////////////////////// + interface IProvideService { + // Documentation says it returns the registered instance, but actual + // implementation does not return anything. + // constant(name: string, value: any): any; + /** + * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator. + * + * @param name The name of the constant. + * @param value The constant value. + */ + constant(name: string, value: any): void; + + /** + * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. + * + * @param name The name of the service to decorate. + * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: + * + * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. + */ + decorator(name: string, decorator: Function): void; + /** + * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service. + * + * @param name The name of the service to decorate. + * @param inlineAnnotatedFunction This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: + * + * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to. + */ + decorator(name: string, inlineAnnotatedFunction: any[]): void; + factory(name: string, serviceFactoryFunction: Function): IServiceProvider; + factory(name: string, inlineAnnotatedFunction: any[]): IServiceProvider; + provider(name: string, provider: IServiceProvider): IServiceProvider; + provider(name: string, serviceProviderConstructor: Function): IServiceProvider; + service(name: string, constructor: Function): IServiceProvider; + service(name: string, inlineAnnotatedFunction: any[]): IServiceProvider; + value(name: string, value: any): IServiceProvider; + } + + } + + /** + * $http params serializer that converts objects to strings + * see https://docs.angularjs.org/api/ng/service/$httpParamSerializer + */ + interface IHttpParamSerializer { + (obj: Object): string; + } +} + +interface JQuery { + // TODO: events, how to define? + //$destroy + + find(element: any): JQuery; + find(obj: JQuery): JQuery; + controller(name?: string): any; + injector(): ng.auto.IInjectorService; + /** It's declared generic for custom scope interfaces */ + scope(): T; + isolateScope(): T; + + inheritedData(key: string, value: any): JQuery; + inheritedData(obj: { [key: string]: any; }): JQuery; + inheritedData(key?: string): any; +} diff --git a/ngClient/_system/js/lib/breeze/breeze.d.ts b/ngClient/_system/js/lib/breeze/breeze.d.ts new file mode 100644 index 000000000..051b53908 --- /dev/null +++ b/ngClient/_system/js/lib/breeze/breeze.d.ts @@ -0,0 +1,1130 @@ +// Type definitions for Breeze 1.5.x +// Project: http://www.breezejs.com/ +// Definitions by: Boris Yankov , IdeaBlade +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Updated Jan 14 2011 - Jay Traband ( www.ideablade.com). +// Updated Aug 13 2013 - Steve Schmitt ( www.ideablade.com). +// Updated Sep 26 2013 for Breeze 1.4.3 - Steve Schmitt ( www.ideablade.com). +// Updated Jul 22 2014 for Breeze 1.4.16 - Steve Schmitt ( www.ideablade.com) +// Updated Aug 22 2014 for Breeze 1.4.17 and removing Q dependency - Steve Schmitt ( www.ideablade.com) +// Updated Jan 16 2015 for Breeze 1.4.17 to add support for noimplicitany - Kevin Wilson ( www.kwilson.me.uk ) +// Updated Jan 20 2015 for Breeze 1.5.2 and merging changes from DefinitelyTyped +// Updated Feb 28 2015 add any/all clause on Predicate +// Updated Jun 27 2016 - Marcel Good (www.ideablade.com) + +declare namespace breeze.core { + + export interface ErrorCallback { + (error: Error): void; + } + + export interface IEnum { + contains(object: any): boolean; + fromName(name: string): EnumSymbol; + getNames(): string[]; + getSymbols(): EnumSymbol[]; + } + + export class Enum implements IEnum { + constructor(name: string, methodObj?: any); + + addSymbol(propertiesObj?: any): EnumSymbol; + contains(object: any): boolean; + fromName(name: string): EnumSymbol; + getNames(): string[]; + getSymbols(): EnumSymbol[]; + static isSymbol(object: any): boolean; + resolveSymbols(): void; + } + + export class EnumSymbol { + parentEnum: IEnum; + + getName(): string; + toString(): string; + } + + export class Event { + constructor(name: string, publisher: any, defaultErrorCallback?: ErrorCallback); + + static enable(eventName: string, target: any): void; + static enable(eventName: string, target: any, isEnabled: boolean): void; + static enable(eventName: string, target: any, isEnabled: Function): void; + + static isEnabled(eventName: string, target: any): boolean; + publish(data: any, publishAsync?: boolean, errorCallback?: ErrorCallback): void; + publishAsync(data: any, errorCallback?: ErrorCallback): void; + subscribe(callback?: (data: any) => void): number; + unsubscribe(unsubKey: number): boolean; + clear(): void; + } + + export function objectForEach(obj: Object, kvfn: (key: string, value: any) => void): void; + + export function extend(target: Object, source: Object): Object; + export function propEq(propertyName: string, value: any): (obj: Object) => boolean; + export function pluck(propertyName: string): (obj: Object) => any; + export function arrayEquals(a1: any[], a2: any[], equalsFn: (e1: any, e2: any) => boolean): boolean; + export function arrayFirst(a1: any[], predicate: (e: any) => boolean): any; + export function arrayIndexOf(a1: any[], predicate: (e: any) => boolean): number; + export function arrayRemoveItem(array: any[], item: any, shouldRemoveMultiple: boolean): any; + export function arrayRemoveItem(array: any[], predicate: (e: any) => boolean, shouldRemoveMultiple: boolean): any; + export function arrayZip(a1: any[], a2: any[], callback: (e1: any, e2: any) => any): any[]; + + export function requireLib(libnames: string, errMessage: string): Object; + export function using(obj: Object, property: string, tempValue: any, fn: () => any): any; + export function memoize(fn: (...any: any[]) => any): any; + export function getUuid(): string; + export function durationToSeconds(duration: string): number; + + export function isDate(o: any): boolean; + export function isGuid(o: any): boolean; + export function isDuration(o: any): boolean; + export function isFunction(o: any): boolean; + export function isEmpty(o: any): boolean; + export function isNumeric(o: any): boolean; + + export function stringStartsWith(str: string, prefix: string): boolean; + export function stringEndsWith(str: string, suffix: string): boolean; + export function formatString(format: string, ...args: any[]): string; +} + +declare namespace breeze { + + export interface Entity { + entityAspect: EntityAspect; + entityType: EntityType; + } + + export interface ComplexObject { + complexAspect: ComplexAspect; + complexType: ComplexType; + } + + export interface IProperty { + name: string; + nameOnServer: string; + displayName: string; + parentType: IStructuralType; + validators: Validator[]; + isDataProperty: boolean; + isNavigationProperty: boolean; + } + + export interface IStructuralType { + complexProperties: DataProperty[]; + dataProperties: DataProperty[]; + name: string; + namespace: string; + shortName: string; + unmappedProperties: DataProperty[]; + validators: Validator[]; + } + + export class AutoGeneratedKeyType { + static Identity: AutoGeneratedKeyType; + static KeyGenerator: AutoGeneratedKeyType; + static None: AutoGeneratedKeyType; + } + + export class ComplexAspect { + complexObject: ComplexObject; + getEntityAspect(): EntityAspect; + parent: Object; + parentProperty: DataProperty; + getPropertyPath(propName: string): string; + originalValues: Object; + } + + export class ComplexType implements IStructuralType { + complexProperties: DataProperty[]; + dataProperties: DataProperty[]; + name: string; + namespace: string; + shortName: string; + unmappedProperties: DataProperty[]; + validators: Validator[]; + addProperty(dataProperty: DataProperty): ComplexType; + getProperties(): DataProperty[]; + } + + export class DataProperty implements IProperty { + complexTypeName: string; + concurrencyMode: string; + dataType: DataTypeSymbol; + defaultValue: any; + isComplexProperty: boolean; + isDataProperty: boolean; + isInherited: boolean; + isNavigationProperty: boolean; + isNullable: boolean; + isPartOfKey: boolean; + isUnmapped: boolean; + + maxLength: number; + name: string; + nameOnServer: string; + displayName: string; + parentType: IStructuralType; + relatedNavigationProperty: NavigationProperty; + validators: Validator[]; + constructor(config: DataPropertyOptions); + } + + export interface DataPropertyOptions { + complexTypeName?: string; + concurrencyMode?: string; + custom?: any; + dataType?: DataTypeSymbol; + defaultValue?: any; + displayName?: string; + isNullable?: boolean; + isPartOfKey?: boolean; + isScalar?: boolean; + isUnmapped?: boolean; + maxLength?: number; + name?: string; + nameOnServer?: string; + validators?: Validator[]; + } + + export class DataService { + adapterInstance: DataServiceAdapter; + adapterName: string; + hasServerMetadata: boolean; + serviceName: string; + uriBuilderName: string; + jsonResultsAdapter: JsonResultsAdapter; + useJsonp: boolean; + constructor(config: DataServiceOptions); + using(config: DataServiceOptions): DataService; + } + + export interface DataServiceOptions { + serviceName?: string; + adapterName?: string; + uriBuilderName?: string; + hasServerMetadata?: boolean; + jsonResultsAdapter?: JsonResultsAdapter; + useJsonp?: boolean; + } + + export class DataServiceAdapter { + checkForRecomposition(interfaceInitializedArgs: { interfaceName: string; isDefault: boolean }): void; + initialize(): void; + fetchMetadata(metadataStore: MetadataStore, dataService: DataService): breeze.promises.IPromise; + executeQuery(mappingContext: { getUrl: () => string; query: EntityQuery; dataService: DataService }): breeze.promises.IPromise; + saveChanges(saveContext: { resourceName: string; dataService: DataService }, saveBundle: Object): breeze.promises.IPromise; + JsonResultsAdapter: JsonResultsAdapter; + } + + export class JsonResultsAdapter { + name: string; + extractResults: (data: {}) => {}; + visitNode: (node: {}, queryContext: QueryContext, nodeContext: NodeContext) => { entityType?: EntityType; nodeId?: any; nodeRefId?: any; ignore?: boolean; }; + constructor(config: { + name: string; + extractResults?: (data: {}) => {}; + visitNode: (node: {}, queryContext: QueryContext, nodeContext: NodeContext) => { entityType?: EntityType; nodeId?: any; nodeRefId?: any; ignore?: boolean; }; + }); + } + + export interface QueryContext { + url: string; + query: EntityQuery | string; + entityManager: EntityManager; + dataService: DataService; + queryOptions: QueryOptions; + } + + export interface NodeContext { + nodeType: string; + } + + export class DataTypeSymbol extends breeze.core.EnumSymbol { + defaultValue: any; + isNumeric: boolean; + isDate: boolean; + } + export interface DataType extends breeze.core.IEnum { + Binary: DataTypeSymbol; + Boolean: DataTypeSymbol; + Byte: DataTypeSymbol; + DateTime: DataTypeSymbol; + DateTimeOffset: DataTypeSymbol; + Decimal: DataTypeSymbol; + Double: DataTypeSymbol; + Guid: DataTypeSymbol; + Int16: DataTypeSymbol; + Int32: DataTypeSymbol; + Int64: DataTypeSymbol; + Single: DataTypeSymbol; + String: DataTypeSymbol; + Time: DataTypeSymbol; + Undefined: DataTypeSymbol; + + toDataType(typeName: string): DataTypeSymbol; + parseDateFromServer(date: any): Date; + defaultValue: any; + isNumeric: boolean; + isInteger: boolean; + + /** Function to convert a value from string to this DataType. Note that this will be called each time a property is changed, so make it fast. */ + parse: (val: any, sourceTypeName: string) => any; + + /** Function to format this DataType for OData queries. */ + fmtOData: (val: any) => any; + + /** Optional function to get the next value for key generation, if this datatype is used as a key. Uses an internal table of previous values. */ + getNext?: () => any; + + /** Optional function to normalize a data value for comparison, if its value cannot be used directly. Note that this will be called each time a property is changed, so make it fast. */ + normalize?: (val: any) => any; + + /** Optional function to get the next value when the datatype is used as a concurrency property. */ + getConcurrencyValue?: (val: any) => any; + + /** Optional function to convert a raw (server) value from string to this DataType. */ + parseRawValue?: (val: any) => any; + } + export var DataType: DataType; + + export class EntityActionSymbol extends breeze.core.EnumSymbol { + } + export interface EntityAction extends breeze.core.IEnum { + AcceptChanges: EntityActionSymbol; + Attach: EntityActionSymbol; + AttachOnImport: EntityActionSymbol; + AttachOnQuery: EntityActionSymbol; + Clear: EntityActionSymbol; + Detach: EntityActionSymbol; + EntityStateChange: EntityActionSymbol; + MergeOnImport: EntityActionSymbol; + MergeOnSave: EntityActionSymbol; + MergeOnQuery: EntityActionSymbol; + PropertyChange: EntityActionSymbol; + RejectChanges: EntityActionSymbol; + } + export var EntityAction: EntityAction; + + export class EntityAspect { + entity: Entity; + entityManager: EntityManager; + entityState: EntityStateSymbol; + isBeingSaved: boolean; + originalValues: Object; + extraMetadata: Object; + + propertyChanged: PropertyChangedEvent; + validationErrorsChanged: ValidationErrorsChangedEvent; + + acceptChanges(): void; + addValidationError(validationError: ValidationError): void; + clearValidationErrors(): void; + getKey(forceRefresh?: boolean): EntityKey; + + getValidationErrors(): ValidationError[]; + getValidationErrors(property: string): ValidationError[]; + getValidationErrors(property: IProperty): ValidationError[]; + hasValidationErrors: boolean; + + isNavigationPropertyLoaded(navigationProperty: string): boolean; + isNavigationPropertyLoaded(navigationProperty: NavigationProperty): boolean; + + loadNavigationProperty(navigationProperty: string, callback?: Function, errorCallback?: Function): breeze.promises.IPromise; + loadNavigationProperty(navigationProperty: NavigationProperty, callback?: Function, errorCallback?: Function): breeze.promises.IPromise; + + rejectChanges(): void; + + removeValidationError(validator: Validator): void; + removeValidationError(validator: Validator, property: DataProperty): void; + removeValidationError(validator: Validator, property: NavigationProperty): void; + removeValidationError(validationError: ValidationError): void; + + setAdded(): void; + setDeleted(): void; + setDetached(): void; + setModified(): void; + setUnchanged(): void; + setEntityState(entityState: EntityStateSymbol): void; + validateEntity(): boolean; + + validateProperty(property: string, context?: any): boolean; + validateProperty(property: DataProperty, context?: any): boolean; + validateProperty(property: NavigationProperty, context?: any): boolean; + } + + export class PropertyChangedEventArgs { + entity: Entity; + property: IProperty; + propertyName: string; + oldValue: any; + newValue: any; + parent: any; + } + + export class PropertyChangedEvent extends breeze.core.Event { + subscribe(callback?: (data: PropertyChangedEventArgs) => void): number; + } + + export class ValidationErrorsChangedEventArgs { + entity: Entity; + added: ValidationError[]; + removed: ValidationError[]; + } + + export class ValidationErrorsChangedEvent extends breeze.core.Event { + subscribe(callback?: (data: ValidationErrorsChangedEventArgs) => void): number; + } + + export class EntityKey { + constructor(entityType: EntityType, keyValue: any); + constructor(entityType: EntityType, keyValues: any[]); + + equals(entityKey: EntityKey): boolean; + static equals(k1: EntityKey, k2: EntityKey): boolean; + entityType: EntityType; + values: any[]; + } + + export interface EntityByKeyResult { + entity: Entity; + entityKey: EntityKey; + fromCache: boolean; + } + export interface ExportEntitiesOptions { + asString: boolean; // default true + includeMetadata: boolean; // default true + } + + export class EntityManager { + dataService: DataService; + keyGeneratorCtor: Function; + metadataStore: MetadataStore; + queryOptions: QueryOptions; + saveOptions: SaveOptions; + serviceName: string; + validationOptions: ValidationOptions; + + entityChanged: EntityChangedEvent; + hasChangesChanged: HasChangesChangedEvent; + validationErrorsChanged: ValidationErrorsChangedEvent; + + constructor(config?: EntityManagerOptions); + constructor(config?: string); + + acceptChanges(): void; + addEntity(entity: Entity): Entity; + attachEntity(entity: Entity, entityState?: EntityStateSymbol, mergeStrategy?: MergeStrategySymbol): Entity; + clear(): void; + createEmptyCopy(): EntityManager; + createEntity(typeName: string, config?: {}, entityState?: EntityStateSymbol, mergeStrategy?: MergeStrategySymbol): Entity; + createEntity(entityType: EntityType, config?: {}, entityState?: EntityStateSymbol, mergeStrategy?: MergeStrategySymbol): Entity; + detachEntity(entity: Entity): boolean; + executeQuery(query: string, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): breeze.promises.IPromise; + executeQuery(query: EntityQuery, callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): breeze.promises.IPromise; + + executeQueryLocally(query: EntityQuery): Entity[]; + exportEntities(entities?: Entity[], includeMetadata?: boolean): string; + exportEntities(entities?: Entity[], options?: ExportEntitiesOptions): any; // string | Object + fetchEntityByKey(typeName: string, keyValue: any, checkLocalCacheFirst?: boolean): breeze.promises.IPromise; + fetchEntityByKey(typeName: string, keyValues: any[], checkLocalCacheFirst?: boolean): breeze.promises.IPromise; + fetchEntityByKey(entityKey: EntityKey): breeze.promises.IPromise; + fetchMetadata(callback?: (schema: any) => void, errorCallback?: breeze.core.ErrorCallback): breeze.promises.IPromise; + generateTempKeyValue(entity: Entity): any; + getChanges(): Entity[]; + getChanges(entityTypeName: string): Entity[]; + getChanges(entityTypeNames: string[]): Entity[]; + getChanges(entityType: EntityType): Entity[]; + getChanges(entityTypes: EntityType[]): Entity[]; + + getEntities(entityTypeName: string, entityState?: EntityStateSymbol): Entity[]; + getEntities(entityTypeNames?: string[], entityState?: EntityStateSymbol): Entity[]; + getEntities(entityTypeName?: string, entityStates?: EntityStateSymbol[]): Entity[]; + getEntities(entityTypeNames?: string[], entityStates?: EntityStateSymbol[]): Entity[]; + + getEntities(entityType: EntityType, entityState?: EntityStateSymbol): Entity[]; + getEntities(entityTypes?: EntityType[], entityState?: EntityStateSymbol): Entity[]; + getEntities(entityType?: EntityType, entityStates?: EntityStateSymbol[]): Entity[]; + getEntities(entityTypes?: EntityType[], entityStates?: EntityStateSymbol[]): Entity[]; + + getEntityByKey(typeName: string, keyValue: any): Entity; + getEntityByKey(typeName: string, keyValues: any[]): Entity; + getEntityByKey(entityKey: EntityKey): Entity; + + hasChanges(): boolean; + hasChanges(entityTypeName: string): boolean; + hasChanges(entityTypeNames: string[]): boolean; + hasChanges(entityType: EntityType): boolean; + hasChanges(entityTypes: EntityType[]): boolean; + + static importEntities(exportedString: string, config?: { mergeStrategy?: MergeStrategySymbol; metadataVersionFn?: (any: any) => void }): EntityManager; + static importEntities(exportedData: Object, config?: { mergeStrategy?: MergeStrategySymbol; metadataVersionFn?: (any: any) => void }): EntityManager; + importEntities(exportedString: string, config?: { mergeStrategy?: MergeStrategySymbol; metadataVersionFn?: (any: any) => void }): { entities: Entity[]; tempKeyMapping: { [key: string] : EntityKey } }; + importEntities(exportedData: Object, config?: { mergeStrategy?: MergeStrategySymbol; metadataVersionFn?: (any: any) => void }): { entities: Entity[]; tempKeyMapping: { [key: string]: EntityKey } }; + + rejectChanges(): Entity[]; + saveChanges(entities?: Entity[], saveOptions?: SaveOptions, callback?: SaveChangesSuccessCallback, errorCallback?: SaveChangesErrorCallback): breeze.promises.IPromise; + setProperties(config: EntityManagerProperties): void; + } + + export interface EntityManagerOptions { + serviceName?: string; + dataService?: DataService; + metadataStore?: MetadataStore; + queryOptions?: QueryOptions; + saveOptions?: SaveOptions; + validationOptions?: ValidationOptions; + keyGeneratorCtor?: Function; + } + + export interface EntityManagerProperties { + serviceName?: string; + dataService?: DataService; + metadataStore?: MetadataStore; + queryOptions?: QueryOptions; + saveOptions?: SaveOptions; + validationOptions?: ValidationOptions; + keyGeneratorCtor?: Function; + } + + export interface ExecuteQuerySuccessCallback { + (data: QueryResult): void; + } + + export interface ExecuteQueryErrorCallback { + (error: { query: EntityQuery; httpResponse: HttpResponse; entityManager: EntityManager; message?: string; stack?:string }): void; + } + + export interface SaveChangesSuccessCallback { + (saveResult: SaveResult): void; + } + + export interface EntityError { + entity: Entity; + errorMessage: string; + errorName: string; + isServerError: boolean; + propertyName: string; + } + + export interface SaveChangesErrorCallback { + (error: { + entityErrors: EntityError[]; + httpResponse: HttpResponse; + message: string; + stack?: string; + status?: number + }): void; + } + + export class EntityChangedEventArgs { + entity: Entity; + entityAction: EntityActionSymbol; + args: Object; + } + + export class EntityChangedEvent extends breeze.core.Event { + subscribe(callback?: (data: EntityChangedEventArgs) => void): number; + } + + export class HasChangesChangedEventArgs { + entityManager: EntityManager; + hasChanges: boolean; + } + + export class HasChangesChangedEvent extends breeze.core.Event { + subscribe(callback?: (data: HasChangesChangedEventArgs) => void): number; + } + + export class EntityQuery { + entityManager: EntityManager; + orderByClause: OrderByClause; + parameters: Object; + queryOptions: QueryOptions; + resourceName: string; + resultEntityType: EntityType; + skipCount: number; + takeCount: number; + wherePredicate: Predicate; + + constructor(resourceName?: string); + /** Create query from an expression tree */ + constructor(tree: Object); + + execute(callback?: ExecuteQuerySuccessCallback, errorCallback?: ExecuteQueryErrorCallback): breeze.promises.IPromise; + executeLocally(): Entity[]; + expand(propertyPaths: string[]): EntityQuery; + expand(propertyPaths: string): EntityQuery; + static from(resourceName: string): EntityQuery; + from(resourceName: string): EntityQuery; + static fromEntities(entity: Entity): EntityQuery; + static fromEntities(entities: Entity[]): EntityQuery; + static fromEntityKey(entityKey: EntityKey): EntityQuery; + static fromEntityNavigation(entity: Entity, navigationProperty: NavigationProperty): EntityQuery; + inlineCount(enabled?: boolean): EntityQuery; + noTracking(enabled?: boolean): EntityQuery; + orderBy(propertyPaths: string, isDescending?: boolean): EntityQuery; + orderBy(propertyPaths: string[], isDescending?: boolean): EntityQuery; + orderByDesc(propertyPaths: string): EntityQuery; + orderByDesc(propertyPaths: string[]): EntityQuery; + select(propertyPaths: string): EntityQuery; + select(propertyPaths: string[]): EntityQuery; + skip(count: number): EntityQuery; + take(count: number): EntityQuery; + top(count: number): EntityQuery; + toType(typeName: string): EntityQuery; + toType(type: EntityType): EntityQuery; + + using(obj: EntityManager): EntityQuery; + using(obj: DataService): EntityQuery; + using(obj: JsonResultsAdapter): EntityQuery; + using(obj: QueryOptions): EntityQuery; + using(obj: MergeStrategySymbol): EntityQuery; + using(obj: FetchStrategySymbol): EntityQuery; + + where(predicate: Predicate): EntityQuery; + where(property: string, operator: string, value: any): EntityQuery; + where(property: string, operator: FilterQueryOpSymbol, value: any): EntityQuery; + where(property: string, filterop: FilterQueryOpSymbol, property2: string, filterop2: FilterQueryOpSymbol, value: any): EntityQuery; // for any/all clauses + where(property: string, filterop: string, property2: string, filterop2: string, value: any): EntityQuery; // for any/all clauses + where(predicate: FilterQueryOpSymbol): EntityQuery; + withParameters(params: Object): EntityQuery; + + toJSON(): string; + } + + export interface OrderByClause { + } + + export class EntityStateSymbol extends breeze.core.EnumSymbol { + isAdded(): boolean; + isAddedModifiedOrDeleted(): boolean; + isDeleted(): boolean; + isDetached(): boolean; + isModified(): boolean; + isUnchanged(): boolean; + isUnchangedOrModified(): boolean; + } + export interface EntityState extends breeze.core.IEnum { + Added: EntityStateSymbol; + Deleted: EntityStateSymbol; + Detached: EntityStateSymbol; + Modified: EntityStateSymbol; + Unchanged: EntityStateSymbol; + } + export var EntityState: EntityState; + + export class EntityType implements IStructuralType { + autoGeneratedKeyType: AutoGeneratedKeyType; + baseEntityType: EntityType; + complexProperties: DataProperty[]; + concurrencyProperties: DataProperty[]; + dataProperties: DataProperty[]; + defaultResourceName: string; + foreignKeyProperties: DataProperty[]; + isAbstract: boolean; + keyProperties: DataProperty[]; + metadataStore: MetadataStore; + name: string; + namespace: string; + navigationProperties: NavigationProperty[]; + shortName: string; + unmappedProperties: DataProperty[]; + validators: Validator[]; + + constructor(config: MetadataStore); + constructor(config: EntityTypeOptions); + + addProperty(property: IProperty): void; + addValidator(validator: Validator, property?: IProperty): void; + createEntity(initialValues?: Object): Entity; + getCtor(): Function; + getDataProperty(propertyName: string): DataProperty; + getNavigationProperty(propertyName: string): NavigationProperty; + getProperties(): IProperty[]; + getProperty(propertyPath: string, throwIfNotFound?: boolean): IProperty; + getPropertyNames(): string[]; + getSelfAndSubtypes(): EntityType[]; + isSubtypeOf(entityType: EntityType): boolean; + setProperties(config: EntityTypeProperties): void; + toString(): string; + } + + export interface EntityTypeOptions { + shortName?: string; + namespace?: string; + autoGeneratedKeyType?: AutoGeneratedKeyType; + defaultResourceName?: string; + dataProperties?: DataProperty[]; + navigationProperties?: NavigationProperty[]; + } + + export interface EntityTypeProperties { + autoGeneratedKeyType?: AutoGeneratedKeyType; + defaultResourceName?: string; + serializerFn?: (dataProperty: DataProperty, value: any) => any; + } + + export class FetchStrategySymbol extends breeze.core.EnumSymbol { + private foo; // to distinguish this class from MergeStrategySymbol + } + export interface FetchStrategy extends breeze.core.IEnum { + FromLocalCache: FetchStrategySymbol; + FromServer: FetchStrategySymbol; + } + export var FetchStrategy: FetchStrategy; + + export class FilterQueryOpSymbol extends breeze.core.EnumSymbol { + } + export interface FilterQueryOp extends breeze.core.IEnum { + Contains: FilterQueryOpSymbol; + EndsWith: FilterQueryOpSymbol; + Equals: FilterQueryOpSymbol; + GreaterThan: FilterQueryOpSymbol; + GreaterThanOrEqual: FilterQueryOpSymbol; + IsTypeOf: FilterQueryOpSymbol; + LessThan: FilterQueryOpSymbol; + LessThanOrEqual: FilterQueryOpSymbol; + NotEquals: FilterQueryOpSymbol; + StartsWith: FilterQueryOpSymbol; + Any: FilterQueryOpSymbol; + All: FilterQueryOpSymbol; + } + export var FilterQueryOp: FilterQueryOp; + + export class LocalQueryComparisonOptions { + static caseInsensitiveSQL: LocalQueryComparisonOptions; + static defaultInstance: LocalQueryComparisonOptions; + + constructor(config: { name?: string; isCaseSensitive?: boolean; usesSql92CompliantStringComparison?: boolean; }); + + setAsDefault(): void; + } + + export class MergeStrategySymbol extends breeze.core.EnumSymbol { + } + export interface MergeStrategy extends breeze.core.IEnum { + OverwriteChanges: MergeStrategySymbol; + PreserveChanges: MergeStrategySymbol; + SkipMerge: MergeStrategySymbol; + Disallowed: MergeStrategySymbol; + } + export var MergeStrategy: MergeStrategy; + + export class MetadataStore { + constructor(); + constructor(config?: MetadataStoreOptions); + namingConvention: NamingConvention; + addDataService(dataService: DataService, shouldOverwrite?: boolean): void; + addEntityType(structuralType: IStructuralType): void; + exportMetadata(): string; + fetchMetadata(dataService: string, callback?: (data: any) => void, errorCallback?: breeze.core.ErrorCallback): breeze.promises.IPromise; + fetchMetadata(dataService: DataService, callback?: (data: any) => void, errorCallback?: breeze.core.ErrorCallback): breeze.promises.IPromise; + getDataService(serviceName: string): DataService; + getEntityType(entityTypeName: string, okIfNotFound?: boolean): IStructuralType; + getEntityTypes(): IStructuralType[]; + hasMetadataFor(serviceName: string): boolean; + static importMetadata(exportedString: string): MetadataStore; + importMetadata(exportedString: string, allowMerge?: boolean): MetadataStore; + isEmpty(): boolean; + registerEntityTypeCtor(entityTypeName: string, entityCtor: Function, initializationFn?: (entity: Entity) => void, noTrackingFn?: (node: Object, entityType: EntityType) => Object): void; + trackUnmappedType(entityCtor: Function, interceptor?: Function): void; + setEntityTypeForResourceName(resourceName: string, entityType: EntityType): void; + setEntityTypeForResourceName(resourceName: string, entityTypeName: string): void; + getEntityTypeNameForResourceName(resourceName: string): string; + setProperties(config: { name?: string; serializerFn?: Function }): void; + } + + export interface MetadataStoreOptions { + namingConvention?: NamingConvention; + localQueryComparisonOptions?: LocalQueryComparisonOptions; + } + + export class NamingConvention { + static camelCase: NamingConvention; + static defaultInstance: NamingConvention; + static none: NamingConvention; + + constructor(config: NamingConventionOptions); + + clientPropertyNameToServer(clientPropertyName: string): string; + clientPropertyNameToServer(clientPropertyName: string, property: IProperty): string; + + serverPropertyNameToClient(serverPropertyName: string): string; + serverPropertyNameToClient(serverPropertyName: string, property: IProperty): string; + + setAsDefault(): NamingConvention; + } + + export interface NamingConventionOptions { + serverPropertyNameToClient?: (name: string) => string; + clientPropertyNameToServer?: (name: string) => string; + } + + export class NavigationProperty implements IProperty { + associationName: string; + entityType: EntityType; + foreignKeyNames: string[]; + inverse: NavigationProperty; + isDataProperty: boolean; + isNavigationProperty: boolean; + isScalar: boolean; + name: string; + nameOnServer: string; + displayName: string; + parentType: IStructuralType; + relatedDataProperties: DataProperty[]; + validators: Validator[]; + + constructor(config: NavigationPropertyOptions); + } + + export interface NavigationPropertyOptions { + name?: string; + nameOnServer?: string; + entityTypeName: string; + isScalar?: boolean; + associationName?: string; + foreignKeyNames?: string[]; + foreignKeyNamesOnServer?: string[]; + validators?: Validator[]; + } + + export interface IRecursiveArray { + [i: number]: T | IRecursiveArray; + } + + export class Predicate { + constructor(); + constructor(property: string, operator: string, value: any); + constructor(property: string, operator: FilterQueryOpSymbol, value: any); + constructor(property: string, operator: string, value: { value: any; isLiteral?: boolean; dataType?: breeze.DataType }); + constructor(property: string, operator: FilterQueryOpSymbol, value: { value: any; isLiteral?: boolean; dataType?: breeze.DataType }); + constructor(property: string, filterop: FilterQueryOpSymbol, property2: string, filterop2: FilterQueryOpSymbol, value: any); // for any/all clauses + constructor(property: string, filterop: string, property2: string, filterop2: string, value: any); // for any/all clauses + constructor(passthru: string); + constructor(predicate: Predicate); + constructor(anArray: IRecursiveArray); + + and: PredicateMethod; + static and: PredicateMethod; + + static create: PredicateMethod; + + static isPredicate(o: any): boolean; + + static not(predicate: Predicate): Predicate; + not(): Predicate; + + static or: PredicateMethod; + or: PredicateMethod; + + toFunction(): Function; + toString(): string; + validate(entityType: EntityType): void; + + toJSON(): string; + } + + export interface PredicateMethod { + (predicates: Predicate[]): Predicate; + (...predicates: Predicate[]): Predicate; + (property: string, operator: string, value: any, valueIsLiteral?: boolean): Predicate; + (property: string, operator: FilterQueryOpSymbol, value: any, valueIsLiteral?: boolean): Predicate; + (property: string, filterop: FilterQueryOpSymbol, property2: string, filterop2: FilterQueryOpSymbol, value: any): Predicate; // for any/all clauses + (property: string, filterop: string, property2: string, filterop2: string, value: any): Predicate; // for any/all clauses + } + + export class QueryOptions { + static defaultInstance: QueryOptions; + fetchStrategy: FetchStrategySymbol; + mergeStrategy: MergeStrategySymbol; + /** Whether query should return cached deleted entities (false by default) */ + includeDeleted: boolean + + constructor(config?: QueryOptionsConfiguration); + + setAsDefault(): void; + using(config: QueryOptionsConfiguration): QueryOptions; + using(config: MergeStrategySymbol): QueryOptions; + using(config: FetchStrategySymbol): QueryOptions; + } + + export interface QueryOptionsConfiguration { + fetchStrategy?: FetchStrategySymbol; + mergeStrategy?: MergeStrategySymbol; + } + + export interface HttpResponse { + config: any; + data: Entity[]; + error?: any; + saveContext?: any; + status: number; + getHeaders(headerName: string): string + } + + export interface QueryResult { + /** Top level entities returned */ + results: Entity[]; + /** Query that was executed */ + query: EntityQuery; + /** Raw response from the server */ + httpResponse: HttpResponse; + /** EntityManager that executed the query */ + entityManager?: EntityManager; + /** Total number of results available on the server */ + inlineCount?: number; + /** All entities returned by the query. Differs from results when an expand is used. */ + retrievedEntities?: Entity[] + } + + export class SaveOptions { + allowConcurrentSaves: boolean; + resourceName: string; + dataService: DataService; + tag: Object; + static defaultInstance: SaveOptions; + + constructor(config?: { allowConcurrentSaves?: boolean; resourceName?: string; dataService?: DataService; tag?: any }); + + setAsDefault(): SaveOptions; + using(config: SaveOptionsConfiguration): SaveOptions; + } + + export interface SaveOptionsConfiguration { + allowConcurrentSaves?: boolean; + resourceName?: string; + dataService?: DataService; + tag?: Object; + } + + export interface SaveResult { + entities: Entity[]; + keyMappings: any; + XHR: XMLHttpRequest; + } + + export class ValidationError { + key: string; + context: any; + errorMessage: string; + property: IProperty; + propertyName: string; + validator: Validator; + getKey: (validator: Validator, property: string) => string; + + constructor(validator: Validator, context: any, errorMessage: string, key: string); + } + + export class ValidationOptions { + static defaultInstance: ValidationOptions; + validateOnAttach: boolean; + validateOnPropertyChange: boolean; + validateOnQuery: boolean; + validateOnSave: boolean; + + constructor(config?: ValidationOptionsConfiguration); + + setAsDefault(): ValidationOptions; + using(config: ValidationOptionsConfiguration): ValidationOptions; + } + + export interface ValidationOptionsConfiguration { + validateOnAttach?: boolean; + validateOnSave?: boolean; + validateOnQuery?: boolean; + validateOnPropertyChange?: boolean; + } + + export class Validator { + /** Map of standard error message templates keyed by validator name.*/ + static messageTemplates: any; + context: any; + name: string; + + constructor(name: string, validatorFn: ValidatorFunction, context?: any); + + static bool(): Validator; + /** integer between 0 and 255 inclusive */ + static byte(context?: { messageTemplate?: string }): Validator; + static date(): Validator; + /** Returns a ISO 8601 duration string Validator. */ + static duration(): Validator; + /** Validators number, double, and single are all the same */ + static number(context?: { messageTemplate?: string }): Validator; + /** Validators number, double, and single are all the same */ + static double(context?: { messageTemplate?: string }): Validator; + /** Validators number, double, and single are all the same */ + static single(context?: { messageTemplate?: string }): Validator; + + static guid(): Validator; + static int16(context?: { messageTemplate?: string }): Validator; + static int32(context?: { messageTemplate?: string }): Validator; + static int64(context?: { messageTemplate?: string }): Validator; + /** Same as int64 */ + static integer(context?: { messageTemplate?: string }): Validator; + static maxLength(context: { maxLength: number; messageTemplate?: string }): Validator; + static required(context?: { messageTemplate?: string }): Validator; + static string(): Validator; + static stringLength(context: { maxLength: number; minLength: number; messageTemplate?: string }): Validator; + /** Returns a credit card number validator that performs a Luhn algorithm checksum test for plausability */ + static creditCard(context?: { messageTemplate?: string }): Validator; + /** Returns a regular expression validator; the expression must be specified in the context parameter */ + static regularExpression(context: { expression: RegExp; messageTemplate?: string }): Validator; + /** Returns the email address validator */ + static emailAddress(context?: { messageTemplate?: string }): Validator; + /** Returns the phone validator, which handles prefix, country code, area code, and local number, with [-/. ] break characters. */ + static phone(context?: { messageTemplate?: string }): Validator; + /** Returns the URL (protocol required) validator */ + static url(context?: { messageTemplate?: string }): Validator; + /** Always returns true */ + static none(): Validator; + + /** Creates a validator instance from a JSON object or an array of instances from an array of JSON objects. */ + static fromJSON(json: string): Validator; + /** Register a validator instance so that any deserialized metadata can reference it. */ + static register(validator: Validator): void; + /** Register a validator factory so that any deserialized metadata can reference it. */ + static registerFactory(fn: () => Validator, name: string): void; + /** Creates a regular expression validator with a fixed expression. */ + static makeRegExpValidator(validatorName: string, expression: RegExp, defaultMessage: string, context?: any): Validator; + + /** Run this validator against the specified value. + @param value {Object} Value to validate + @param additionalContext {Object} Any additional contextual information that the Validator can make use of. + @return {ValidationError|null} A ValidationError if validation fails, null otherwise */ + validate(value: any, context?: any): ValidationError; + + /** Returns the message generated by the most recent execution of this Validator. */ + getMessage(): string; + } + + export interface ValidatorFunction { + (value: any, context: ValidatorFunctionContext): void; + } + + export interface ValidatorFunctionContext { + value: any; + validatorName: string; + displayName: string; + messageTemplate: string; + message?: string; + } + + export var metadataVersion: string; + export var remoteAccess_odata: string; + export var remoteAccess_webApi: string; + export var version: string; + +} + +declare namespace breeze.config { + + export var ajax: string; + export var dataService: string; + export var functionRegistry: Object; + /** + Returns the ctor function used to implement a specific interface with a specific adapter name. + @param interfaceName {String} One of the following interface names "ajax", "dataService" or "modelLibrary" + @param adapterName {String} The name of any previously registered adapter. If this parameter is omitted then + this method returns the "default" adapter for this interface. If there is no default adapter, then a null is returned. + @returns {Function|null} Returns either a ctor function or null. + **/ + export function getAdapter(interfaceName: string, adapterName?: string): Function; + /** + Returns the adapter instance corresponding to the specified interface and adapter names. + @param interfaceName {String} The name of the interface. + @param adapterName {String} - The name of a previously registered adapter. If this parameter is + omitted then the default implementation of the specified interface is returned. If there is + no defaultInstance of this interface, then the first registered instance of this interface is returned. + @return {an instance of the specified adapter} + **/ + export function getAdapterInstance(interfaceName: string, adapterName?: string): Object; + /** + Initializes a single adapter implementation. Initialization means either newing a instance of the + specified interface and then calling "initialize" on it or simply calling "initialize" on the instance + if it already exists. + @param interfaceName {String} The name of the interface to which the adapter to initialize belongs. + @param adapterName {String} - The name of a previously registered adapter to initialize. + @param isDefault=true {Boolean} - Whether to make this the default "adapter" for this interface. + @return {an instance of the specified adapter} + **/ + export function initializeAdapterInstance(interfaceName: string, adapterName: string, isDefault?: boolean): Adapter; + + // TODO This is added later on / coni2k - 05 Jul. '16 + export interface Adapter { + getRoutePrefix: Function + } + + export interface AdapterInstancesConfig { + /** the name of a previously registered "ajax" adapter */ + ajax?: string; + /** the name of a previously registered "dataService" adapter */ + dataService?: string; + /** the name of a previously registered "modelLibrary" adapter */ + modelLibary?: string; + /** the name of a previously registered "uriBuilder" adapter */ + uriBuilder?: string; + } + /** + Initializes a collection of adapter implementations and makes each one the default for its corresponding interface. + @param config {AdapterInstancesConfig} + @return [array of instances] + **/ + export function initializeAdapterInstances(config: AdapterInstancesConfig): Object[]; + export var interfaceInitialized: Event; + export var interfaceRegistry: Object; + export var objectRegistry: Object; + /** + Method use to register implementations of standard breeze interfaces. Calls to this method are usually + made as the last step within an adapter implementation. + @param interfaceName {String} - one of the following interface names "ajax", "dataService" or "modelLibrary" + @param adapterCtor {Function} - an ctor function that returns an instance of the specified interface. + **/ + export function registerAdapter(interfaceName: string, adapterCtor: Function): void; + export function registerFunction(fn: Function, fnName: string): void; + export function registerType(ctor: Function, typeName: string): void; + //static setProperties(config: Object): void; //deprecated + /** + Set the promise implementation, if Q.js is not found. + @param q - implementation of promise. @see http://wiki.commonjs.org/wiki/Promises/A + */ + export function setQ(q: breeze.promises.IPromiseService): void; + export var stringifyPad: string; + export var typeRegistry: Object; + +} + +/** Promises interface used by Breeze. Usually implemented by Q (https://github.com/kriskowal/q) or angular.$q using breeze.config.setQ(impl) */ +declare namespace breeze.promises { + + export interface IPromise { + then(onFulfill: (value: T) => U, onReject?: (reason: any) => U): IPromise; + then(onFulfill: (value: T) => IPromise, onReject?: (reason: any) => U): IPromise; + then(onFulfill: (value: T) => U, onReject?: (reason: any) => IPromise): IPromise; + then(onFulfill: (value: T) => IPromise, onReject?: (reason: any) => IPromise): IPromise; + catch(onRejected: (reason: any) => U): IPromise; + catch(onRejected: (reason: any) => IPromise): IPromise; + finally(finallyCallback: () => any): IPromise; + } + + export interface IDeferred { + promise: IPromise; + resolve(value: T): void; + reject(reason: any): void; + } + + export interface IPromiseService { + defer(): IDeferred; + reject(reason?: any): IPromise; + resolve(object: T): IPromise; + resolve(object: IPromise): IPromise; + } +} + +declare module "breeze" { + export = breeze; +} diff --git a/ngClient/_system/js/lib/jquery/jquery.d.ts b/ngClient/_system/js/lib/jquery/jquery.d.ts new file mode 100644 index 000000000..5dc88bf79 --- /dev/null +++ b/ngClient/_system/js/lib/jquery/jquery.d.ts @@ -0,0 +1,3239 @@ +// Type definitions for jQuery 1.10.x / 2.0.x +// Project: http://jquery.com/ +// Definitions by: Boris Yankov , Christian Hoffmeister , Steve Fenton , Diullei Gomes , Tass Iliopoulos , Jason Swearingen , Sean Hill , Guus Goossens , Kelly Summerlin , Basarat Ali Syed , Nicholas Wolverson , Derek Cicerone , Andrew Gaspar , James Harrison Fisher , Seikichi Kondo , Benjamin Jackman , Poul Sorensen , Josh Strobl , John Reilly , Dick van den Brink +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/* ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + +/** + * Interface for the AJAX setting that will configure the AJAX request + */ +interface JQueryAjaxSettings { + /** + * The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. + */ + accepts?: any; + /** + * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success(). + */ + async?: boolean; + /** + * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. + */ + beforeSend? (jqXHR: JQueryXHR, settings: JQueryAjaxSettings): any; + /** + * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. + */ + cache?: boolean; + /** + * A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. + */ + complete? (jqXHR: JQueryXHR, textStatus: string): any; + /** + * An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5) + */ + contents?: { [key: string]: any; }; + //According to jQuery.ajax source code, ajax's option actually allows contentType to set to "false" + // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/742 + /** + * When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. + */ + contentType?: any; + /** + * This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). + */ + context?: any; + /** + * An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5) + */ + converters?: { [key: string]: any; }; + /** + * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5) + */ + crossDomain?: boolean; + /** + * Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). + */ + data?: any; + /** + * A function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. + */ + dataFilter? (data: any, ty: any): any; + /** + * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). + */ + dataType?: string; + /** + * A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. + */ + error? (jqXHR: JQueryXHR, textStatus: string, errorThrown: string): any; + /** + * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. + */ + global?: boolean; + /** + * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5) + */ + headers?: { [key: string]: any; }; + /** + * Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. + */ + ifModified?: boolean; + /** + * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1) + */ + isLocal?: boolean; + /** + * Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" } + */ + jsonp?: any; + /** + * Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. + */ + jsonpCallback?: any; + /** + * The HTTP method to use for the request (e.g. "POST", "GET", "PUT"). (version added: 1.9.0) + */ + method?: string; + /** + * A mime type to override the XHR mime type. (version added: 1.5.1) + */ + mimeType?: string; + /** + * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. + */ + password?: string; + /** + * By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. + */ + processData?: boolean; + /** + * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. + */ + scriptCharset?: string; + /** + * An object of numeric HTTP codes and functions to be called when the response has the corresponding code. f the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. (version added: 1.5) + */ + statusCode?: { [key: string]: any; }; + /** + * A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. + */ + success? (data: any, textStatus: string, jqXHR: JQueryXHR): any; + /** + * Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period. + */ + timeout?: number; + /** + * Set this to true if you wish to use the traditional style of param serialization. + */ + traditional?: boolean; + /** + * The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers. + */ + type?: string; + /** + * A string containing the URL to which the request is sent. + */ + url?: string; + /** + * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. + */ + username?: string; + /** + * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory. + */ + xhr?: any; + /** + * An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed. In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it. (version added: 1.5.1) + */ + xhrFields?: { [key: string]: any; }; +} + +/** + * Interface for the jqXHR object + */ +interface JQueryXHR extends XMLHttpRequest, JQueryPromise { + /** + * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). + */ + overrideMimeType(mimeType: string): any; + /** + * Cancel the request. + * + * @param statusText A string passed as the textStatus parameter for the done callback. Default value: "canceled" + */ + abort(statusText?: string): void; + /** + * Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details. + */ + then(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => R, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise; + /** + * Property containing the parsed response if the response Content-Type is json + */ + responseJSON?: any; + /** + * A function to be called if the request fails. + */ + error(xhr: JQueryXHR, textStatus: string, errorThrown: string): void; +} + +/** + * Interface for the JQuery callback + */ +interface JQueryCallback { + /** + * Add a callback or a collection of callbacks to a callback list. + * + * @param callbacks A function, or array of functions, that are to be added to the callback list. + */ + add(callbacks: Function): JQueryCallback; + /** + * Add a callback or a collection of callbacks to a callback list. + * + * @param callbacks A function, or array of functions, that are to be added to the callback list. + */ + add(callbacks: Function[]): JQueryCallback; + + /** + * Disable a callback list from doing anything more. + */ + disable(): JQueryCallback; + + /** + * Determine if the callbacks list has been disabled. + */ + disabled(): boolean; + + /** + * Remove all of the callbacks from a list. + */ + empty(): JQueryCallback; + + /** + * Call all of the callbacks with the given arguments + * + * @param arguments The argument or list of arguments to pass back to the callback list. + */ + fire(...arguments: any[]): JQueryCallback; + + /** + * Determine if the callbacks have already been called at least once. + */ + fired(): boolean; + + /** + * Call all callbacks in a list with the given context and arguments. + * + * @param context A reference to the context in which the callbacks in the list should be fired. + * @param arguments An argument, or array of arguments, to pass to the callbacks in the list. + */ + fireWith(context?: any, args?: any[]): JQueryCallback; + + /** + * Determine whether a supplied callback is in a list + * + * @param callback The callback to search for. + */ + has(callback: Function): boolean; + + /** + * Lock a callback list in its current state. + */ + lock(): JQueryCallback; + + /** + * Determine if the callbacks list has been locked. + */ + locked(): boolean; + + /** + * Remove a callback or a collection of callbacks from a callback list. + * + * @param callbacks A function, or array of functions, that are to be removed from the callback list. + */ + remove(callbacks: Function): JQueryCallback; + /** + * Remove a callback or a collection of callbacks from a callback list. + * + * @param callbacks A function, or array of functions, that are to be removed from the callback list. + */ + remove(callbacks: Function[]): JQueryCallback; +} + +/** + * Allows jQuery Promises to interop with non-jQuery promises + */ +interface JQueryGenericPromise { + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + */ + then(doneFilter: (value?: T, ...values: any[]) => U|JQueryPromise, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; + + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + */ + then(doneFilter: (value?: T, ...values: any[]) => void, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise; +} + +/** + * Interface for the JQuery promise/deferred callbacks + */ +interface JQueryPromiseCallback { + (value?: T, ...args: any[]): void; +} + +interface JQueryPromiseOperator { + (callback1: JQueryPromiseCallback|JQueryPromiseCallback[], ...callbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; +} + +/** + * Interface for the JQuery promise, part of callbacks + */ +interface JQueryPromise extends JQueryGenericPromise { + /** + * Determine the current state of a Deferred object. + */ + state(): string; + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * + * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. + * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. + */ + always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is resolved. + * + * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. + * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. + */ + done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. + * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. + */ + fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * + * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. + */ + progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; + + // Deprecated - given no typings + pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; +} + +/** + * Interface for the JQuery deferred, part of callbacks + */ +interface JQueryDeferred extends JQueryGenericPromise { + /** + * Determine the current state of a Deferred object. + */ + state(): string; + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * + * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. + * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. + */ + always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is resolved. + * + * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. + * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. + */ + done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. + * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. + */ + fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * + * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. + */ + progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; + + /** + * Call the progressCallbacks on a Deferred object with the given args. + * + * @param args Optional arguments that are passed to the progressCallbacks. + */ + notify(value?: any, ...args: any[]): JQueryDeferred; + + /** + * Call the progressCallbacks on a Deferred object with the given context and args. + * + * @param context Context passed to the progressCallbacks as the this object. + * @param args Optional arguments that are passed to the progressCallbacks. + */ + notifyWith(context: any, value?: any[]): JQueryDeferred; + + /** + * Reject a Deferred object and call any failCallbacks with the given args. + * + * @param args Optional arguments that are passed to the failCallbacks. + */ + reject(value?: any, ...args: any[]): JQueryDeferred; + /** + * Reject a Deferred object and call any failCallbacks with the given context and args. + * + * @param context Context passed to the failCallbacks as the this object. + * @param args An optional array of arguments that are passed to the failCallbacks. + */ + rejectWith(context: any, value?: any[]): JQueryDeferred; + + /** + * Resolve a Deferred object and call any doneCallbacks with the given args. + * + * @param value First argument passed to doneCallbacks. + * @param args Optional subsequent arguments that are passed to the doneCallbacks. + */ + resolve(value?: T, ...args: any[]): JQueryDeferred; + + /** + * Resolve a Deferred object and call any doneCallbacks with the given context and args. + * + * @param context Context passed to the doneCallbacks as the this object. + * @param args An optional array of arguments that are passed to the doneCallbacks. + */ + resolveWith(context: any, value?: T[]): JQueryDeferred; + + /** + * Return a Deferred's Promise object. + * + * @param target Object onto which the promise methods have to be attached + */ + promise(target?: any): JQueryPromise; + + // Deprecated - given no typings + pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise; +} + +/** + * Interface of the JQuery extension of the W3C event object + */ +interface BaseJQueryEventObject extends Event { + data: any; + delegateTarget: Element; + isDefaultPrevented(): boolean; + isImmediatePropagationStopped(): boolean; + isPropagationStopped(): boolean; + namespace: string; + originalEvent: Event; + preventDefault(): any; + relatedTarget: Element; + result: any; + stopImmediatePropagation(): void; + stopPropagation(): void; + target: Element; + pageX: number; + pageY: number; + which: number; + metaKey: boolean; +} + +interface JQueryInputEventObject extends BaseJQueryEventObject { + altKey: boolean; + ctrlKey: boolean; + metaKey: boolean; + shiftKey: boolean; +} + +interface JQueryMouseEventObject extends JQueryInputEventObject { + button: number; + clientX: number; + clientY: number; + offsetX: number; + offsetY: number; + pageX: number; + pageY: number; + screenX: number; + screenY: number; +} + +interface JQueryKeyEventObject extends JQueryInputEventObject { + char: any; + charCode: number; + key: any; + keyCode: number; +} + +interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject{ +} + +/* + Collection of properties of the current browser +*/ + +interface JQuerySupport { + ajax?: boolean; + boxModel?: boolean; + changeBubbles?: boolean; + checkClone?: boolean; + checkOn?: boolean; + cors?: boolean; + cssFloat?: boolean; + hrefNormalized?: boolean; + htmlSerialize?: boolean; + leadingWhitespace?: boolean; + noCloneChecked?: boolean; + noCloneEvent?: boolean; + opacity?: boolean; + optDisabled?: boolean; + optSelected?: boolean; + scriptEval? (): boolean; + style?: boolean; + submitBubbles?: boolean; + tbody?: boolean; +} + +interface JQueryParam { + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + * + * @param obj An array or object to serialize. + */ + (obj: any): string; + + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + * + * @param obj An array or object to serialize. + * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. + */ + (obj: any, traditional: boolean): string; +} + +/** + * The interface used to construct jQuery events (with $.Event). It is + * defined separately instead of inline in JQueryStatic to allow + * overriding the construction function with specific strings + * returning specific event objects. + */ +interface JQueryEventConstructor { + (name: string, eventProperties?: any): JQueryEventObject; + new (name: string, eventProperties?: any): JQueryEventObject; +} + +/** + * The interface used to specify coordinates. + */ +interface JQueryCoordinates { + left: number; + top: number; +} + +/** + * Elements in the array returned by serializeArray() + */ +interface JQuerySerializeArrayElement { + name: string; + value: string; +} + +interface JQueryAnimationOptions { + /** + * A string or number determining how long the animation will run. + */ + duration?: any; + /** + * A string indicating which easing function to use for the transition. + */ + easing?: string; + /** + * A function to call once the animation is complete. + */ + complete?: Function; + /** + * A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set. + */ + step?: (now: number, tween: any) => any; + /** + * A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties. (version added: 1.8) + */ + progress?: (animation: JQueryPromise, progress: number, remainingMs: number) => any; + /** + * A function to call when the animation begins. (version added: 1.8) + */ + start?: (animation: JQueryPromise) => any; + /** + * A function to be called when the animation completes (its Promise object is resolved). (version added: 1.8) + */ + done?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + /** + * A function to be called when the animation fails to complete (its Promise object is rejected). (version added: 1.8) + */ + fail?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + /** + * A function to be called when the animation completes or stops without completing (its Promise object is either resolved or rejected). (version added: 1.8) + */ + always?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + /** + * A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it. + */ + queue?: any; + /** + * A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions. (version added: 1.4) + */ + specialEasing?: Object; +} + +interface JQueryEasingFunction { + ( percent: number ): number; +} + +interface JQueryEasingFunctions { + [ name: string ]: JQueryEasingFunction; + linear: JQueryEasingFunction; + swing: JQueryEasingFunction; +} + +/** + * Static members of jQuery (those on $ and jQuery themselves) + */ +interface JQueryStatic { + + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). + */ + ajax(settings: JQueryAjaxSettings): JQueryXHR; + /** + * Perform an asynchronous HTTP (Ajax) request. + * + * @param url A string containing the URL to which the request is sent. + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup(). + */ + ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR; + + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * + * @param dataTypes An optional string containing one or more space-separated dataTypes + * @param handler A handler to set default values for future Ajax requests. + */ + ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * + * @param handler A handler to set default values for future Ajax requests. + */ + ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void; + + ajaxSettings: JQueryAjaxSettings; + + /** + * Set default values for future Ajax requests. Its use is not recommended. + * + * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. + */ + ajaxSetup(options: JQueryAjaxSettings): void; + + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). + */ + get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP GET request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). + */ + get(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP GET request. + * + * @param settings The JQueryAjaxSettings to be used for the request + */ + get(settings : JQueryAjaxSettings): JQueryXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + */ + getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + */ + getJSON(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + /** + * Load a JavaScript file from the server using a GET HTTP request, then execute it. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + */ + getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR; + + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + */ + param: JQueryParam; + + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + */ + post(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP POST request. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + */ + post(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR; + /** + * Load data from the server using a HTTP POST request. + * + * @param settings The JQueryAjaxSettings to be used for the request + */ + post(settings : JQueryAjaxSettings): JQueryXHR; + /** + * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. + * + * @param flags An optional list of space-separated flags that change how the callback list behaves. + */ + Callbacks(flags?: string): JQueryCallback; + + /** + * Holds or releases the execution of jQuery's ready event. + * + * @param hold Indicates whether the ready hold is being requested or released + */ + holdReady(hold: boolean): void; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param selector A string containing a selector expression + * @param context A DOM Element, Document, or jQuery to use as context + */ + (selector: string, context?: Element|JQuery): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param element A DOM element to wrap in a jQuery object. + */ + (element: Element): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object. + */ + (elementArray: Element[]): JQuery; + + /** + * Binds a function to be executed when the DOM has finished loading. + * + * @param callback A function to execute after the DOM is ready. + */ + (callback: (jQueryAlias?: JQueryStatic) => any): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param object A plain object to wrap in a jQuery object. + */ + (object: {}): JQuery; + + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * + * @param object An existing jQuery object to clone. + */ + (object: JQuery): JQuery; + + /** + * Specify a function to execute when the DOM is fully loaded. + */ + (): JQuery; + + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. + * @param ownerDocument A document in which the new elements will be created. + */ + (html: string, ownerDocument?: Document): JQuery; + + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * + * @param html A string defining a single, standalone, HTML element (e.g.
or
). + * @param attributes An object of attributes, events, and methods to call on the newly-created element. + */ + (html: string, attributes: Object): JQuery; + + /** + * Relinquish jQuery's control of the $ variable. + * + * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). + */ + noConflict(removeAll?: boolean): JQueryStatic; + + /** + * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. + * + * @param deferreds One or more Deferred objects, or plain JavaScript objects. + */ + when(...deferreds: Array/* as JQueryDeferred */>): JQueryPromise; + + /** + * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties. + */ + cssHooks: { [key: string]: any; }; + cssNumber: any; + + /** + * Store arbitrary data associated with the specified element. Returns the value that was set. + * + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + * @param value The new data value. + */ + data(element: Element, key: string, value: T): T; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. + * + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + */ + data(element: Element, key: string): any; + /** + * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element. + * + * @param element The DOM element to associate with the data. + */ + data(element: Element): any; + + /** + * Execute the next function on the queue for the matched element. + * + * @param element A DOM element from which to remove and execute a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + dequeue(element: Element, queueName?: string): void; + + /** + * Determine whether an element has any jQuery data associated with it. + * + * @param element A DOM element to be checked for data. + */ + hasData(element: Element): boolean; + + /** + * Show the queue of functions to be executed on the matched element. + * + * @param element A DOM element to inspect for an attached queue. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + queue(element: Element, queueName?: string): any[]; + /** + * Manipulate the queue of functions to be executed on the matched element. + * + * @param element A DOM element where the array of queued functions is attached. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(element: Element, queueName: string, newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed on the matched element. + * + * @param element A DOM element on which to add a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param callback The new function to add to the queue. + */ + queue(element: Element, queueName: string, callback: Function): JQuery; + + /** + * Remove a previously-stored piece of data. + * + * @param element A DOM element from which to remove data. + * @param name A string naming the piece of data to remove. + */ + removeData(element: Element, name?: string): JQuery; + + /** + * A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. + * + * @param beforeStart A function that is called just before the constructor returns. + */ + Deferred(beforeStart?: (deferred: JQueryDeferred) => any): JQueryDeferred; + + /** + * Effects + */ + + easing: JQueryEasingFunctions; + + fx: { + tick: () => void; + /** + * The rate (in milliseconds) at which animations fire. + */ + interval: number; + stop: () => void; + speeds: { slow: number; fast: number; }; + /** + * Globally disable all animations. + */ + off: boolean; + step: any; + }; + + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param fnction The function whose context will be changed. + * @param context The object to which the context (this) of the function should be set. + * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. + */ + proxy(fnction: (...args: any[]) => any, context: Object, ...additionalArguments: any[]): any; + /** + * Takes a function and returns a new one that will always have a particular context. + * + * @param context The object to which the context (this) of the function should be set. + * @param name The name of the function whose context will be changed (should be a property of the context object). + * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. + */ + proxy(context: Object, name: string, ...additionalArguments: any[]): any; + + Event: JQueryEventConstructor; + + /** + * Takes a string and throws an exception containing it. + * + * @param message The message to send out. + */ + error(message: any): JQuery; + + expr: any; + fn: any; //TODO: Decide how we want to type this + + isReady: boolean; + + // Properties + support: JQuerySupport; + + /** + * Check to see if a DOM element is a descendant of another DOM element. + * + * @param container The DOM element that may contain the other element. + * @param contained The DOM element that may be contained by (a descendant of) the other element. + */ + contains(container: Element, contained: Element): boolean; + + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: T[], + callback: (indexInArray: number, valueOfElement: T) => any + ): any; + + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * + * @param collection The object or array to iterate over. + * @param callback The function that will be executed on every object. + */ + each( + collection: any, + callback: (indexInArray: any, valueOfElement: any) => any + ): any; + + /** + * Merge the contents of two or more objects together into the first object. + * + * @param target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(target: any, object1?: any, ...objectN: any[]): any; + /** + * Merge the contents of two or more objects together into the first object. + * + * @param deep If true, the merge becomes recursive (aka. deep copy). + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + */ + extend(deep: boolean, target: any, object1?: any, ...objectN: any[]): any; + + /** + * Execute some JavaScript code globally. + * + * @param code The JavaScript code to execute. + */ + globalEval(code: string): any; + + /** + * Finds the elements of an array which satisfy a filter function. The original array is not affected. + * + * @param array The array to search through. + * @param func The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value. this will be the global window object. + * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements for which "callback" returns true. If "invert" is true, then the function returns an array consisting of all elements for which "callback" returns false. + */ + grep(array: T[], func: (elementOfArray?: T, indexInArray?: number) => boolean, invert?: boolean): T[]; + + /** + * Search for a specified value within an array and return its index (or -1 if not found). + * + * @param value The value to search for. + * @param array An array through which to search. + * @param fromIndex he index of the array at which to begin the search. The default is 0, which will search the whole array. + */ + inArray(value: T, array: T[], fromIndex?: number): number; + + /** + * Determine whether the argument is an array. + * + * @param obj Object to test whether or not it is an array. + */ + isArray(obj: any): boolean; + /** + * Check to see if an object is empty (contains no enumerable properties). + * + * @param obj The object that will be checked to see if it's empty. + */ + isEmptyObject(obj: any): boolean; + /** + * Determine if the argument passed is a Javascript function object. + * + * @param obj Object to test whether or not it is a function. + */ + isFunction(obj: any): boolean; + /** + * Determines whether its argument is a number. + * + * @param obj The value to be tested. + */ + isNumeric(value: any): boolean; + /** + * Check to see if an object is a plain object (created using "{}" or "new Object"). + * + * @param obj The object that will be checked to see if it's a plain object. + */ + isPlainObject(obj: any): boolean; + /** + * Determine whether the argument is a window. + * + * @param obj Object to test whether or not it is a window. + */ + isWindow(obj: any): boolean; + /** + * Check to see if a DOM node is within an XML document (or is an XML document). + * + * @param node he DOM node that will be checked to see if it's in an XML document. + */ + isXMLDoc(node: Node): boolean; + + /** + * Convert an array-like object into a true JavaScript array. + * + * @param obj Any object to turn into a native Array. + */ + makeArray(obj: any): any[]; + + /** + * Translate all items in an array or object to new array of items. + * + * @param array The Array to translate. + * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. + */ + map(array: T[], callback: (elementOfArray?: T, indexInArray?: number) => U): U[]; + /** + * Translate all items in an array or object to new array of items. + * + * @param arrayOrObject The Array or Object to translate. + * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. + */ + map(arrayOrObject: any, callback: (value?: any, indexOrKey?: any) => any): any; + + /** + * Merge the contents of two arrays together into the first array. + * + * @param first The first array to merge, the elements of second added. + * @param second The second array to merge into the first, unaltered. + */ + merge(first: T[], second: T[]): T[]; + + /** + * An empty function. + */ + noop(): any; + + /** + * Return a number representing the current time. + */ + now(): number; + + /** + * Takes a well-formed JSON string and returns the resulting JavaScript object. + * + * @param json The JSON string to parse. + */ + parseJSON(json: string): any; + + /** + * Parses a string into an XML document. + * + * @param data a well-formed XML string to be parsed + */ + parseXML(data: string): XMLDocument; + + /** + * Remove the whitespace from the beginning and end of a string. + * + * @param str Remove the whitespace from the beginning and end of a string. + */ + trim(str: string): string; + + /** + * Determine the internal JavaScript [[Class]] of an object. + * + * @param obj Object to get the internal JavaScript [[Class]] of. + */ + type(obj: any): string; + + /** + * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. + * + * @param array The Array of DOM elements. + */ + unique(array: Element[]): Element[]; + + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context DOM element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + */ + parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[]; + + /** + * Parses a string into an array of DOM nodes. + * + * @param data HTML string to be parsed + * @param context DOM element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + */ + parseHTML(data: string, context?: Document, keepScripts?: boolean): any[]; +} + +/** + * The jQuery instance members + */ +interface JQuery { + /** + * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. + * + * @param handler The function to be invoked. + */ + ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery; + /** + * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxError(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxSettings: JQueryAjaxSettings, thrownError: any) => any): JQuery; + /** + * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxSend(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxOptions: JQueryAjaxSettings) => any): JQuery; + /** + * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxStart(handler: () => any): JQuery; + /** + * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxStop(handler: () => any): JQuery; + /** + * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. + * + * @param handler The function to be invoked. + */ + ajaxSuccess(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: JQueryAjaxSettings) => any): JQuery; + + /** + * Load data from the server and place the returned HTML into the matched element. + * + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param complete A callback function that is executed when the request completes. + */ + load(url: string, data?: string|Object, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): JQuery; + + /** + * Encode a set of form elements as a string for submission. + */ + serialize(): string; + /** + * Encode a set of form elements as an array of names and values. + */ + serializeArray(): JQuerySerializeArrayElement[]; + + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param className One or more space-separated classes to be added to the class attribute of each matched element. + */ + addClass(className: string): JQuery; + /** + * Adds the specified class(es) to each of the set of matched elements. + * + * @param function A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set. + */ + addClass(func: (index: number, className: string) => string): JQuery; + + /** + * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. + */ + addBack(selector?: string): JQuery; + + /** + * Get the value of an attribute for the first element in the set of matched elements. + * + * @param attributeName The name of the attribute to get. + */ + attr(attributeName: string): string; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributeName The name of the attribute to set. + * @param value A value to set for the attribute. + */ + attr(attributeName: string, value: string|number): JQuery; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributeName The name of the attribute to set. + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments. + */ + attr(attributeName: string, func: (index: number, attr: string) => string|number): JQuery; + /** + * Set one or more attributes for the set of matched elements. + * + * @param attributes An object of attribute-value pairs to set. + */ + attr(attributes: Object): JQuery; + + /** + * Determine whether any of the matched elements are assigned the given class. + * + * @param className The class name to search for. + */ + hasClass(className: string): boolean; + + /** + * Get the HTML contents of the first element in the set of matched elements. + */ + html(): string; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param htmlString A string of HTML to set as the content of each matched element. + */ + html(htmlString: string): JQuery; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. + */ + html(func: (index: number, oldhtml: string) => string): JQuery; + /** + * Set the HTML contents of each element in the set of matched elements. + * + * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. + */ + + /** + * Get the value of a property for the first element in the set of matched elements. + * + * @param propertyName The name of the property to get. + */ + prop(propertyName: string): any; + /** + * Set one or more properties for the set of matched elements. + * + * @param propertyName The name of the property to set. + * @param value A value to set for the property. + */ + prop(propertyName: string, value: string|number|boolean): JQuery; + /** + * Set one or more properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + */ + prop(properties: Object): JQuery; + /** + * Set one or more properties for the set of matched elements. + * + * @param propertyName The name of the property to set. + * @param func A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element. + */ + prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): JQuery; + + /** + * Remove an attribute from each element in the set of matched elements. + * + * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. + */ + removeAttr(attributeName: string): JQuery; + + /** + * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. + * + * @param className One or more space-separated classes to be removed from the class attribute of each matched element. + */ + removeClass(className?: string): JQuery; + /** + * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. + * + * @param function A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments. + */ + removeClass(func: (index: number, className: string) => string): JQuery; + + /** + * Remove a property for the set of matched elements. + * + * @param propertyName The name of the property to remove. + */ + removeProp(propertyName: string): JQuery; + + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. + * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. + */ + toggleClass(className: string, swtch?: boolean): JQuery; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param swtch A boolean value to determine whether the class should be added or removed. + */ + toggleClass(swtch?: boolean): JQuery; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument. + * + * @param func A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments. + * @param swtch A boolean value to determine whether the class should be added or removed. + */ + toggleClass(func: (index: number, className: string, swtch: boolean) => string, swtch?: boolean): JQuery; + + /** + * Get the current value of the first element in the set of matched elements. + */ + val(): any; + /** + * Set the value of each element in the set of matched elements. + * + * @param value A string of text, an array of strings or number corresponding to the value of each matched element to set as selected/checked. + */ + val(value: string|string[]|number): JQuery; + /** + * Set the value of each element in the set of matched elements. + * + * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + val(func: (index: number, value: string) => string): JQuery; + + + /** + * Get the value of style properties for the first element in the set of matched elements. + * + * @param propertyName A CSS property. + */ + css(propertyName: string): string; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param propertyName A CSS property name. + * @param value A value to set for the property. + */ + css(propertyName: string, value: string|number): JQuery; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param propertyName A CSS property name. + * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments. + */ + css(propertyName: string, value: (index: number, value: string) => string|number): JQuery; + /** + * Set one or more CSS properties for the set of matched elements. + * + * @param properties An object of property-value pairs to set. + */ + css(properties: Object): JQuery; + + /** + * Get the current computed height for the first element in the set of matched elements. + */ + height(): number; + /** + * Set the CSS height of every matched element. + * + * @param value An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string). + */ + height(value: number|string): JQuery; + /** + * Set the CSS height of every matched element. + * + * @param func A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set. + */ + height(func: (index: number, height: number) => number|string): JQuery; + + /** + * Get the current computed height for the first element in the set of matched elements, including padding but not border. + */ + innerHeight(): number; + + /** + * Sets the inner height on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerHeight(height: number|string): JQuery; + + /** + * Get the current computed width for the first element in the set of matched elements, including padding but not border. + */ + innerWidth(): number; + + /** + * Sets the inner width on elements in the set of matched elements, including padding but not border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + innerWidth(width: number|string): JQuery; + + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the document. + */ + offset(): JQueryCoordinates; + /** + * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + * + * @param coordinates An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + */ + offset(coordinates: JQueryCoordinates): JQuery; + /** + * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements. + * + * @param func A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties. + */ + offset(func: (index: number, coords: JQueryCoordinates) => JQueryCoordinates): JQuery; + + /** + * Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without "px") representation of the value or null if called on an empty set of elements. + * + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + */ + outerHeight(includeMargin?: boolean): number; + + /** + * Sets the outer height on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerHeight(height: number|string): JQuery; + + /** + * Get the current computed width for the first element in the set of matched elements, including padding and border. + * + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + */ + outerWidth(includeMargin?: boolean): number; + + /** + * Sets the outer width on elements in the set of matched elements, including padding and border. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + outerWidth(width: number|string): JQuery; + + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. + */ + position(): JQueryCoordinates; + + /** + * Get the current horizontal position of the scroll bar for the first element in the set of matched elements or set the horizontal position of the scroll bar for every matched element. + */ + scrollLeft(): number; + /** + * Set the current horizontal position of the scroll bar for each of the set of matched elements. + * + * @param value An integer indicating the new position to set the scroll bar to. + */ + scrollLeft(value: number): JQuery; + + /** + * Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. + */ + scrollTop(): number; + /** + * Set the current vertical position of the scroll bar for each of the set of matched elements. + * + * @param value An integer indicating the new position to set the scroll bar to. + */ + scrollTop(value: number): JQuery; + + /** + * Get the current computed width for the first element in the set of matched elements. + */ + width(): number; + /** + * Set the CSS width of each element in the set of matched elements. + * + * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). + */ + width(value: number|string): JQuery; + /** + * Set the CSS width of each element in the set of matched elements. + * + * @param func A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set. + */ + width(func: (index: number, width: number) => number|string): JQuery; + + /** + * Remove from the queue all items that have not yet been run. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + clearQueue(queueName?: string): JQuery; + + /** + * Store arbitrary data associated with the matched elements. + * + * @param key A string naming the piece of data to set. + * @param value The new data value; it can be any Javascript type including Array or Object. + */ + data(key: string, value: any): JQuery; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + * + * @param key Name of the data stored. + */ + data(key: string): any; + /** + * Store arbitrary data associated with the matched elements. + * + * @param obj An object of key-value pairs of data to update. + */ + data(obj: { [key: string]: any; }): JQuery; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + */ + data(): any; + + /** + * Execute the next function on the queue for the matched elements. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + dequeue(queueName?: string): JQuery; + + /** + * Remove a previously-stored piece of data. + * + * @param name A string naming the piece of data to delete or space-separated string naming the pieces of data to delete. + */ + removeData(name: string): JQuery; + /** + * Remove a previously-stored piece of data. + * + * @param list An array of strings naming the pieces of data to delete. + */ + removeData(list: string[]): JQuery; + /** + * Remove all previously-stored piece of data. + */ + removeData(): JQuery; + + /** + * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. + * + * @param type The type of queue that needs to be observed. (default: fx) + * @param target Object onto which the promise methods have to be attached + */ + promise(type?: string, target?: Object): JQueryPromise; + + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + animate(properties: Object, duration?: string|number, complete?: Function): JQuery; + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. (default: swing) + * @param complete A function to call once the animation is complete. + */ + animate(properties: Object, duration?: string|number, easing?: string, complete?: Function): JQuery; + /** + * Perform a custom animation of a set of CSS properties. + * + * @param properties An object of CSS properties and values that the animation will move toward. + * @param options A map of additional options to pass to the method. + */ + animate(properties: Object, options: JQueryAnimationOptions): JQuery; + + /** + * Set a timer to delay execution of subsequent items in the queue. + * + * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + delay(duration: number, queueName?: string): JQuery; + + /** + * Display the matched elements by fading them to opaque. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeIn(duration?: number|string, complete?: Function): JQuery; + /** + * Display the matched elements by fading them to opaque. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeIn(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display the matched elements by fading them to opaque. + * + * @param options A map of additional options to pass to the method. + */ + fadeIn(options: JQueryAnimationOptions): JQuery; + + /** + * Hide the matched elements by fading them to transparent. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeOut(duration?: number|string, complete?: Function): JQuery; + /** + * Hide the matched elements by fading them to transparent. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeOut(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Hide the matched elements by fading them to transparent. + * + * @param options A map of additional options to pass to the method. + */ + fadeOut(options: JQueryAnimationOptions): JQuery; + + /** + * Adjust the opacity of the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param complete A function to call once the animation is complete. + */ + fadeTo(duration: string|number, opacity: number, complete?: Function): JQuery; + /** + * Adjust the opacity of the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeTo(duration: string|number, opacity: number, easing?: string, complete?: Function): JQuery; + + /** + * Display or hide the matched elements by animating their opacity. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + fadeToggle(duration?: number|string, complete?: Function): JQuery; + /** + * Display or hide the matched elements by animating their opacity. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + fadeToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display or hide the matched elements by animating their opacity. + * + * @param options A map of additional options to pass to the method. + */ + fadeToggle(options: JQueryAnimationOptions): JQuery; + + /** + * Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. + * + * @param queue The name of the queue in which to stop animations. + */ + finish(queue?: string): JQuery; + + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + hide(duration?: number|string, complete?: Function): JQuery; + /** + * Hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + hide(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Hide the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + hide(options: JQueryAnimationOptions): JQuery; + + /** + * Display the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + show(duration?: number|string, complete?: Function): JQuery; + /** + * Display the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + show(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + show(options: JQueryAnimationOptions): JQuery; + + /** + * Display the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideDown(duration?: number|string, complete?: Function): JQuery; + /** + * Display the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideDown(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideDown(options: JQueryAnimationOptions): JQuery; + + /** + * Display or hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideToggle(duration?: number|string, complete?: Function): JQuery; + /** + * Display or hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideToggle(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display or hide the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideToggle(options: JQueryAnimationOptions): JQuery; + + /** + * Hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + slideUp(duration?: number|string, complete?: Function): JQuery; + /** + * Hide the matched elements with a sliding motion. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + slideUp(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Hide the matched elements with a sliding motion. + * + * @param options A map of additional options to pass to the method. + */ + slideUp(options: JQueryAnimationOptions): JQuery; + + /** + * Stop the currently-running animation on the matched elements. + * + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + */ + stop(clearQueue?: boolean, jumpToEnd?: boolean): JQuery; + /** + * Stop the currently-running animation on the matched elements. + * + * @param queue The name of the queue in which to stop animations. + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + */ + stop(queue?: string, clearQueue?: boolean, jumpToEnd?: boolean): JQuery; + + /** + * Display or hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete. + */ + toggle(duration?: number|string, complete?: Function): JQuery; + /** + * Display or hide the matched elements. + * + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete. + */ + toggle(duration?: number|string, easing?: string, complete?: Function): JQuery; + /** + * Display or hide the matched elements. + * + * @param options A map of additional options to pass to the method. + */ + toggle(options: JQueryAnimationOptions): JQuery; + /** + * Display or hide the matched elements. + * + * @param showOrHide A Boolean indicating whether to show or hide the elements. + */ + toggle(showOrHide: boolean): JQuery; + + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute each time the event is triggered. + */ + bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ + bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. + * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. + */ + bind(eventType: string, preventBubble: boolean): JQuery; + /** + * Attach a handler to an event for the elements. + * + * @param events An object containing one or more DOM event types and functions to execute for them. + */ + bind(events: any): JQuery; + + /** + * Trigger the "blur" event on an element + */ + blur(): JQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + blur(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "blur" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "change" event on an element. + */ + change(): JQuery; + /** + * Bind an event handler to the "change" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + change(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "change" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "click" event on an element. + */ + click(): JQuery; + /** + * Bind an event handler to the "click" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + */ + click(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "click" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "contextmenu" event on an element. + */ + contextmenu(): JQuery; + /** + * Bind an event handler to the "contextmenu" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + contextmenu(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "contextmenu" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + contextmenu(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "dblclick" event on an element. + */ + dblclick(): JQuery; + /** + * Bind an event handler to the "dblclick" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + dblclick(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "dblclick" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + delegate(selector: any, eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "focus" event on an element. + */ + focus(): JQuery; + /** + * Bind an event handler to the "focus" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focus(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "focus" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "focusin" event on an element. + */ + focusin(): JQuery; + /** + * Bind an event handler to the "focusin" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focusin(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "focusin" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focusin(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "focusout" event on an element. + */ + focusout(): JQuery; + /** + * Bind an event handler to the "focusout" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + focusout(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "focusout" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + focusout(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. + * + * @param handlerIn A function to execute when the mouse pointer enters the element. + * @param handlerOut A function to execute when the mouse pointer leaves the element. + */ + hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. + * + * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + */ + hover(handlerInOut: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "keydown" event on an element. + */ + keydown(): JQuery; + /** + * Bind an event handler to the "keydown" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keydown(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; + /** + * Bind an event handler to the "keydown" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keydown(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; + + /** + * Trigger the "keypress" event on an element. + */ + keypress(): JQuery; + /** + * Bind an event handler to the "keypress" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keypress(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; + /** + * Bind an event handler to the "keypress" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keypress(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; + + /** + * Trigger the "keyup" event on an element. + */ + keyup(): JQuery; + /** + * Bind an event handler to the "keyup" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + keyup(handler: (eventObject: JQueryKeyEventObject) => any): JQuery; + /** + * Bind an event handler to the "keyup" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + keyup(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery; + + /** + * Bind an event handler to the "load" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + load(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "load" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "mousedown" event on an element. + */ + mousedown(): JQuery; + /** + * Bind an event handler to the "mousedown" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mousedown(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mousedown" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mousedown(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseenter" event on an element. + */ + mouseenter(): JQuery; + /** + * Bind an event handler to be fired when the mouse enters an element. + * + * @param handler A function to execute when the event is triggered. + */ + mouseenter(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to be fired when the mouse enters an element. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseenter(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseleave" event on an element. + */ + mouseleave(): JQuery; + /** + * Bind an event handler to be fired when the mouse leaves an element. + * + * @param handler A function to execute when the event is triggered. + */ + mouseleave(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to be fired when the mouse leaves an element. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseleave(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mousemove" event on an element. + */ + mousemove(): JQuery; + /** + * Bind an event handler to the "mousemove" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mousemove(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mousemove" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mousemove(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseout" event on an element. + */ + mouseout(): JQuery; + /** + * Bind an event handler to the "mouseout" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseout(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mouseout" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseout(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseover" event on an element. + */ + mouseover(): JQuery; + /** + * Bind an event handler to the "mouseover" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseover(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mouseover" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseover(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Trigger the "mouseup" event on an element. + */ + mouseup(): JQuery; + /** + * Bind an event handler to the "mouseup" JavaScript event. + * + * @param handler A function to execute when the event is triggered. + */ + mouseup(handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + /** + * Bind an event handler to the "mouseup" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + mouseup(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery; + + /** + * Remove an event handler. + */ + off(): JQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param handler A handler function previously attached for the event(s), or the special value false. Takes handler with extra args that can be attached with on(). + */ + off(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + /** + * Remove an event handler. + * + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". + * @param handler A handler function previously attached for the event(s), or the special value false. + */ + off(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove an event handler. + * + * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s). + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + */ + off(events: { [key: string]: any; }, selector?: string): JQuery; + + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax). + */ + on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, data : any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + on(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; + /** + * Attach an event handler function for one or more events to the selected elements. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + on(events: { [key: string]: any; }, data?: any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param handler A function to execute at the time the event is triggered. + */ + one(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. + * @param data An object containing data that will be passed to the event handler. + * @param handler A function to execute at the time the event is triggered. + */ + one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. + */ + one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + one(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; + + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * + * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). + * @param data Data to be passed to the handler in event.data when an event occurs. + */ + one(events: { [key: string]: any; }, data?: any): JQuery; + + + /** + * Specify a function to execute when the DOM is fully loaded. + * + * @param handler A function to execute after the DOM is ready. + */ + ready(handler: (jQueryAlias?: JQueryStatic) => any): JQuery; + + /** + * Trigger the "resize" event on an element. + */ + resize(): JQuery; + /** + * Bind an event handler to the "resize" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + resize(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "resize" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + resize(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "scroll" event on an element. + */ + scroll(): JQuery; + /** + * Bind an event handler to the "scroll" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + scroll(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "scroll" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + scroll(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "select" event on an element. + */ + select(): JQuery; + /** + * Bind an event handler to the "select" JavaScript event. + * + * @param handler A function to execute each time the event is triggered. + */ + select(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "select" JavaScript event. + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + select(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Trigger the "submit" event on an element. + */ + submit(): JQuery; + /** + * Bind an event handler to the "submit" JavaScript event + * + * @param handler A function to execute each time the event is triggered. + */ + submit(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "submit" JavaScript event + * + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + */ + submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(eventType: string, extraParameters?: any[]|Object): JQuery; + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * + * @param event A jQuery.Event object. + * @param extraParameters Additional parameters to pass along to the event handler. + */ + trigger(event: JQueryEventObject, extraParameters?: any[]|Object): JQuery; + + /** + * Execute all handlers attached to an element for an event. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param extraParameters An array of additional parameters to pass along to the event handler. + */ + triggerHandler(eventType: string, ...extraParameters: any[]): Object; + + /** + * Execute all handlers attached to an element for an event. + * + * @param event A jQuery.Event object. + * @param extraParameters An array of additional parameters to pass along to the event handler. + */ + triggerHandler(event: JQueryEventObject, ...extraParameters: any[]): Object; + + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param handler The function that is to be no longer executed. + */ + unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param eventType A string containing a JavaScript event type, such as click or submit. + * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). + */ + unbind(eventType: string, fls: boolean): JQuery; + /** + * Remove a previously-attached event handler from the elements. + * + * @param evt A JavaScript event object as passed to an event handler. + */ + unbind(evt: any): JQuery; + + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + */ + undelegate(): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" + * @param handler A function to execute at the time the event is triggered. + */ + undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param selector A selector which will be used to filter the event results. + * @param events An object of one or more event types and previously bound functions to unbind from them. + */ + undelegate(selector: string, events: Object): JQuery; + /** + * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. + * + * @param namespace A string containing a namespace to unbind all events from. + */ + undelegate(namespace: string): JQuery; + + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ + unload(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document. (DEPRECATED from v1.10) + */ + context: Element; + + jquery: string; + + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param handler A function to execute when the event is triggered. + */ + error(handler: (eventObject: JQueryEventObject) => any): JQuery; + /** + * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) + * + * @param eventData A plain object of data that will be passed to the event handler. + * @param handler A function to execute when the event is triggered. + */ + error(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; + + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + */ + pushStack(elements: any[]): JQuery; + /** + * Add a collection of DOM elements onto the jQuery stack. + * + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + * @param name The name of a jQuery method that generated the array of elements. + * @param arguments The arguments that were passed in to the jQuery method (for serialization). + */ + pushStack(elements: any[], name: string, arguments: any[]): JQuery; + + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param content1 HTML string, DOM element, DocumentFragment, array of elements, or jQuery object to insert after each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. + */ + after(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + after(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param content1 DOM element, DocumentFragment, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. + */ + append(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + append(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Insert every element in the set of matched elements to the end of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. + */ + appendTo(target: JQuery|any[]|Element|string): JQuery; + + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param content1 HTML string, DOM element, DocumentFragment, array of elements, or jQuery object to insert before each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. + */ + before(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + before(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Create a deep copy of the set of matched elements. + * + * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. + * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). + */ + clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery; + + /** + * Remove the set of matched elements from the DOM. + * + * param selector A selector expression that filters the set of matched elements to be removed. + */ + detach(selector?: string): JQuery; + + /** + * Remove all child nodes of the set of matched elements from the DOM. + */ + empty(): JQuery; + + /** + * Insert every element in the set of matched elements after the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. + */ + insertAfter(target: JQuery|any[]|Element|Text|string): JQuery; + + /** + * Insert every element in the set of matched elements before the target. + * + * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. + */ + insertBefore(target: JQuery|any[]|Element|Text|string): JQuery; + + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param content1 DOM element, DocumentFragment, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. + * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. + */ + prepend(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * + * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. + */ + prepend(func: (index: number, html: string) => string|Element|JQuery): JQuery; + + /** + * Insert every element in the set of matched elements to the beginning of the target. + * + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. + */ + prependTo(target: JQuery|any[]|Element|string): JQuery; + + /** + * Remove the set of matched elements from the DOM. + * + * @param selector A selector expression that filters the set of matched elements to be removed. + */ + remove(selector?: string): JQuery; + + /** + * Replace each target element with the set of matched elements. + * + * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. + */ + replaceAll(target: JQuery|any[]|Element|string): JQuery; + + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. + */ + replaceWith(newContent: JQuery|any[]|Element|Text|string): JQuery; + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * + * param func A function that returns content with which to replace the set of matched elements. + */ + replaceWith(func: () => Element|JQuery): JQuery; + + /** + * Get the combined text contents of each element in the set of matched elements, including their descendants. + */ + text(): string; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. + */ + text(text: string|number|boolean): JQuery; + /** + * Set the content of each element in the set of matched elements to the specified text. + * + * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. + */ + text(func: (index: number, text: string) => string): JQuery; + + /** + * Retrieve all the elements contained in the jQuery set, as an array. + */ + toArray(): any[]; + + /** + * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. + */ + unwrap(): JQuery; + + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrap(wrappingElement: JQuery|Element|string): JQuery; + /** + * Wrap an HTML structure around each element in the set of matched elements. + * + * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrap(func: (index: number) => string|JQuery): JQuery; + + /** + * Wrap an HTML structure around all elements in the set of matched elements. + * + * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. + */ + wrapAll(wrappingElement: JQuery|Element|string): JQuery; + wrapAll(func: (index: number) => string): JQuery; + + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. + */ + wrapInner(wrappingElement: JQuery|Element|string): JQuery; + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * + * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. + */ + wrapInner(func: (index: number) => string): JQuery; + + /** + * Iterate over a jQuery object, executing a function for each matched element. + * + * @param func A function to execute for each matched element. + */ + each(func: (index: number, elem: Element) => any): JQuery; + + /** + * Retrieve one of the elements matched by the jQuery object. + * + * @param index A zero-based integer indicating which element to retrieve. + */ + get(index: number): HTMLElement; + /** + * Retrieve the elements matched by the jQuery object. + */ + get(): any[]; + + /** + * Search for a given element from among the matched elements. + */ + index(): number; + /** + * Search for a given element from among the matched elements. + * + * @param selector A selector representing a jQuery collection in which to look for an element. + */ + index(selector: string|JQuery|Element): number; + + /** + * The number of elements in the jQuery object. + */ + length: number; + /** + * A selector representing selector passed to jQuery(), if any, when creating the original set. + * version deprecated: 1.7, removed: 1.9 + */ + selector: string; + [index: string]: any; + [index: number]: HTMLElement; + + /** + * Add elements to the set of matched elements. + * + * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. + * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. + */ + add(selector: string, context?: Element): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param elements One or more elements to add to the set of matched elements. + */ + add(...elements: Element[]): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param html An HTML fragment to add to the set of matched elements. + */ + add(html: string): JQuery; + /** + * Add elements to the set of matched elements. + * + * @param obj An existing jQuery object to add to the set of matched elements. + */ + add(obj: JQuery): JQuery; + + /** + * Get the children of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + children(selector?: string): JQuery; + + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + */ + closest(selector: string): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param selector A string containing a selector expression to match elements against. + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ + closest(selector: string, context?: Element): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param obj A jQuery object to match elements against. + */ + closest(obj: JQuery): JQuery; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * + * @param element An element to match elements against. + */ + closest(element: Element): JQuery; + + /** + * Get an array of all the elements and selectors matched against the current element up through the DOM tree. + * + * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object). + * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. + */ + closest(selectors: any, context?: Element): any[]; + + /** + * Get the children of each element in the set of matched elements, including text and comment nodes. + */ + contents(): JQuery; + + /** + * End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. + */ + end(): JQuery; + + /** + * Reduce the set of matched elements to the one at the specified index. + * + * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set. + * + */ + eq(index: number): JQuery; + + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param selector A string containing a selector expression to match the current set of elements against. + */ + filter(selector: string): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + filter(func: (index: number, element: Element) => any): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param element An element to match the current set of elements against. + */ + filter(element: Element): JQuery; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + filter(obj: JQuery): JQuery; + + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param selector A string containing a selector expression to match elements against. + */ + find(selector: string): JQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param element An element to match elements against. + */ + find(element: Element): JQuery; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * + * @param obj A jQuery object to match elements against. + */ + find(obj: JQuery): JQuery; + + /** + * Reduce the set of matched elements to the first in the set. + */ + first(): JQuery; + + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param selector A string containing a selector expression to match elements against. + */ + has(selector: string): JQuery; + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * + * @param contained A DOM element to match elements against. + */ + has(contained: Element): JQuery; + + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param selector A string containing a selector expression to match elements against. + */ + is(selector: string): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. + */ + is(func: (index: number, element: Element) => boolean): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + is(obj: JQuery): boolean; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * + * @param elements One or more elements to match the current set of elements against. + */ + is(elements: any): boolean; + + /** + * Reduce the set of matched elements to the final one in the set. + */ + last(): JQuery; + + /** + * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. + * + * @param callback A function object that will be invoked for each element in the current set. + */ + map(callback: (index: number, domElement: Element) => any): JQuery; + + /** + * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + next(selector?: string): JQuery; + + /** + * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + nextAll(selector?: string): JQuery; + + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(selector?: string, filter?: string): JQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(element?: Element, filter?: string): JQuery; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * + * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + nextUntil(obj?: JQuery, filter?: string): JQuery; + + /** + * Remove elements from the set of matched elements. + * + * @param selector A string containing a selector expression to match elements against. + */ + not(selector: string): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param func A function used as a test for each element in the set. this is the current DOM element. + */ + not(func: (index: number, element: Element) => boolean): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param elements One or more DOM elements to remove from the matched set. + */ + not(elements: Element|Element[]): JQuery; + /** + * Remove elements from the set of matched elements. + * + * @param obj An existing jQuery object to match the current set of elements against. + */ + not(obj: JQuery): JQuery; + + /** + * Get the closest ancestor element that is positioned. + */ + offsetParent(): JQuery; + + /** + * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + parent(selector?: string): JQuery; + + /** + * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + parents(selector?: string): JQuery; + + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(selector?: string, filter?: string): JQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(element?: Element, filter?: string): JQuery; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + */ + parentsUntil(obj?: JQuery, filter?: string): JQuery; + + /** + * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + prev(selector?: string): JQuery; + + /** + * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + prevAll(selector?: string): JQuery; + + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(selector?: string, filter?: string): JQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(element?: Element, filter?: string): JQuery; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * + * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + */ + prevUntil(obj?: JQuery, filter?: string): JQuery; + + /** + * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. + * + * @param selector A string containing a selector expression to match elements against. + */ + siblings(selector?: string): JQuery; + + /** + * Reduce the set of matched elements to a subset specified by a range of indices. + * + * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. + * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. + */ + slice(start: number, end?: number): JQuery; + + /** + * Show the queue of functions to be executed on the matched elements. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + */ + queue(queueName?: string): any[]; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(callback: Function): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue An array of functions to replace the current queue contents. + */ + queue(queueName: string, newQueue: Function[]): JQuery; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. + */ + queue(queueName: string, callback: Function): JQuery; +} +declare module "jquery" { + export = $; +} +declare var jQuery: JQueryStatic; +declare var $: JQueryStatic; diff --git a/ngClient/_system/js/lib/toastr/toastr.d.ts b/ngClient/_system/js/lib/toastr/toastr.d.ts new file mode 100644 index 000000000..e921bfbd7 --- /dev/null +++ b/ngClient/_system/js/lib/toastr/toastr.d.ts @@ -0,0 +1,214 @@ +// Type definitions for Toastr 2.1.1 +// Project: https://github.com/CodeSeven/toastr +// Definitions by: Boris Yankov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// + +interface ToastrOptions { + /** + * Optionally override the animation easing to show or hide the toasts. Default is swing. swing and linear are built into jQuery. + */ + showEasing?: string; + /** + * Optionally override the animation easing to show or hide the toasts. Default is swing. swing and linear are built into jQuery. + */ + hideEasing?: string; + /** + * Use the jQuery show/hide method of your choice. These default to fadeIn/fadeOut. The methods fadeIn/fadeOut, slideDown/slideUp, and show/hide are built into jQuery. + */ + showMethod?: string; + /** + * Use the jQuery show/hide method of your choice. These default to fadeIn/fadeOut. The methods fadeIn/fadeOut, slideDown/slideUp, and show/hide are built into jQuery. + */ + hideMethod?: string; + /** + * Should a close button be shown + */ + closeButton?: boolean; + /** + * Html for the close button + */ + closeHtml?: string; + /** + * Should clicking on toast dismiss it? + */ + tapToDismiss?: boolean; + /** + * CSS class the toast element will be given + */ + toastClass?: string; + /** + * Id toast container will be given + */ + containerId?: string; + /** + * Should debug details be outputted to the console + */ + debug?: boolean; + /** + * Time in milliseconds the toast should take to show + */ + showDuration?: number; + /** + * onShown function callback + **/ + onShown?: () => void; + /** + * Time in milliseconds the toast should take to hide + */ + hideDuration?: number; + /** + * onHidden function callback + **/ + onHidden?: () => void; + /** + * Time in milliseconds the toast should be displayed after mouse over + */ + extendedTimeOut?: number; + iconClasses?: { + /** + * Icon to use on error toasts + */ + error: string; + /** + * Icon to use on info toasts + */ + info: string; + /** + * Icon to use on success toasts + */ + success: string; + /** + * Icon to use on warning toasts + */ + warning: string; + }; + /** + * Icon to use for toast + */ + iconClass?: string; + /** + * Where toast should be displayed + */ + positionClass?: string; + /** + * Where toast should be displayed - background + */ + backgroundpositionClass?: string; + /** + * Time in milliseconds that the toast should be displayed + */ + timeOut?: number; + /** + * CSS class the title element will be given + */ + titleClass?: string; + /** + * CSS class the message element will be given + */ + messageClass?: string; + /** + * Set newest toast to appear on top + **/ + newestOnTop?: boolean; + /** + * The element to put the toastr container + **/ + target?: string; + /** + * Rather than having identical toasts stack, set the preventDuplicates property to true. Duplicates are matched to the previous toast based on their message content. + */ + preventDuplicates?: boolean; + /** + * Visually indicates how long before a toast expires. + */ + progressBar?: boolean; + /** + * Function to execute on toast click + */ + onclick?: () => void; + /** + * Set if toastr should parse containing html + **/ + allowHtml?: boolean; +} + +interface ToastrDisplayMethod { + /** + * Create a toast + * + * @param message Message to display in toast + */ + (message: string): JQuery; + /** + * Create a toast + * + * @param message Message to display in toast + * @param title Title to display on toast + */ + (message: string, title: string): JQuery; + /** + * Create a toast + * + * @param message Message to display in toast + * @param title Title to display on toast + * @param overrides Option values for toast + */ + (message: string, title: string, overrides: ToastrOptions): JQuery; +} + +interface Toastr { + /** + * Clear toasts + */ + clear: { + /** + * Clear all toasts + */ + (): void; + /** + * Clear specific toast + * + * @param toast Toast to clear + */ + (toast: JQuery): void; + /** + * Clear specific toast + * + * @param toast Toast to clear + * @param clearOptions force clearing a toast, ignoring focus + */ + (toast: JQuery, clearOptions: { force: boolean }): void; + }; + /** + * Create an error toast + */ + error: ToastrDisplayMethod; + /** + * Create an info toast + */ + info: ToastrDisplayMethod; + /** + * Create an options object + */ + options: ToastrOptions; + /** + * Create a success toast + */ + success: ToastrDisplayMethod; + /** + * Create a warning toast + */ + warning: ToastrDisplayMethod; + /** + * Get toastr version + */ + version: string; +} + +declare var toastr: Toastr; +declare module "toastr" { + export = toastr; +} diff --git a/ngClient/_system/js/tsconfig.json b/ngClient/_system/js/tsconfig.json new file mode 100644 index 000000000..7b330fd2e --- /dev/null +++ b/ngClient/_system/js/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "noImplicitAny": false, + "noEmitOnError": true, + "removeComments": true, + "target": "es5" + }, + "exclude": [ + "./appSettings", + "./lib" + ] +} diff --git a/ngClient/_system/views/account/changeEmail.html b/ngClient/_system/views/account/changeEmail.html index 1d5648a52..89d90aa28 100644 --- a/ngClient/_system/views/account/changeEmail.html +++ b/ngClient/_system/views/account/changeEmail.html @@ -1,4 +1,4 @@ -
+

Change Email

diff --git a/ngClient/_system/views/content/contributors.html b/ngClient/_system/views/content/contributors.html index a59877416..2884c4d6b 100644 --- a/ngClient/_system/views/content/contributors.html +++ b/ngClient/_system/views/content/contributors.html @@ -192,29 +192,6 @@

- - - Shai Aharoni - InternetBird - - Software Developer - .NET, Javascript - 5+ - -
    -
  • - -
  • -
  • - -
  • -
- - - - - -

diff --git a/ngClient/_system/views/resourcePool/resourcePoolManage.html b/ngClient/_system/views/resourcePool/resourcePoolManage.html index a4aae2edf..396be3af0 100644 --- a/ngClient/_system/views/resourcePool/resourcePoolManage.html +++ b/ngClient/_system/views/resourcePool/resourcePoolManage.html @@ -282,7 +282,7 @@

- + diff --git a/ngClient/default.aspx b/ngClient/default.aspx index 1a4db26d6..6a5bdef18 100644 --- a/ngClient/default.aspx +++ b/ngClient/default.aspx @@ -129,7 +129,7 @@ - + diff --git a/ngClient/gulpfile.js b/ngClient/gulpfile.js index 3dc1c5114..34b70a76c 100644 --- a/ngClient/gulpfile.js +++ b/ngClient/gulpfile.js @@ -2,35 +2,37 @@ 'use strict'; var gulp = require('gulp'), - clean = require('gulp-clean'), concat = require('gulp-concat'), cssmin = require('gulp-cssmin'), fs = require('fs'), - jshint = require('gulp-jshint'), + jshint = require('gulp-jshint'), // Obsolete? rename = require('gulp-rename'), sourcemaps = require('gulp-sourcemaps'), - tap = require('gulp-tap'), + ts = require("gulp-typescript"), uglify = require('gulp-uglify'); +// Common +var jsRoot = "./_system/js"; + // app.js variables -var appMinJs = 'app.min.js', +var appJsConfig = jsRoot + "/tsconfig.json", + appMinJs = 'app.min.js', appJs = appMinJs.replace('.min', ''), - appJsRoot = './_system/js/app', + appJsRoot = jsRoot + '/app', appJsSourceMapRoot = appJsRoot.substring(1), - appJsSrc = [appJsRoot + '/**/*.js', - '!' + appJsRoot + '/' + appJs, - '!' + appJsRoot + '/' + appMinJs]; + appJsSrc = [appJsRoot + '/**/*.ts']; // app.css variables var appMinCss = 'app.min.css', appCss = appMinCss.replace('.min', ''), appCssRoot = './_system/css', appCssSrc = [appCssRoot + '/*.css', - appJsRoot + '/directives/**/*.css', + appJsRoot + '/directives/**/*.css', // Angular directives '!' + appCssRoot + '/' + appCss, '!' + appCssRoot + '/' + appMinCss]; // appSettings.js variables +var appSettingsRoot = jsRoot + '/appSettings'; var appSettingsJs = 'appSettings.js'; // lib variables @@ -65,7 +67,7 @@ var libMinJs = 'lib.min.js', libJsSrcRoot + '/toastr/toastr.js', // toastr libJsSrcRoot + '/source-map/dist/source-map.js' // sourceMap ], - libJsDest = './_system/js/lib'; + libJsDest = jsRoot + "/lib"; // lib.css variables var libMinCss = 'lib.min.css', @@ -91,11 +93,11 @@ gulp.task('default', [appJs, appCss, appSettingsJs, libJs, libCss, 'watch']); // app.js: jshhint + concat all into app.js + minify all into app.min.js gulp.task(appJs, function () { - return gulp.src(appJsSrc) - .pipe(jshint()) - .pipe(jshint.reporter('jshint-stylish')) + var tsProject = ts.createProject(appJsConfig, { outFile: appJs }); + + return tsProject.src() .pipe(sourcemaps.init()) - .pipe(concat(appJs, { newLine: '\r\n' })) + .pipe(ts(tsProject)).js .pipe(gulp.dest(appJsRoot)) .pipe(rename(appMinJs)) .pipe(uglify()) @@ -104,6 +106,22 @@ gulp.task(appJs, function () { .pipe(gulp.dest(appJsRoot)); }); +// Old app.js, before typescript - Obsolete +//// app.js: jshhint + concat all into app.js + minify all into app.min.js +//gulp.task(appJs, function () { +// return gulp.src(appJsSrc) +// .pipe(jshint()) +// .pipe(jshint.reporter('jshint-stylish')) +// .pipe(sourcemaps.init()) +// .pipe(concat(appJs, { newLine: '\r\n' })) +// .pipe(gulp.dest(appJsRoot)) +// .pipe(rename(appMinJs)) +// .pipe(uglify()) +// .on('error', errorHandler) +// .pipe(sourcemaps.write('./', { sourceRoot: appJsSourceMapRoot })) +// .pipe(gulp.dest(appJsRoot)); +//}); + // app.css: concat all into app.css + minify all into app.min.css gulp.task(appCss, function () { @@ -118,13 +136,11 @@ gulp.task(appCss, function () { // appSettings.js: if it doesn't exist, copy '/appSettings/Setup/appSettings.js' file to '/appSettings' folder gulp.task(appSettingsJs, function () { - var appSettingsRoot = './_system/js/appSettings'; - fs.stat(appSettingsRoot + '/' + appSettingsJs, function (err, stat) { // If there is no error, it means file is already there. No need to copy from setup, move along! if (err === null) { - return; + return null; } return gulp.src(appSettingsRoot + '/Setup/' + appSettingsJs) diff --git a/ngClient/ngClient.csproj b/ngClient/ngClient.csproj index 39d17f4f0..441d18508 100644 --- a/ngClient/ngClient.csproj +++ b/ngClient/ngClient.csproj @@ -1,5 +1,6 @@  + Debug @@ -22,6 +23,7 @@ + 1.8 true @@ -55,64 +57,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -135,6 +137,7 @@ + @@ -161,6 +164,10 @@ Web.config + + + + @@ -172,6 +179,7 @@ + @@ -181,6 +189,22 @@ $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + Unknown + -1 + True + False + CommonJS + False + + + False + False + True + + + + diff --git a/ngClient/package.json b/ngClient/package.json index d94b7e5e7..af61a62cb 100644 --- a/ngClient/package.json +++ b/ngClient/package.json @@ -13,9 +13,11 @@ "gulp-rename": "^1.2.2", "gulp-sourcemaps": "^1.6.0", "gulp-tap": "^0.1.3", + "gulp-typescript": "^2.13.6", "gulp-uglify": "^1.5.3", "jshint": "^2.9.2", "jshint-stylish": "^2.1.0", + "typescript": "^1.8.10", "angular": "^1.5.0", "angular-ui-bootstrap": "^1.2.1",