From df19ca45a071bf2711c17bd4daea8e583de7ef57 Mon Sep 17 00:00:00 2001 From: Warren Buckley Date: Thu, 2 Apr 2020 15:35:21 +0100 Subject: [PATCH 01/46] Make this a sucessful login even though they have no start nodes - so our SPA app can decide in the UI what to do/show --- src/Umbraco.Web/Security/BackOfficeSignInManager.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Umbraco.Web/Security/BackOfficeSignInManager.cs b/src/Umbraco.Web/Security/BackOfficeSignInManager.cs index 8e5e532731..5f1c1012f3 100644 --- a/src/Umbraco.Web/Security/BackOfficeSignInManager.cs +++ b/src/Umbraco.Web/Security/BackOfficeSignInManager.cs @@ -121,7 +121,9 @@ namespace Umbraco.Web.Security { _logger.WriteCore(TraceEventType.Information, 0, $"Login attempt failed for username {userName} from IP address {_request.RemoteIpAddress}, no content and/or media start nodes could be found for any of the user's groups", null, null); - return SignInStatus.Failure; + + // We will say its a sucessful login which it is, but they have no node access + return SignInStatus.Success; } } From cc62525378fec06658d3aa6e11409ce929460df1 Mon Sep 17 00:00:00 2001 From: Warren Buckley Date: Thu, 2 Apr 2020 15:36:16 +0100 Subject: [PATCH 02/46] Debug with emitted events - ensure to remove this once PR is done --- .../src/common/services/events.service.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/services/events.service.js b/src/Umbraco.Web.UI.Client/src/common/services/events.service.js index 51f63e6787..f90936f371 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/events.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/events.service.js @@ -1,7 +1,7 @@ /** Used to broadcast and listen for global events and allow the ability to add async listeners to the callbacks */ /* - Core app events: + Core app events: app.ready app.authenticated @@ -12,12 +12,14 @@ */ function eventsService($q, $rootScope) { - + return { - + /** raise an event with a given name */ emit: function (name, args) { + console.log(`Emitting event: ${name}`, args); + //there are no listeners if (!$rootScope.$$listeners[name]) { return; From ce3ea2328d6a761a5fbcfacec170368611a9aa92 Mon Sep 17 00:00:00 2001 From: Warren Buckley Date: Thu, 2 Apr 2020 15:38:19 +0100 Subject: [PATCH 03/46] Use the events to notify us that the user does not have start nodes - potetnially could emit a new event as the login screen not showing in this POC --- src/Umbraco.Web.UI.Client/src/init.js | 7 +++++++ src/Umbraco.Web.UI.Client/src/main.controller.js | 4 ++++ .../src/views/common/login.controller.js | 7 +++++++ 3 files changed, 18 insertions(+) diff --git a/src/Umbraco.Web.UI.Client/src/init.js b/src/Umbraco.Web.UI.Client/src/init.js index d5c5166d21..f46b24a546 100644 --- a/src/Umbraco.Web.UI.Client/src/init.js +++ b/src/Umbraco.Web.UI.Client/src/init.js @@ -18,6 +18,13 @@ app.run(['$rootScope', '$route', '$location', 'urlHelper', 'navigationService', /** Listens for authentication and checks if our required assets are loaded, if/once they are we'll broadcast a ready event */ eventsService.on("app.authenticated", function (evt, data) { + // Lets check if the auth'd user has a start node set (befor trying to make the app ready) + const user = data.user; + if(user.startContentIds.length === 0 && user.startMediaIds.length === 0){ + const args = { isTimedOut: true, noAccess: true }; + eventsService.emit("app.notAuthenticated", args); + } + assetsService._loadInitAssets().then(function () { appReady(data); diff --git a/src/Umbraco.Web.UI.Client/src/main.controller.js b/src/Umbraco.Web.UI.Client/src/main.controller.js index 198ac132c1..4fac328f70 100644 --- a/src/Umbraco.Web.UI.Client/src/main.controller.js +++ b/src/Umbraco.Web.UI.Client/src/main.controller.js @@ -57,6 +57,7 @@ function MainController($scope, $location, appState, treeService, notificationsS }; $scope.showLoginScreen = function(isTimedOut) { + console.log('SHOW ME THE LOGIN SCREEN'); $scope.login.isTimedOut = isTimedOut; $scope.login.show = true; }; @@ -72,6 +73,9 @@ function MainController($scope, $location, appState, treeService, notificationsS $scope.authenticated = null; $scope.user = null; const isTimedOut = data && data.isTimedOut ? true : false; + + console.log('Log me out & show login screen?', isTimedOut); + $scope.showLoginScreen(isTimedOut); // Remove the localstorage items for tours shown diff --git a/src/Umbraco.Web.UI.Client/src/views/common/login.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/login.controller.js index 86132fe8f3..713af9661b 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/login.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/login.controller.js @@ -17,6 +17,13 @@ angular.module('umbraco').controller("Umbraco.LoginController", function (events $location.url(path); }); + eventsService.on("app.notAuthenticated", function(evt, data){ + console.log('not authenticated event back', data); + if(data.noAccess){ + alert('NO NO NO YOU HAVE NO START NODES'); + } + }); + $scope.$on('$destroy', function () { eventsService.unsubscribe(evtOn); }); From 9fece778b888299341725eded4bad12f173b6d4d Mon Sep 17 00:00:00 2001 From: Dima Lakhter Date: Fri, 3 Apr 2020 11:57:53 -0700 Subject: [PATCH 04/46] Possible fix for issue #7870 --- src/Umbraco.Core/PropertyEditors/DataEditor.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Umbraco.Core/PropertyEditors/DataEditor.cs b/src/Umbraco.Core/PropertyEditors/DataEditor.cs index c749c61300..add523ecf6 100644 --- a/src/Umbraco.Core/PropertyEditors/DataEditor.cs +++ b/src/Umbraco.Core/PropertyEditors/DataEditor.cs @@ -19,7 +19,6 @@ namespace Umbraco.Core.PropertyEditors public class DataEditor : IDataEditor { private IDictionary _defaultConfiguration; - private IDataValueEditor _dataValueEditor; /// /// Initializes a new instance of the class. @@ -91,7 +90,7 @@ namespace Umbraco.Core.PropertyEditors /// simple enough for now. /// // TODO: point of that one? shouldn't we always configure? - public IDataValueEditor GetValueEditor() => ExplicitValueEditor ?? (_dataValueEditor ?? (_dataValueEditor = CreateValueEditor())); + public IDataValueEditor GetValueEditor() => ExplicitValueEditor ?? CreateValueEditor(); /// /// From 0184599b5c3a08fe292c43151a4cf9ca7263b1e2 Mon Sep 17 00:00:00 2001 From: Ronald Barendse Date: Thu, 9 Apr 2020 14:57:15 +0200 Subject: [PATCH 05/46] Fix EnsureMemberProperties data type IDs --- .../Models/PublishedContent/PublishedContentType.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Umbraco.Core/Models/PublishedContent/PublishedContentType.cs b/src/Umbraco.Core/Models/PublishedContent/PublishedContentType.cs index b11e991118..458b63ade3 100644 --- a/src/Umbraco.Core/Models/PublishedContent/PublishedContentType.cs +++ b/src/Umbraco.Core/Models/PublishedContent/PublishedContentType.cs @@ -105,13 +105,13 @@ namespace Umbraco.Core.Models.PublishedContent { "Email", Constants.DataTypes.Textbox }, { "Username", Constants.DataTypes.Textbox }, { "PasswordQuestion", Constants.DataTypes.Textbox }, - { "Comments", Constants.DataTypes.Textbox }, + { "Comments", Constants.DataTypes.Textarea }, { "IsApproved", Constants.DataTypes.Boolean }, { "IsLockedOut", Constants.DataTypes.Boolean }, - { "LastLockoutDate", Constants.DataTypes.DateTime }, - { "CreateDate", Constants.DataTypes.DateTime }, - { "LastLoginDate", Constants.DataTypes.DateTime }, - { "LastPasswordChangeDate", Constants.DataTypes.DateTime }, + { "LastLockoutDate", Constants.DataTypes.LabelDateTime }, + { "CreateDate", Constants.DataTypes.LabelDateTime }, + { "LastLoginDate", Constants.DataTypes.LabelDateTime }, + { "LastPasswordChangeDate", Constants.DataTypes.LabelDateTime } }; #region Content type From fdb3c55d092930d8fc0af6c3c043eeb53b198ca0 Mon Sep 17 00:00:00 2001 From: Robert Foster Date: Thu, 9 Apr 2020 15:34:22 +1000 Subject: [PATCH 06/46] Added support for Grid Editor in an IPublishedElement - resolves #7916 --- src/Umbraco.Web/GridTemplateExtensions.cs | 28 +++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/Umbraco.Web/GridTemplateExtensions.cs b/src/Umbraco.Web/GridTemplateExtensions.cs index afa929cfbb..81dc33d2c6 100644 --- a/src/Umbraco.Web/GridTemplateExtensions.cs +++ b/src/Umbraco.Web/GridTemplateExtensions.cs @@ -45,6 +45,34 @@ namespace Umbraco.Web return html.Partial(view, model); } + public static MvcHtmlString GetGridHtml(this HtmlHelper html, IPublishedElement contentItem) + { + return html.GetGridHtml(contentItem, "bodyText", "bootstrap3"); + } + + public static MvcHtmlString GetGridHtml(this HtmlHelper html, IPublishedElement contentItem, string propertyAlias) + { + if (propertyAlias == null) throw new ArgumentNullException(nameof(propertyAlias)); + if (string.IsNullOrWhiteSpace(propertyAlias)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(propertyAlias)); + + return html.GetGridHtml(contentItem, propertyAlias, "bootstrap3"); + } + + public static MvcHtmlString GetGridHtml(this HtmlHelper html, IPublishedElement contentItem, string propertyAlias, string framework) + { + if (propertyAlias == null) throw new ArgumentNullException(nameof(propertyAlias)); + if (string.IsNullOrWhiteSpace(propertyAlias)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(propertyAlias)); + + var view = "Grid/" + framework; + var prop = contentItem.GetProperty(propertyAlias); + if (prop == null) throw new InvalidOperationException("No property type found with alias " + propertyAlias); + var model = prop.GetValue(); + + var asString = model as string; + if (asString != null && string.IsNullOrEmpty(asString)) return new MvcHtmlString(string.Empty); + + return html.Partial(view, model); + } public static MvcHtmlString GetGridHtml(this IPublishedProperty property, HtmlHelper html, string framework = "bootstrap3") { var asString = property.GetValue() as string; From 9f7c44c64ebfb23acd1bb06aa22c5bc39ad5079a Mon Sep 17 00:00:00 2001 From: Benjamin Carleski Date: Wed, 1 Apr 2020 16:22:20 -0700 Subject: [PATCH 07/46] 7879: Handle for multiple picked media relations --- .../PropertyEditors/MediaPickerPropertyEditor.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Umbraco.Web/PropertyEditors/MediaPickerPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/MediaPickerPropertyEditor.cs index ece210b9d1..fa8060bd15 100644 --- a/src/Umbraco.Web/PropertyEditors/MediaPickerPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/MediaPickerPropertyEditor.cs @@ -45,8 +45,11 @@ namespace Umbraco.Web.PropertyEditors if (string.IsNullOrEmpty(asString)) yield break; - if (Udi.TryParse(asString, out var udi)) - yield return new UmbracoEntityReference(udi); + foreach (var udiStr in asString.Split(',')) + { + if (Udi.TryParse(udiStr, out var udi)) + yield return new UmbracoEntityReference(udi); + } } } } From bcea0f645a1f39b13bedbac0f6b4b6f6b6d6a9e0 Mon Sep 17 00:00:00 2001 From: mattchanner Date: Wed, 1 Apr 2020 13:12:05 +0100 Subject: [PATCH 08/46] Added null check on raw JSON to prevent null reference error deserializing the grid --- src/Umbraco.Web/PropertyEditors/GridPropertyEditor.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Umbraco.Web/PropertyEditors/GridPropertyEditor.cs b/src/Umbraco.Web/PropertyEditors/GridPropertyEditor.cs index 28cc70f776..862837381a 100644 --- a/src/Umbraco.Web/PropertyEditors/GridPropertyEditor.cs +++ b/src/Umbraco.Web/PropertyEditors/GridPropertyEditor.cs @@ -192,6 +192,10 @@ namespace Umbraco.Web.PropertyEditors public IEnumerable GetReferences(object value) { var rawJson = value == null ? string.Empty : value is string str ? str : value.ToString(); + + if (rawJson.IsNullOrWhiteSpace()) + yield break; + DeserializeGridValue(rawJson, out var richTextEditorValues, out var mediaValues); foreach (var umbracoEntityReference in richTextEditorValues.SelectMany(x => From 199d908d7a5e9c1908f36f0bbe309b52c5f16939 Mon Sep 17 00:00:00 2001 From: Emil Olsson Date: Thu, 9 Apr 2020 17:25:48 +0200 Subject: [PATCH 09/46] #7658 Fix linking account if multiple IDP on common user overlay (#7845) --- .../src/views/common/overlays/user/user.controller.js | 4 ++++ .../src/views/common/overlays/user/user.html | 5 ++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/views/common/overlays/user/user.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/overlays/user/user.controller.js index 5ed87f073b..8248d11863 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/overlays/user/user.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/overlays/user/user.controller.js @@ -91,6 +91,10 @@ angular.module("umbraco") }); } + $scope.linkProvider = function (e) { + e.target.submit(); + } + $scope.unlink = function (e, loginProvider, providerKey) { var result = confirm("Are you sure you want to unlink this account?"); if (!result) { diff --git a/src/Umbraco.Web.UI.Client/src/views/common/overlays/user/user.html b/src/Umbraco.Web.UI.Client/src/views/common/overlays/user/user.html index 531feef892..8b12d061f3 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/overlays/user/user.html +++ b/src/Umbraco.Web.UI.Client/src/views/common/overlays/user/user.html @@ -49,12 +49,11 @@
-
+ diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml index 0a372dbcb5..dc8dc0d7ef 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml @@ -1846,7 +1846,7 @@ To manage your website, simply open the Umbraco back office and start adding con Reset password Your password has been changed! Password changed - Please confirm the new password + Please confirm the new password Enter your new password Your new password cannot be blank! Current password @@ -2223,6 +2223,7 @@ To manage your website, simply open the Umbraco back office and start adding con Create Edit Name + Add new row References @@ -2388,7 +2389,7 @@ To manage your website, simply open the Umbraco back office and start adding con Welcome to The Friendly CMS Thank you for choosing Umbraco - we think this could be the beginning of something beautiful. While it may feel overwhelming at first, we've done a lot to make the learning curve as smooth and fast as possible. - + Umbraco Forms Create forms using an intuitive drag and drop interface. From simple contact forms that sends e-mails to advanced questionaires that integrate with CRM systems. Your clients will love it! diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml index 482973f5e7..7a3ec88bd3 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml @@ -2235,6 +2235,7 @@ To manage your website, simply open the Umbraco back office and start adding con Create Edit Name + Add new row References @@ -2400,7 +2401,7 @@ To manage your website, simply open the Umbraco back office and start adding con Welcome to The Friendly CMS Thank you for choosing Umbraco - we think this could be the beginning of something beautiful. While it may feel overwhelming at first, we've done a lot to make the learning curve as smooth and fast as possible. - + Umbraco Forms Create forms using an intuitive drag and drop interface. From simple contact forms that sends e-mails to advanced questionaires that integrate with CRM systems. Your clients will love it! From 421d7ac30d3b95362e2a95d577de20b22b4ef615 Mon Sep 17 00:00:00 2001 From: Carole Rennie Logan Date: Fri, 10 Apr 2020 15:49:10 +0100 Subject: [PATCH 13/46] Renaming PR team name in contributing docs --- .github/CONTRIBUTING.md | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 0101ac9d16..5634b5bda5 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -22,7 +22,7 @@ This project and everyone participating in it, is governed by the [our Code of C [Reviews](#reviews) * [Styleguides](#styleguides) - * [The PR team](#the-pr-team) + * [The Core Contributors](#the-core-contributors-team) * [Questions?](#questions) [Working with the code](#working-with-the-code) @@ -98,20 +98,21 @@ To be honest, we don't like rules very much. We trust you have the best of inten That said, the Umbraco development team likes to follow the hints that ReSharper gives us (no problem if you don't have this installed) and we've added a `.editorconfig` file so that Visual Studio knows what to do with whitespace, line endings, etc. -### The PR team +### The Core Contributors team -The pull request team consists of one member of Umbraco HQ, [Sebastiaan](https://github.com/nul800sebastiaan), who gets assistance from the following community members who have comitted to volunteering their free time: +The Core Contributors team consists of one member of Umbraco HQ, [Sebastiaan](https://github.com/nul800sebastiaan), who gets assistance from the following community members who have comitted to volunteering their free time: - [Anders Bjerner](https://github.com/abjerner) -- [Dave Woestenborghs](https://github.com/dawoe) - [Emma Burstow](https://github.com/emmaburstow) - [Poornima Nayar](https://github.com/poornimanayar) +- [Kenn Jacobsen](https://twitter.com/KennJacobsen_DK) + These wonderful people aim to provide you with a first reply to your PR, review and test out your changes and on occasions, they might ask more questions. If they are happy with your work, they'll let Umbraco HQ know by approving the PR. Hq will have final sign-off and will check the work again before it is merged. ### Questions? -You can get in touch with [the PR team](#the-pr-team) in multiple ways; we love open conversations and we are a friendly bunch. No question you have is stupid. Any question you have usually helps out multiple people with the same question. Ask away: +You can get in touch with [the core contributors team](#the-core-contributors-team) in multiple ways; we love open conversations and we are a friendly bunch. No question you have is stupid. Any question you have usually helps out multiple people with the same question. Ask away: - If there's an existing issue on the issue tracker then that's a good place to leave questions and discuss how to start or move forward. - Unsure where to start? Did something not work as expected? Try leaving a note in the ["Contributing to Umbraco"](https://our.umbraco.com/forum/contributing-to-umbraco-cms/) forum. The team monitors that one closely, so one of us will be on hand and ready to point you in the right direction. @@ -193,4 +194,4 @@ In this command we're syncing with the `v8/contrib` branch, but you can of cours ### And finally -We welcome all kinds of contributions to this repository. If you don't feel you'd like to make code changes here, you can visit our [documentation repository](https://github.com/umbraco/UmbracoDocs) and use your experience to contribute to making the docs we have, even better. We also encourage community members to feel free to comment on others' pull requests and issues - the expertise we have is not limited to the PR team and HQ. So, if you see something on the issue tracker or pull requests you feel you can add to, please don't be shy. +We welcome all kinds of contributions to this repository. If you don't feel you'd like to make code changes here, you can visit our [documentation repository](https://github.com/umbraco/UmbracoDocs) and use your experience to contribute to making the docs we have, even better. We also encourage community members to feel free to comment on others' pull requests and issues - the expertise we have is not limited to the Core Contributors and HQ. So, if you see something on the issue tracker or pull requests you feel you can add to, please don't be shy. From 3e9c759426e5b852f0ea643a26b68c73f4048343 Mon Sep 17 00:00:00 2001 From: Jan Skovgaard Date: Fri, 10 Apr 2020 17:41:31 +0200 Subject: [PATCH 14/46] =?UTF-8?q?Move=20the=20infinite=20overlay=20to=20th?= =?UTF-8?q?e=20same=20source=20order=20as=20regular=20o=E2=80=A6=20(#7923)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/less/components/editor/umb-editor.less | 3 ++- src/Umbraco.Web.UI/Umbraco/Views/Default.cshtml | 8 +++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/less/components/editor/umb-editor.less b/src/Umbraco.Web.UI.Client/src/less/components/editor/umb-editor.less index d2a3bdedb1..e81df77772 100644 --- a/src/Umbraco.Web.UI.Client/src/less/components/editor/umb-editor.less +++ b/src/Umbraco.Web.UI.Client/src/less/components/editor/umb-editor.less @@ -1,6 +1,7 @@ .umb-editors { .absolute(); overflow: hidden; + z-index: 7500; .umb-editor { box-shadow: 0px 0 30px 0 rgba(0,0,0,.3); @@ -104,4 +105,4 @@ i { margin-right:5px; } -} \ No newline at end of file +} diff --git a/src/Umbraco.Web.UI/Umbraco/Views/Default.cshtml b/src/Umbraco.Web.UI/Umbraco/Views/Default.cshtml index 056d2b6f51..bd8d23a851 100644 --- a/src/Umbraco.Web.UI/Umbraco/Views/Default.cshtml +++ b/src/Umbraco.Web.UI/Umbraco/Views/Default.cshtml @@ -66,11 +66,7 @@
-
-
- -
@@ -93,7 +89,7 @@
- + + From a977cfdc3f8d5ed5f062a0d22fb899f439c1ae87 Mon Sep 17 00:00:00 2001 From: Matthew-Wise <6782865+Matthew-Wise@users.noreply.github.com> Date: Fri, 10 Apr 2020 16:57:33 +0100 Subject: [PATCH 15/46] Moved from angular.IsNumber to Utilities.IsNumber (#7925) --- .../src/common/directives/components/umbaceeditor.directive.js | 2 +- .../src/common/resources/content.resource.js | 2 +- .../src/common/resources/media.resource.js | 2 +- .../src/common/resources/member.resource.js | 2 +- .../src/common/services/contenteditinghelper.service.js | 2 +- .../src/common/services/umbdataformatter.service.js | 2 +- src/Umbraco.Web.UI.Client/src/common/services/user.service.js | 2 +- .../imagecropper/imagecropper.prevalues.controller.js | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbaceeditor.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbaceeditor.directive.js index b4d98031e7..329a3913f2 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbaceeditor.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbaceeditor.directive.js @@ -80,7 +80,7 @@ } // Advanced options if (Utilities.isDefined(opts.firstLineNumber)) { - if (angular.isNumber(opts.firstLineNumber)) { + if (Utilities.isNumber(opts.firstLineNumber)) { session.setOption('firstLineNumber', opts.firstLineNumber); } else if (angular.isFunction(opts.firstLineNumber)) { session.setOption('firstLineNumber', opts.firstLineNumber()); diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js index d714ea4938..cd05e26e56 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js @@ -610,7 +610,7 @@ function contentResource($q, $http, umbDataFormatter, umbRequestHelper) { //converts the value to a js bool function toBool(v) { - if (angular.isNumber(v)) { + if (Utilities.isNumber(v)) { return v > 0; } if (angular.isString(v)) { diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/media.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/media.resource.js index e4e3cc6f3f..b5c53b6f44 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/media.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/media.resource.js @@ -348,7 +348,7 @@ function mediaResource($q, $http, umbDataFormatter, umbRequestHelper) { //converts the value to a js bool function toBool(v) { - if (angular.isNumber(v)) { + if (Utilities.isNumber(v)) { return v > 0; } if (angular.isString(v)) { diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/member.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/member.resource.js index d21edbbab8..32f81fdff1 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/member.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/member.resource.js @@ -53,7 +53,7 @@ function memberResource($q, $http, umbDataFormatter, umbRequestHelper) { //converts the value to a js bool function toBool(v) { - if (angular.isNumber(v)) { + if (Utilities.isNumber(v)) { return v > 0; } if (angular.isString(v)) { diff --git a/src/Umbraco.Web.UI.Client/src/common/services/contenteditinghelper.service.js b/src/Umbraco.Web.UI.Client/src/common/services/contenteditinghelper.service.js index 3cfe4f740e..5cf54ad6a0 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/contenteditinghelper.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/contenteditinghelper.service.js @@ -10,7 +10,7 @@ function contentEditingHelper(fileManager, $q, $location, $routeParams, editorSt function isValidIdentifier(id) { //empty id <= 0 - if (angular.isNumber(id)) { + if (Utilities.isNumber(id)) { if (id === 0) { return false; } diff --git a/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js b/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js index d9aef1ddba..c36ffdc58a 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js @@ -242,7 +242,7 @@ var currUsers = saveModel.users; var formattedUsers = []; for (var j = 0; j < currUsers.length; j++) { - if (!angular.isNumber(currUsers[j])) { + if (!Utilities.isNumber(currUsers[j])) { formattedUsers.push(currUsers[j].id); } else { diff --git a/src/Umbraco.Web.UI.Client/src/common/services/user.service.js b/src/Umbraco.Web.UI.Client/src/common/services/user.service.js index afd7b606e7..91dc08ebe2 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/user.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/user.service.js @@ -128,7 +128,7 @@ angular.module('umbraco.services') function setUserTimeoutInternal(newTimeout) { var asNumber = parseFloat(newTimeout); - if (!isNaN(asNumber) && currentUser && angular.isNumber(asNumber)) { + if (!isNaN(asNumber) && currentUser && Utilities.isNumber(asNumber)) { currentUser.remainingAuthSeconds = newTimeout; lastServerTimeoutSet = new Date(); } diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.prevalues.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.prevalues.controller.js index de56442239..79ed11aef8 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.prevalues.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.prevalues.controller.js @@ -47,7 +47,7 @@ angular.module("umbraco").controller("Umbraco.PrevalueEditors.CropSizesControlle $scope.setFocus = true; if ($scope.newItem && $scope.newItem.alias && - angular.isNumber($scope.newItem.width) && angular.isNumber($scope.newItem.height) && + Utilities.isNumber($scope.newItem.width) && Utilities.isNumber($scope.newItem.height) && $scope.newItem.width > 0 && $scope.newItem.height > 0) { var exists = _.find($scope.model.value, function (item) { return $scope.newItem.alias === item.alias; }); From 1e851b615f56a5bd7eeedcc18c843807c145db5e Mon Sep 17 00:00:00 2001 From: Marc Goodson Date: Fri, 10 Apr 2020 16:50:57 +0100 Subject: [PATCH 16/46] Button tag isn't closed? leaving invalid markup It looks like to me there is an 'extra' closing div in this markup... but I think this is because the button isn't closed, there is a closing div where the closing button should be? - eg the icon and span are part of thee button... I've made this change locally and it operates fine, but then it operating fine before hand too... --- .../src/views/components/umb-layout-selector.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Umbraco.Web.UI.Client/src/views/components/umb-layout-selector.html b/src/Umbraco.Web.UI.Client/src/views/components/umb-layout-selector.html index 1fa917a07f..c9bf3b3083 100644 --- a/src/Umbraco.Web.UI.Client/src/views/components/umb-layout-selector.html +++ b/src/Umbraco.Web.UI.Client/src/views/components/umb-layout-selector.html @@ -21,7 +21,7 @@ {{layout.name}} - + From 76e4b6b3012753b9388963e636380ac3c227ec47 Mon Sep 17 00:00:00 2001 From: Matthew-Wise <6782865+Matthew-Wise@users.noreply.github.com> Date: Fri, 10 Apr 2020 17:07:37 +0100 Subject: [PATCH 17/46] Replaced angular.toJson with Utilities.toJson [#CanConHackathon] (#7924) --- .../components/forms/umbrawmodel.directive.js | 2 +- .../src/common/resources/auth.resource.js | 2 +- .../common/resources/currentuser.resource.js | 2 +- .../src/common/services/macro.service.js | 4 +- .../services/umbrequesthelper.service.js | 4 +- .../src/common/services/util.service.js | 2 +- src/Umbraco.Web.UI.Client/src/utilities.js | 31 ++++++++++- .../test/unit/utilities.spec.js | 55 +++++++++++++++++++ 8 files changed, 93 insertions(+), 9 deletions(-) create mode 100644 src/Umbraco.Web.UI.Client/test/unit/utilities.spec.js diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbrawmodel.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbrawmodel.directive.js index 9b479b60ae..406f65781c 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbrawmodel.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbrawmodel.directive.js @@ -49,7 +49,7 @@ angular.module("umbraco.directives") function jsonToString(object) { // better than JSON.stringify(), because it formats + filters $$hashKey etc. // NOTE that this will remove all $-prefixed values - return angular.toJson(object, true); + return Utilities.toJson(object, true); } function isValidJson(model) { diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/auth.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/auth.resource.js index 678cffe42e..936f69e738 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/auth.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/auth.resource.js @@ -30,7 +30,7 @@ function authResource($q, $http, umbRequestHelper, angularHelper) { umbRequestHelper.getApiUrl( "authenticationApiBaseUrl", "PostSend2FACode"), - angular.toJson(provider)), + Utilities.toJson(provider)), 'Could not send code'); }, diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/currentuser.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/currentuser.resource.js index e10837ceca..60b87e919f 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/currentuser.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/currentuser.resource.js @@ -87,7 +87,7 @@ function currentUserResource($q, $http, umbRequestHelper, umbDataFormatter) { umbRequestHelper.getApiUrl( "currentUserApiBaseUrl", "PostSetInvitedUserPassword"), - angular.toJson(newPassword)), + Utilities.toJson(newPassword)), 'Failed to change password'); }, diff --git a/src/Umbraco.Web.UI.Client/src/common/services/macro.service.js b/src/Umbraco.Web.UI.Client/src/common/services/macro.service.js index a91f9d51e4..bdead487b5 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/macro.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/macro.service.js @@ -67,7 +67,7 @@ function macroService() { } else { //if it's not a string we'll send it through the json serializer - var json = angular.toJson(val); + var json = Utilities.toJson(val); //then we need to url encode it so that it's safe var encoded = encodeURIComponent(json); keyVal = key + "=\"" + encoded + "\" "; @@ -142,7 +142,7 @@ function macroService() { if (item.value !== null && item.value !== undefined && !_.isString(item.value)) { try { - val = angular.toJson(val); + val = Utilities.toJson(val); } catch (e) { // not json diff --git a/src/Umbraco.Web.UI.Client/src/common/services/umbrequesthelper.service.js b/src/Umbraco.Web.UI.Client/src/common/services/umbrequesthelper.service.js index cf2b8d30ad..d343aea0d2 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/umbrequesthelper.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/umbrequesthelper.service.js @@ -342,11 +342,11 @@ function umbRequestHelper($http, $q, notificationsService, eventsService, formHe //add the json data if (angular.isArray(data)) { _.each(data, function(item) { - formData.append(item.key, !angular.isString(item.value) ? angular.toJson(item.value) : item.value); + formData.append(item.key, !angular.isString(item.value) ? Utilities.toJson(item.value) : item.value); }); } else { - formData.append(data.key, !angular.isString(data.value) ? angular.toJson(data.value) : data.value); + formData.append(data.key, !angular.isString(data.value) ? Utilities.toJson(data.value) : data.value); } //call the callback diff --git a/src/Umbraco.Web.UI.Client/src/common/services/util.service.js b/src/Umbraco.Web.UI.Client/src/common/services/util.service.js index a7ff9def21..a7c98b9ac4 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/util.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/util.service.js @@ -210,7 +210,7 @@ function umbSessionStorage($window) { }, set: function (key, value) { - storage["umb_" + key] = angular.toJson(value); + storage["umb_" + key] = Utilities.toJson(value); } }; diff --git a/src/Umbraco.Web.UI.Client/src/utilities.js b/src/Umbraco.Web.UI.Client/src/utilities.js index bd12506358..71d904427b 100644 --- a/src/Umbraco.Web.UI.Client/src/utilities.js +++ b/src/Umbraco.Web.UI.Client/src/utilities.js @@ -66,6 +66,34 @@ */ const isObject = val => val !== null && typeof val === 'object'; + const isWindow = obj => obj && obj.window === obj; + + const isScope = obj => obj && obj.$evalAsync && obj.$watch; + + const toJsonReplacer = (key, value) => { + var val = value; + if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') { + val = undefined; + } else if (isWindow(value)) { + val = '$WINDOW'; + } else if (value && window.document === value) { + val = '$DOCUMENT'; + } else if (isScope(value)) { + val = '$SCOPE'; + } + return val; + } + /** + * Equivalent to angular.toJson + */ + const toJson = (obj, pretty) => { + if (isUndefined(obj)) return undefined; + if (!isNumber(pretty)) { + pretty = pretty ? 2 : null; + } + return JSON.stringify(obj, toJsonReplacer, pretty); + } + let _utilities = { noop: noop, copy: copy, @@ -77,7 +105,8 @@ isDefined: isDefined, isString: isString, isNumber: isNumber, - isObject: isObject + isObject: isObject, + toJson: toJson }; if (typeof (window.Utilities) === 'undefined') { diff --git a/src/Umbraco.Web.UI.Client/test/unit/utilities.spec.js b/src/Umbraco.Web.UI.Client/test/unit/utilities.spec.js new file mode 100644 index 0000000000..825ede8ea5 --- /dev/null +++ b/src/Umbraco.Web.UI.Client/test/unit/utilities.spec.js @@ -0,0 +1,55 @@ +(function () { + describe("Utilities", function () { + describe("toJson", function () { + it("should delegate to JSON.stringify", function () { + var spy = spyOn(JSON, "stringify").and.callThrough(); + + expect(Utilities.toJson({})).toEqual("{}"); + expect(spy).toHaveBeenCalled(); + }); + + it("should format objects pretty", function () { + expect(Utilities.toJson({ a: 1, b: 2 }, true)).toBe( + '{\n "a": 1,\n "b": 2\n}' + ); + expect(Utilities.toJson({ a: { b: 2 } }, true)).toBe( + '{\n "a": {\n "b": 2\n }\n}' + ); + expect(Utilities.toJson({ a: 1, b: 2 }, false)).toBe('{"a":1,"b":2}'); + expect(Utilities.toJson({ a: 1, b: 2 }, 0)).toBe('{"a":1,"b":2}'); + expect(Utilities.toJson({ a: 1, b: 2 }, 1)).toBe( + '{\n "a": 1,\n "b": 2\n}' + ); + expect(Utilities.toJson({ a: 1, b: 2 }, {})).toBe( + '{\n "a": 1,\n "b": 2\n}' + ); + }); + + it("should not serialize properties starting with $$", function () { + expect(Utilities.toJson({ $$some: "value" }, false)).toEqual("{}"); + }); + + it("should serialize properties starting with $", function () { + expect(Utilities.toJson({ $few: "v" }, false)).toEqual('{"$few":"v"}'); + }); + + it("should not serialize $window object", function () { + expect(Utilities.toJson(window)).toEqual('"$WINDOW"'); + }); + + it("should not serialize $document object", function () { + expect(Utilities.toJson(document)).toEqual('"$DOCUMENT"'); + }); + + it("should not serialize scope instances", inject(function ( + $rootScope + ) { + expect(Utilities.toJson({ key: $rootScope })).toEqual('{"key":"$SCOPE"}'); + })); + + it("should serialize undefined as undefined", function () { + expect(Utilities.toJson(undefined)).toEqual(undefined); + }); + }); + }); +})(); From 318fcbe3ba02c33105c51c0e123dd0b4bb184c08 Mon Sep 17 00:00:00 2001 From: Mike Masey Date: Fri, 10 Apr 2020 17:24:08 +0100 Subject: [PATCH 18/46] V8: Angular Divorce: isString (#7929) --- .../directives/components/forms/fixnumber.directive.js | 4 ++-- .../directives/components/grid/grid.rte.directive.js | 2 +- .../components/tags/umbtagseditor.directive.js | 2 +- .../directives/components/tree/umbtree.directive.js | 4 ++-- .../directives/components/umbaceeditor.directive.js | 4 ++-- .../src/common/filters/umbwordlimit.filter.js | 4 ++-- .../src/common/resources/content.resource.js | 2 +- .../src/common/resources/media.resource.js | 2 +- .../src/common/resources/member.resource.js | 2 +- .../src/common/services/filemanager.service.js | 2 +- .../src/common/services/macro.service.js | 2 +- .../src/common/services/mediahelper.service.js | 2 +- .../src/common/services/navigation.service.js | 10 +++++----- .../src/common/services/servervalidationmgr.service.js | 6 +++--- .../src/common/services/umbdataformatter.service.js | 4 ++-- .../src/common/services/umbrequesthelper.service.js | 8 ++++---- src/Umbraco.Web.UI.Client/src/navigation.controller.js | 2 +- .../src/views/propertyeditors/grid/grid.controller.js | 2 +- .../imagecropper/imagecropper.controller.js | 4 ++-- .../propertyeditors/listview/listview.controller.js | 2 +- .../src/views/propertyeditors/rte/rte.controller.js | 2 +- .../propertyeditors/rte/rte.prevalues.controller.js | 2 +- .../test/lib/angular/angular-mocks.js | 8 ++++---- 23 files changed, 41 insertions(+), 41 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/fixnumber.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/fixnumber.directive.js index 3084472332..56f5323c73 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/fixnumber.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/fixnumber.directive.js @@ -32,7 +32,7 @@ function fixNumber($parse) { //always try to format the model value as an int ctrl.$formatters.push(function (value) { - if (angular.isString(value)) { + if (Utilities.isString(value)) { return parseFloat(value, 10); } return value; @@ -55,4 +55,4 @@ function fixNumber($parse) { } }; } -angular.module('umbraco.directives').directive("fixNumber", fixNumber); \ No newline at end of file +angular.module('umbraco.directives').directive("fixNumber", fixNumber); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/grid/grid.rte.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/grid/grid.rte.directive.js index f606c0539a..3578624b50 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/grid/grid.rte.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/grid/grid.rte.directive.js @@ -29,7 +29,7 @@ angular.module("umbraco.directives") } var editorConfig = scope.configuration ? scope.configuration : null; - if (!editorConfig || angular.isString(editorConfig)) { + if (!editorConfig || Utilities.isString(editorConfig)) { editorConfig = tinyMceService.defaultPrevalues(); //for the grid by default, we don't want to include the macro toolbar editorConfig.toolbar = _.without(editorConfig, "umbmacro"); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/tags/umbtagseditor.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/tags/umbtagseditor.directive.js index 7ff7f7fa66..aecdcba118 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/tags/umbtagseditor.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/tags/umbtagseditor.directive.js @@ -159,7 +159,7 @@ function configureViewModel(isInitLoad) { if (vm.value) { - if (angular.isString(vm.value) && vm.value.length > 0) { + if (Utilities.isString(vm.value) && vm.value.length > 0) { if (vm.config.storageType === "Json") { //json storage vm.viewModel = JSON.parse(vm.value); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/tree/umbtree.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/tree/umbtree.directive.js index 3d743c7e9a..8825f5daa0 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/tree/umbtree.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/tree/umbtree.directive.js @@ -100,7 +100,7 @@ function umbTreeDirective($q, $rootScope, treeService, notificationsService, use * @param {any} args either a string representing the 'section' or an object containing: 'section', 'treeAlias', 'customTreeParams', 'cacheKey' */ function load(args) { - if (angular.isString(args)) { + if (Utilities.isString(args)) { $scope.section = args; } else if (args) { @@ -147,7 +147,7 @@ function umbTreeDirective($q, $rootScope, treeService, notificationsService, use throw "args.path cannot be null"; } - if (angular.isString(args.path)) { + if (Utilities.isString(args.path)) { args.path = args.path.replace('"', '').split(','); } diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbaceeditor.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbaceeditor.directive.js index 329a3913f2..10fc44c2c6 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbaceeditor.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbaceeditor.directive.js @@ -72,10 +72,10 @@ } // Basic options - if (angular.isString(opts.theme)) { + if (Utilities.isString(opts.theme)) { acee.setTheme('ace/theme/' + opts.theme); } - if (angular.isString(opts.mode)) { + if (Utilities.isString(opts.mode)) { session.setMode('ace/mode/' + opts.mode); } // Advanced options diff --git a/src/Umbraco.Web.UI.Client/src/common/filters/umbwordlimit.filter.js b/src/Umbraco.Web.UI.Client/src/common/filters/umbwordlimit.filter.js index c02624409f..93f0bddc96 100644 --- a/src/Umbraco.Web.UI.Client/src/common/filters/umbwordlimit.filter.js +++ b/src/Umbraco.Web.UI.Client/src/common/filters/umbwordlimit.filter.js @@ -13,7 +13,7 @@ function umbWordLimitFilter() { return function (collection, property) { - if (!angular.isString(collection)) { + if (!Utilities.isString(collection)) { return collection; } @@ -35,4 +35,4 @@ angular.module('umbraco.filters').filter('umbWordLimit', umbWordLimitFilter); -})(); \ No newline at end of file +})(); diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js index cd05e26e56..96dcd38f13 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js @@ -613,7 +613,7 @@ function contentResource($q, $http, umbDataFormatter, umbRequestHelper) { if (Utilities.isNumber(v)) { return v > 0; } - if (angular.isString(v)) { + if (Utilities.isString(v)) { return v === "true"; } if (typeof v === "boolean") { diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/media.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/media.resource.js index b5c53b6f44..e24f4786eb 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/media.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/media.resource.js @@ -351,7 +351,7 @@ function mediaResource($q, $http, umbDataFormatter, umbRequestHelper) { if (Utilities.isNumber(v)) { return v > 0; } - if (angular.isString(v)) { + if (Utilities.isString(v)) { return v === "true"; } if (typeof v === "boolean") { diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/member.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/member.resource.js index 32f81fdff1..c45e173a98 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/member.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/member.resource.js @@ -56,7 +56,7 @@ function memberResource($q, $http, umbDataFormatter, umbRequestHelper) { if (Utilities.isNumber(v)) { return v > 0; } - if (angular.isString(v)) { + if (Utilities.isString(v)) { return v === "true"; } if (typeof v === "boolean") { diff --git a/src/Umbraco.Web.UI.Client/src/common/services/filemanager.service.js b/src/Umbraco.Web.UI.Client/src/common/services/filemanager.service.js index cb2ec8ed0b..5b34814331 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/filemanager.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/filemanager.service.js @@ -27,7 +27,7 @@ function fileManager($rootScope) { setFiles: function (args) { //propertyAlias, files - if (!angular.isString(args.propertyAlias)) { + if (!Utilities.isString(args.propertyAlias)) { throw "args.propertyAlias must be a non empty string"; } if (!Utilities.isObject(args.files)) { diff --git a/src/Umbraco.Web.UI.Client/src/common/services/macro.service.js b/src/Umbraco.Web.UI.Client/src/common/services/macro.service.js index bdead487b5..5b79b9c327 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/macro.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/macro.service.js @@ -62,7 +62,7 @@ function macroService() { val = val ? val : ""; //need to detect if the val is a string or an object var keyVal; - if (angular.isString(val)) { + if (Utilities.isString(val)) { keyVal = key + "=\"" + (val ? val : "") + "\" "; } else { diff --git a/src/Umbraco.Web.UI.Client/src/common/services/mediahelper.service.js b/src/Umbraco.Web.UI.Client/src/common/services/mediahelper.service.js index 308ccc8d65..ce2a18c3c0 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/mediahelper.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/mediahelper.service.js @@ -45,7 +45,7 @@ function mediaHelper(umbRequestHelper, $log) { //this performs a simple check to see if we have a media file as value //it doesnt catch everything, but better then nothing - if (angular.isString(item.value) && item.value.indexOf(mediaRoot) === 0) { + if (Utilities.isString(item.value) && item.value.indexOf(mediaRoot) === 0) { return true; } diff --git a/src/Umbraco.Web.UI.Client/src/common/services/navigation.service.js b/src/Umbraco.Web.UI.Client/src/common/services/navigation.service.js index ab9cfb63d2..6401fa3aef 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/navigation.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/navigation.service.js @@ -88,7 +88,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService * @param {any} requestPath */ function pathToRouteParts(requestPath) { - if (!angular.isString(requestPath)) { + if (!Utilities.isString(requestPath)) { throw "The value for requestPath is not a string"; } var pathAndQuery = requestPath.split("#")[1]; @@ -130,11 +130,11 @@ function navigationService($routeParams, $location, $q, $injector, eventsService */ isRouteChangingNavigation: function (currUrlParams, nextUrlParams) { - if (angular.isString(currUrlParams)) { + if (Utilities.isString(currUrlParams)) { currUrlParams = pathToRouteParts(currUrlParams); } - if (angular.isString(nextUrlParams)) { + if (Utilities.isString(nextUrlParams)) { nextUrlParams = pathToRouteParts(nextUrlParams); } @@ -483,14 +483,14 @@ function navigationService($routeParams, $location, $q, $injector, eventsService appState.setMenuState("currentNode", node); - if (action.metaData && action.metaData["actionRoute"] && angular.isString(action.metaData["actionRoute"])) { + if (action.metaData && action.metaData["actionRoute"] && Utilities.isString(action.metaData["actionRoute"])) { //first check if the menu item simply navigates to a route var parts = action.metaData["actionRoute"].split("?"); $location.path(parts[0]).search(parts.length > 1 ? parts[1] : ""); this.hideNavigation(); return; } - else if (action.metaData && action.metaData["jsAction"] && angular.isString(action.metaData["jsAction"])) { + else if (action.metaData && action.metaData["jsAction"] && Utilities.isString(action.metaData["jsAction"])) { //we'll try to get the jsAction from the injector var menuAction = action.metaData["jsAction"].split('.'); diff --git a/src/Umbraco.Web.UI.Client/src/common/services/servervalidationmgr.service.js b/src/Umbraco.Web.UI.Client/src/common/services/servervalidationmgr.service.js index b9bfa51122..e2e51a6c28 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/servervalidationmgr.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/servervalidationmgr.service.js @@ -25,7 +25,7 @@ function serverValidationManager($timeout) { } function getFieldErrors(self, fieldName) { - if (!angular.isString(fieldName)) { + if (!Utilities.isString(fieldName)) { throw "fieldName must be a string"; } @@ -36,10 +36,10 @@ function serverValidationManager($timeout) { } function getPropertyErrors(self, propertyAlias, culture, fieldName) { - if (!angular.isString(propertyAlias)) { + if (!Utilities.isString(propertyAlias)) { throw "propertyAlias must be a string"; } - if (fieldName && !angular.isString(fieldName)) { + if (fieldName && !Utilities.isString(fieldName)) { throw "fieldName must be a string"; } diff --git a/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js b/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js index c36ffdc58a..bfcf4d3532 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js @@ -158,7 +158,7 @@ var currGroups = saveModel.userGroups; var formattedGroups = []; for (var i = 0; i < currGroups.length; i++) { - if (!angular.isString(currGroups[i])) { + if (!Utilities.isString(currGroups[i])) { formattedGroups.push(currGroups[i].alias); } else { @@ -229,7 +229,7 @@ var currSections = saveModel.sections; var formattedSections = []; for (var i = 0; i < currSections.length; i++) { - if (!angular.isString(currSections[i])) { + if (!Utilities.isString(currSections[i])) { formattedSections.push(currSections[i].alias); } else { diff --git a/src/Umbraco.Web.UI.Client/src/common/services/umbrequesthelper.service.js b/src/Umbraco.Web.UI.Client/src/common/services/umbrequesthelper.service.js index d343aea0d2..fc9b8ae40b 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/umbrequesthelper.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/umbrequesthelper.service.js @@ -91,7 +91,7 @@ function umbRequestHelper($http, $q, notificationsService, eventsService, formHe } return Umbraco.Sys.ServerVariables["umbracoUrls"][apiName] + actionName + - (!queryStrings ? "" : "?" + (angular.isString(queryStrings) ? queryStrings : this.dictionaryToQueryString(queryStrings))); + (!queryStrings ? "" : "?" + (Utilities.isString(queryStrings) ? queryStrings : this.dictionaryToQueryString(queryStrings))); }, @@ -129,7 +129,7 @@ function umbRequestHelper($http, $q, notificationsService, eventsService, formHe var err = { //NOTE: the default error message here should never be used based on the above docs! - errorMsg: (angular.isString(opts) ? opts : 'An error occurred!'), + errorMsg: (Utilities.isString(opts) ? opts : 'An error occurred!'), data: data, status: status }; @@ -342,11 +342,11 @@ function umbRequestHelper($http, $q, notificationsService, eventsService, formHe //add the json data if (angular.isArray(data)) { _.each(data, function(item) { - formData.append(item.key, !angular.isString(item.value) ? Utilities.toJson(item.value) : item.value); + formData.append(item.key, !Utilities.isString(item.value) ? Utilities.toJson(item.value) : item.value); }); } else { - formData.append(data.key, !angular.isString(data.value) ? Utilities.toJson(data.value) : data.value); + formData.append(data.key, !Utilities.isString(data.value) ? Utilities.toJson(data.value) : data.value); } //call the callback diff --git a/src/Umbraco.Web.UI.Client/src/navigation.controller.js b/src/Umbraco.Web.UI.Client/src/navigation.controller.js index 281be2d331..425cdb3054 100644 --- a/src/Umbraco.Web.UI.Client/src/navigation.controller.js +++ b/src/Umbraco.Web.UI.Client/src/navigation.controller.js @@ -68,7 +68,7 @@ function NavigationController($scope, $rootScope, $location, $log, $q, $routePar args.event.stopPropagation(); args.event.preventDefault(); - if (n.metaData && n.metaData["jsClickCallback"] && angular.isString(n.metaData["jsClickCallback"]) && n.metaData["jsClickCallback"] !== "") { + if (n.metaData && n.metaData["jsClickCallback"] && Utilities.isString(n.metaData["jsClickCallback"]) && n.metaData["jsClickCallback"] !== "") { //this is a legacy tree node! var jsPrefix = "javascript:"; var js; diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.controller.js index f9e366a4a0..d18660dcb2 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.controller.js @@ -739,7 +739,7 @@ angular.module("umbraco") //if nothing is found, set it to 12 if (!$scope.model.config.items.columns) { $scope.model.config.items.columns = 12; - } else if (angular.isString($scope.model.config.items.columns)) { + } else if (Utilities.isString($scope.model.config.items.columns)) { $scope.model.config.items.columns = parseInt($scope.model.config.items.columns); } diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.controller.js index e3576426a3..68e7ea4f5c 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.controller.js @@ -95,7 +95,7 @@ angular.module('umbraco') //move previously saved value to the editor if ($scope.model.value) { //backwards compat with the old file upload (incase some-one swaps them..) - if (angular.isString($scope.model.value)) { + if (Utilities.isString($scope.model.value)) { setModelValueWithSrc($scope.model.value); } else { @@ -232,7 +232,7 @@ angular.module('umbraco') //this is a fallback in case the cropper has been asssigned a upload field } - else if (angular.isString(property.value)) { + else if (Utilities.isString(property.value)) { if (thumbnail) { if (mediaHelper.detectIfImageByExtension(property.value)) { diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/listview.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/listview.controller.js index 139a2515b5..fd206c1bc5 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/listview.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/listview.controller.js @@ -709,7 +709,7 @@ function listViewController($scope, $interpolate, $routeParams, $injector, $time } function isDate(val) { - if (angular.isString(val)) { + if (Utilities.isString(val)) { return val.match(/^(\d{4})\-(\d{2})\-(\d{2})\ (\d{2})\:(\d{2})\:(\d{2})$/); } return false; diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/rte/rte.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/rte/rte.controller.js index 748d8da1a4..74a70118eb 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/rte/rte.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/rte/rte.controller.js @@ -12,7 +12,7 @@ angular.module("umbraco") $scope.textAreaHtmlId = $scope.model.alias + "_" + String.CreateGuid(); var editorConfig = $scope.model.config ? $scope.model.config.editor : null; - if (!editorConfig || angular.isString(editorConfig)) { + if (!editorConfig || Utilities.isString(editorConfig)) { editorConfig = tinyMceService.defaultPrevalues(); } //make sure there's a max image size diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/rte/rte.prevalues.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/rte/rte.prevalues.controller.js index 47b0215dac..33e2b834f3 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/rte/rte.prevalues.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/rte/rte.prevalues.controller.js @@ -3,7 +3,7 @@ angular.module("umbraco").controller("Umbraco.PrevalueEditors.RteController", var cfg = tinyMceService.defaultPrevalues(); if($scope.model.value){ - if(angular.isString($scope.model.value)){ + if(Utilities.isString($scope.model.value)){ $scope.model.value = cfg; } }else{ diff --git a/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js b/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js index 95313088ee..5eca59d741 100644 --- a/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js +++ b/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js @@ -165,7 +165,7 @@ angular.mock.$Browser.prototype = { if (value == undefined) { delete this.cookieHash[name]; } else { - if (angular.isString(value) && //strings only + if (Utilities.isString(value) && //strings only value.length <= 4096) { //strict cookie storage limits this.cookieHash[name] = value; } @@ -486,7 +486,7 @@ angular.mock.$LogProvider = function () { */ angular.mock.TzDate = function (offset, timestamp) { var self = new Date(0); - if (angular.isString(timestamp)) { + if (Utilities.isString(timestamp)) { var tsStr = timestamp; self.origDate = jsonStringToDate(timestamp); @@ -943,7 +943,7 @@ function createHttpBackendMock($rootScope, $delegate, $browser) { wasExpected = false; function prettyPrint(data) { - return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp) + return (Utilities.isString(data) || angular.isFunction(data) || data instanceof RegExp) ? data : angular.toJson(data); } @@ -1385,7 +1385,7 @@ function MockHttpExpectation(method, url, data, headers) { this.matchData = function (d) { if (angular.isUndefined(data)) return true; if (data && angular.isFunction(data.test)) return data.test(d); - if (data && !angular.isString(data)) return angular.toJson(data) == d; + if (data && !Utilities.isString(data)) return angular.toJson(data) == d; return data == d; }; From b5b319f9176e06f797c8aa5b314f5478c54e1259 Mon Sep 17 00:00:00 2001 From: Mike Masey Date: Fri, 10 Apr 2020 17:34:23 +0100 Subject: [PATCH 19/46] Convert angular.isArray to Utilities.isArray (#7934) --- .../components/application/umbappheader.directive.js | 4 ++-- .../components/forms/checklistmodel.directive.js | 6 +++--- .../directives/components/tags/umbtagseditor.directive.js | 2 +- .../directives/components/tree/umbtree.directive.js | 2 +- .../directives/components/umbmediagrid.directive.js | 2 +- .../directives/validation/valpropertymsg.directive.js | 6 +++--- .../common/directives/validation/valsubview.directive.js | 2 +- .../src/common/interceptors/security.interceptor.js | 2 +- .../src/common/resources/content.resource.js | 4 ++-- .../src/common/services/angularhelper.service.js | 2 +- .../src/common/services/assets.service.js | 2 +- .../src/common/services/filemanager.service.js | 2 +- .../src/common/services/formhelper.service.js | 2 +- .../src/common/services/listviewhelper.service.js | 8 ++++---- .../src/common/services/tinymce.service.js | 2 +- .../src/common/services/tree.service.js | 8 ++++---- .../src/common/services/umbrequesthelper.service.js | 8 ++++---- .../infiniteeditors/macropicker/macropicker.controller.js | 6 +++--- .../infiniteeditors/mediapicker/mediapicker.controller.js | 2 +- .../infiniteeditors/treepicker/treepicker.controller.js | 2 +- .../src/views/documenttypes/create.controller.js | 2 +- .../src/views/prevalueeditors/colorpicker.controller.js | 2 +- .../src/views/prevalueeditors/multivalues.controller.js | 2 +- .../src/views/prevalueeditors/treepicker.controller.js | 2 +- .../propertyeditors/colorpicker/colorpicker.controller.js | 2 +- .../colorpicker/multicolorpicker.controller.js | 2 +- .../contentpicker/contentpicker.controller.js | 4 ++-- .../dropdownFlexible/dropdownFlexible.controller.js | 2 +- .../src/views/propertyeditors/grid/grid.controller.js | 4 ++-- .../views/propertyeditors/listview/listview.controller.js | 2 +- .../memberpicker/memberpicker.controller.js | 2 +- .../relatedlinks/relatedlinks.controller.js | 2 +- .../views/propertyeditors/urllist/urllist.controller.js | 4 ++-- .../test/lib/angular/angular-mocks.js | 2 +- 34 files changed, 54 insertions(+), 54 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js index ead54b3fc3..372a816dd5 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js @@ -31,7 +31,7 @@ if (scope.user.avatars) { scope.avatar = []; - if (angular.isArray(scope.user.avatars)) { + if (Utilities.isArray(scope.user.avatars)) { for (var i = 0; i < scope.user.avatars.length; i++) { scope.avatar.push({ value: scope.user.avatars[i] }); } @@ -46,7 +46,7 @@ if (scope.user.avatars) { scope.avatar = []; - if (angular.isArray(scope.user.avatars)) { + if (Utilities.isArray(scope.user.avatars)) { for (var i = 0; i < scope.user.avatars.length; i++) { scope.avatar.push({ value: scope.user.avatars[i] }); } diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/checklistmodel.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/checklistmodel.directive.js index a89477b001..d944989bab 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/checklistmodel.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/checklistmodel.directive.js @@ -9,7 +9,7 @@ angular.module('umbraco.directives') .directive('checklistModel', ['$parse', '$compile', function($parse, $compile) { // contains function contains(arr, item) { - if (angular.isArray(arr)) { + if (Utilities.isArray(arr)) { for (var i = 0; i < arr.length; i++) { if (angular.equals(arr[i], item)) { return true; @@ -21,7 +21,7 @@ angular.module('umbraco.directives') // add function add(arr, item) { - arr = angular.isArray(arr) ? arr : []; + arr = Utilities.isArray(arr) ? arr : []; for (var i = 0; i < arr.length; i++) { if (angular.equals(arr[i], item)) { return arr; @@ -33,7 +33,7 @@ angular.module('umbraco.directives') // remove function remove(arr, item) { - if (angular.isArray(arr)) { + if (Utilities.isArray(arr)) { for (var i = 0; i < arr.length; i++) { if (angular.equals(arr[i], item)) { arr.splice(i, 1); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/tags/umbtagseditor.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/tags/umbtagseditor.directive.js index aecdcba118..1308515e8e 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/tags/umbtagseditor.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/tags/umbtagseditor.directive.js @@ -191,7 +191,7 @@ } } } - else if (angular.isArray(vm.value)) { + else if (Utilities.isArray(vm.value)) { vm.viewModel = vm.value; } } diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/tree/umbtree.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/tree/umbtree.directive.js index 8825f5daa0..5a7da80eff 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/tree/umbtree.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/tree/umbtree.directive.js @@ -87,7 +87,7 @@ function umbTreeDirective($q, $rootScope, treeService, notificationsService, use /** Helper function to emit tree events */ function emitEvent(eventName, args) { - if (registeredCallbacks[eventName] && angular.isArray(registeredCallbacks[eventName])) { + if (registeredCallbacks[eventName] && Utilities.isArray(registeredCallbacks[eventName])) { _.each(registeredCallbacks[eventName], function (c) { c(args);//call it }); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbmediagrid.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbmediagrid.directive.js index 1c4bf4d583..aa28d49c4a 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbmediagrid.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbmediagrid.directive.js @@ -314,7 +314,7 @@ Use this directive to generate a thumbnail grid of media items. }; var unbindItemsWatcher = scope.$watch('items', function(newValue, oldValue) { - if (angular.isArray(newValue)) { + if (Utilities.isArray(newValue)) { activate(); } }); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/validation/valpropertymsg.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/validation/valpropertymsg.directive.js index 149c2b5087..68ca771eeb 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/validation/valpropertymsg.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/validation/valpropertymsg.directive.js @@ -101,7 +101,7 @@ function valPropertyMsg(serverValidationManager, localizationService) { var errCount = 0; for (var e in formCtrl.$error) { - if (angular.isArray(formCtrl.$error[e])) { + if (Utilities.isArray(formCtrl.$error[e])) { errCount++; } } @@ -111,8 +111,8 @@ function valPropertyMsg(serverValidationManager, localizationService) { // is the only one, then we'll clear. if (errCount === 0 - || (errCount === 1 && angular.isArray(formCtrl.$error.valPropertyMsg)) - || (formCtrl.$invalid && angular.isArray(formCtrl.$error.valServer))) { + || (errCount === 1 && Utilities.isArray(formCtrl.$error.valPropertyMsg)) + || (formCtrl.$invalid && Utilities.isArray(formCtrl.$error.valServer))) { scope.errorMsg = ""; formCtrl.$setValidity('valPropertyMsg', true); } else if (showValidation && scope.errorMsg === "") { diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/validation/valsubview.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/validation/valsubview.directive.js index 524b5f7efe..1f5aaaa1c2 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/validation/valsubview.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/validation/valsubview.directive.js @@ -40,7 +40,7 @@ function link(scope, el, attr, ctrl) { //if there are no containing form or valFormManager controllers, then we do nothing - if (!ctrl || !angular.isArray(ctrl) || ctrl.length !== 2 || !ctrl[0] || !ctrl[1]) { + if (!ctrl || !Utilities.isArray(ctrl) || ctrl.length !== 2 || !ctrl[0] || !ctrl[1]) { return; } diff --git a/src/Umbraco.Web.UI.Client/src/common/interceptors/security.interceptor.js b/src/Umbraco.Web.UI.Client/src/common/interceptors/security.interceptor.js index 30daaf5837..bf748975a1 100644 --- a/src/Umbraco.Web.UI.Client/src/common/interceptors/security.interceptor.js +++ b/src/Umbraco.Web.UI.Client/src/common/interceptors/security.interceptor.js @@ -44,7 +44,7 @@ var headers = config.headers ? config.headers : {}; //Here we'll check if we should ignore the error (either based on the original header set or the request configuration) - if (headers["x-umb-ignore-error"] === "ignore" || config.umbIgnoreErrors === true || (angular.isArray(config.umbIgnoreStatus) && config.umbIgnoreStatus.indexOf(rejection.status) !== -1)) { + if (headers["x-umb-ignore-error"] === "ignore" || config.umbIgnoreErrors === true || (Utilities.isArray(config.umbIgnoreStatus) && config.umbIgnoreStatus.indexOf(rejection.status) !== -1)) { //exit/ignore return $q.reject(rejection); } diff --git a/src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js index 96dcd38f13..7bc2a9d2c8 100644 --- a/src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js +++ b/src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js @@ -1003,10 +1003,10 @@ function contentResource($q, $http, umbDataFormatter, umbRequestHelper) { loginPageId: loginPageId, errorPageId: errorPageId }; - if (angular.isArray(groups) && groups.length) { + if (Utilities.isArray(groups) && groups.length) { publicAccess.groups = groups; } - else if (angular.isArray(usernames) && usernames.length) { + else if (Utilities.isArray(usernames) && usernames.length) { publicAccess.usernames = usernames; } else { diff --git a/src/Umbraco.Web.UI.Client/src/common/services/angularhelper.service.js b/src/Umbraco.Web.UI.Client/src/common/services/angularhelper.service.js index 8cba83328f..f2ff711ac9 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/angularhelper.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/angularhelper.service.js @@ -33,7 +33,7 @@ function angularHelper($q) { //this is sequential promise chaining, it's not pretty but we need to do it this way. //$q.all doesn't execute promises in sequence but that's what we want to do here. - if (!angular.isArray(promises)) { + if (!Utilities.isArray(promises)) { throw "promises must be an array"; } diff --git a/src/Umbraco.Web.UI.Client/src/common/services/assets.service.js b/src/Umbraco.Web.UI.Client/src/common/services/assets.service.js index 6673002981..30e59e9a88 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/assets.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/assets.service.js @@ -256,7 +256,7 @@ angular.module('umbraco.services') load: function (pathArray, scope, defaultAssetType) { var promise; - if (!angular.isArray(pathArray)) { + if (!Utilities.isArray(pathArray)) { throw "pathArray must be an array"; } diff --git a/src/Umbraco.Web.UI.Client/src/common/services/filemanager.service.js b/src/Umbraco.Web.UI.Client/src/common/services/filemanager.service.js index 5b34814331..9e0285d58d 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/filemanager.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/filemanager.service.js @@ -40,7 +40,7 @@ function fileManager($rootScope) { } var metaData = []; - if (angular.isArray(args.metaData)) { + if (Utilities.isArray(args.metaData)) { metaData = args.metaData; } diff --git a/src/Umbraco.Web.UI.Client/src/common/services/formhelper.service.js b/src/Umbraco.Web.UI.Client/src/common/services/formhelper.service.js index 0555318bae..9d84c3c616 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/formhelper.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/formhelper.service.js @@ -83,7 +83,7 @@ function formHelper(angularHelper, serverValidationManager, notificationsService if (!args || !args.notifications) { return false; } - if (angular.isArray(args.notifications)) { + if (Utilities.isArray(args.notifications)) { for (var i = 0; i < args.notifications.length; i++) { notificationsService.showNotification(args.notifications[i]); } diff --git a/src/Umbraco.Web.UI.Client/src/common/services/listviewhelper.service.js b/src/Umbraco.Web.UI.Client/src/common/services/listviewhelper.service.js index 20d014ab0f..28156e70c3 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/listviewhelper.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/listviewhelper.service.js @@ -332,14 +332,14 @@ selection.length = 0; - if (angular.isArray(items)) { + if (Utilities.isArray(items)) { for (i = 0; items.length > i; i++) { var item = items[i]; item.selected = false; } } - if(angular.isArray(folders)) { + if(Utilities.isArray(folders)) { for (i = 0; folders.length > i; i++) { var folder = folders[i]; folder.selected = false; @@ -366,7 +366,7 @@ var checkbox = $event.target; var clearSelection = false; - if (!angular.isArray(items)) { + if (!Utilities.isArray(items)) { return; } @@ -413,7 +413,7 @@ function selectAllItemsToggle(items, selection) { - if (!angular.isArray(items)) { + if (!Utilities.isArray(items)) { return; } diff --git a/src/Umbraco.Web.UI.Client/src/common/services/tinymce.service.js b/src/Umbraco.Web.UI.Client/src/common/services/tinymce.service.js index d2b91a3707..66f0b110bf 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/tinymce.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/tinymce.service.js @@ -480,7 +480,7 @@ function tinyMceService($rootScope, $q, imageHelper, $locale, $http, $timeout, s //now we need to check if this custom config key is defined in our baseline, if it is we don't want to //overwrite the baseline config item if it is an array, we want to concat the items in the array, otherwise //if it's an object it will overwrite the baseline - if (angular.isArray(config[i]) && angular.isArray(tinyMceConfig.customConfig[i])) { + if (Utilities.isArray(config[i]) && Utilities.isArray(tinyMceConfig.customConfig[i])) { //concat it and below this concat'd array will overwrite the baseline in angular.extend tinyMceConfig.customConfig[i] = config[i].concat(tinyMceConfig.customConfig[i]); } diff --git a/src/Umbraco.Web.UI.Client/src/common/services/tree.service.js b/src/Umbraco.Web.UI.Client/src/common/services/tree.service.js index 3c9846fc43..0d6216f7cc 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/tree.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/tree.service.js @@ -47,7 +47,7 @@ function treeService($q, treeResource, iconHelper, notificationsService, eventsS /** Internal method to track expanded paths on a tree */ _trackExpandedPaths: function (node, expandedPaths) { - if (!node.children || !angular.isArray(node.children) || node.children.length == 0) { + if (!node.children || !Utilities.isArray(node.children) || node.children.length == 0) { return; } @@ -174,7 +174,7 @@ function treeService($q, treeResource, iconHelper, notificationsService, eventsS //we determine this based on the server variables if (Umbraco.Sys.ServerVariables.umbracoPlugins && Umbraco.Sys.ServerVariables.umbracoPlugins.trees && - angular.isArray(Umbraco.Sys.ServerVariables.umbracoPlugins.trees)) { + Utilities.isArray(Umbraco.Sys.ServerVariables.umbracoPlugins.trees)) { var found = _.find(Umbraco.Sys.ServerVariables.umbracoPlugins.trees, function (item) { return invariantEquals(item.alias, treeAlias); @@ -473,7 +473,7 @@ function treeService($q, treeResource, iconHelper, notificationsService, eventsS for (var i = 0; i < treeNode.children.length; i++) { var child = treeNode.children[i]; - if (child.children && angular.isArray(child.children) && child.children.length > 0) { + if (child.children && Utilities.isArray(child.children) && child.children.length > 0) { //recurse found = this.getDescendantNode(child, id); if (found) { @@ -773,7 +773,7 @@ function treeService($q, treeResource, iconHelper, notificationsService, eventsS if (!args.path) { throw "No path defined on args object for syncTree"; } - if (!angular.isArray(args.path)) { + if (!Utilities.isArray(args.path)) { throw "Path must be an array"; } if (args.path.length < 1) { diff --git a/src/Umbraco.Web.UI.Client/src/common/services/umbrequesthelper.service.js b/src/Umbraco.Web.UI.Client/src/common/services/umbrequesthelper.service.js index fc9b8ae40b..edf698c8a7 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/umbrequesthelper.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/umbrequesthelper.service.js @@ -44,7 +44,7 @@ function umbRequestHelper($http, $q, notificationsService, eventsService, formHe */ dictionaryToQueryString: function (queryStrings) { - if (angular.isArray(queryStrings)) { + if (Utilities.isArray(queryStrings)) { return _.map(queryStrings, function (item) { var key = null; var val = null; @@ -254,7 +254,7 @@ function umbRequestHelper($http, $q, notificationsService, eventsService, formHe // so we know which property it belongs to on the server side var fileKey = "file_" + args.files[f].alias + "_" + (args.files[f].culture ? args.files[f].culture : ""); - if (angular.isArray(args.files[f].metaData) && args.files[f].metaData.length > 0) { + if (Utilities.isArray(args.files[f].metaData) && args.files[f].metaData.length > 0) { fileKey += ("_" + args.files[f].metaData.join("_")); } formData.append(fileKey, args.files[f].file); @@ -322,7 +322,7 @@ function umbRequestHelper($http, $q, notificationsService, eventsService, formHe //validate input, jsonData can be an array of key/value pairs or just one key/value pair. if (!jsonData) { throw "jsonData cannot be null"; } - if (angular.isArray(jsonData)) { + if (Utilities.isArray(jsonData)) { _.each(jsonData, function (item) { if (!item.key || !item.value) { throw "jsonData array item must have both a key and a value property"; } }); @@ -340,7 +340,7 @@ function umbRequestHelper($http, $q, notificationsService, eventsService, formHe transformRequest: function(data) { var formData = new FormData(); //add the json data - if (angular.isArray(data)) { + if (Utilities.isArray(data)) { _.each(data, function(item) { formData.append(item.key, !Utilities.isString(item.value) ? Utilities.toJson(item.value) : item.value); }); diff --git a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/macropicker/macropicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/macropicker/macropicker.controller.js index dfc77f786c..b4a8f36444 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/macropicker/macropicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/macropicker/macropicker.controller.js @@ -42,7 +42,7 @@ function MacroPickerController($scope, entityResource, macroResource, umbPropEdi .then(function (data) { //go to next page if there are params otherwise we can just exit - if (!angular.isArray(data) || data.length === 0) { + if (!Utilities.isArray(data) || data.length === 0) { if (insertIfNoParameters) { $scope.model.submit($scope.model); @@ -104,12 +104,12 @@ function MacroPickerController($scope, entityResource, macroResource, umbPropEdi entityResource.getAll("Macro", ($scope.model.dialogData && $scope.model.dialogData.richTextEditor && $scope.model.dialogData.richTextEditor === true) ? "UseInEditor=true" : null) .then(function (data) { - if (angular.isArray(data) && data.length == 0) { + if (Utilities.isArray(data) && data.length == 0) { $scope.nomacros = true; } //if 'allowedMacros' is specified, we need to filter - if (angular.isArray($scope.model.dialogData.allowedMacros) && $scope.model.dialogData.allowedMacros.length > 0) { + if (Utilities.isArray($scope.model.dialogData.allowedMacros) && $scope.model.dialogData.allowedMacros.length > 0) { $scope.macros = _.filter(data, function(d) { return _.contains($scope.model.dialogData.allowedMacros, d.alias); }); diff --git a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js index 6728486a0d..62b675b28b 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js @@ -497,7 +497,7 @@ angular.module("umbraco") var folderImage = $scope.images[folderIndex]; var imageIsSelected = false; - if ($scope.model && angular.isArray($scope.model.selection)) { + if ($scope.model && Utilities.isArray($scope.model.selection)) { for (var selectedIndex = 0; selectedIndex < $scope.model.selection.length; selectedIndex++) { diff --git a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/treepicker/treepicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/treepicker/treepicker.controller.js index 4679e7748b..e2e16f111c 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/treepicker/treepicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/treepicker/treepicker.controller.js @@ -271,7 +271,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", openMiniListView(args.node); } - if (angular.isArray(args.children)) { + if (Utilities.isArray(args.children)) { //iterate children _.each(args.children, diff --git a/src/Umbraco.Web.UI.Client/src/views/documenttypes/create.controller.js b/src/Umbraco.Web.UI.Client/src/views/documenttypes/create.controller.js index e1334aa816..732aa898a7 100644 --- a/src/Umbraco.Web.UI.Client/src/views/documenttypes/create.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/documenttypes/create.controller.js @@ -97,7 +97,7 @@ function DocumentTypesCreateController($scope, $location, navigationService, con $scope.error = err; //show any notifications - if (angular.isArray(err.data.notifications)) { + if (Utilities.isArray(err.data.notifications)) { for (var i = 0; i < err.data.notifications.length; i++) { notificationsService.showNotification(err.data.notifications[i]); } diff --git a/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/colorpicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/colorpicker.controller.js index b4381b699b..9ad2c87ab4 100644 --- a/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/colorpicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/colorpicker.controller.js @@ -19,7 +19,7 @@ angular.module("umbraco").controller("Umbraco.PrevalueEditors.ColorPickerControl // Make an array from the dictionary var items = []; - if (angular.isArray($scope.model.prevalues)) { + if (Utilities.isArray($scope.model.prevalues)) { for (var i in $scope.model.prevalues) { var oldValue = $scope.model.prevalues[i]; diff --git a/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/multivalues.controller.js b/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/multivalues.controller.js index 3da57943f9..c37c382dac 100644 --- a/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/multivalues.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/multivalues.controller.js @@ -7,7 +7,7 @@ angular.module("umbraco").controller("Umbraco.PrevalueEditors.MultiValuesControl $scope.hasError = false; $scope.focusOnNew = false; - if (!angular.isArray($scope.model.value)) { + if (!Utilities.isArray($scope.model.value)) { //make an array from the dictionary var items = []; diff --git a/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/treepicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/treepicker.controller.js index 951b76193f..0359043da4 100644 --- a/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/treepicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/prevalueeditors/treepicker.controller.js @@ -118,7 +118,7 @@ angular.module('umbraco') } function populate(data) { - if (angular.isArray(data)) { + if (Utilities.isArray(data)) { _.each(data, function (item, i) { $scope.add(item); }); diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/colorpicker/colorpicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/colorpicker/colorpicker.controller.js index ba2ad72191..e2f502e463 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/colorpicker/colorpicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/colorpicker/colorpicker.controller.js @@ -25,7 +25,7 @@ function ColorPickerController($scope, $timeout) { initActiveColor(); } - if (!angular.isArray($scope.model.config.items)) { + if (!Utilities.isArray($scope.model.config.items)) { //make an array from the dictionary var items = []; for (var i in $scope.model.config.items) { diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/colorpicker/multicolorpicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/colorpicker/multicolorpicker.controller.js index 91c6e673b9..2cbad88a43 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/colorpicker/multicolorpicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/colorpicker/multicolorpicker.controller.js @@ -55,7 +55,7 @@ }); }); - if (!angular.isArray($scope.model.value)) { + if (!Utilities.isArray($scope.model.value)) { //make an array from the dictionary var items = []; for (var i in $scope.model.value) { diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js index 5df324c60f..238872db40 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/contentpicker/contentpicker.controller.js @@ -152,7 +152,7 @@ function contentPickerController($scope, entityResource, editorState, iconHelper dataTypeKey: $scope.model.dataTypeKey, currentNode: editorState ? editorState.current : null, callback: function (data) { - if (angular.isArray(data)) { + if (Utilities.isArray(data)) { _.each(data, function (item, i) { $scope.add(item); }); @@ -233,7 +233,7 @@ function contentPickerController($scope, entityResource, editorState, iconHelper $scope.currentPicker = dialogOptions; $scope.currentPicker.submit = function (model) { - if (angular.isArray(model.selection)) { + if (Utilities.isArray(model.selection)) { _.each(model.selection, function (item, i) { $scope.add(item); }); diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/dropdownFlexible/dropdownFlexible.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/dropdownFlexible/dropdownFlexible.controller.js index 0f530ae5ee..a8979c949b 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/dropdownFlexible/dropdownFlexible.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/dropdownFlexible/dropdownFlexible.controller.js @@ -45,7 +45,7 @@ angular.module("umbraco").controller("Umbraco.PropertyEditors.DropdownFlexibleCo $scope.model.value = [$scope.model.singleDropdownValue]; } - if (angular.isArray($scope.model.config.items)) { + if (Utilities.isArray($scope.model.config.items)) { //PP: I dont think this will happen, but we have tests that expect it to happen.. //if array is simple values, convert to array of objects if (!Utilities.isObject($scope.model.config.items[0])){ diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.controller.js index d18660dcb2..10b2f19e83 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.controller.js @@ -745,7 +745,7 @@ angular.module("umbraco") if ($scope.model.value && $scope.model.value.sections && $scope.model.value.sections.length > 0 && $scope.model.value.sections[0].rows && $scope.model.value.sections[0].rows.length > 0) { - if ($scope.model.value.name && angular.isArray($scope.model.config.items.templates)) { + if ($scope.model.value.name && Utilities.isArray($scope.model.config.items.templates)) { //This will occur if it is an existing value, in which case // we need to determine which layout was applied by looking up @@ -756,7 +756,7 @@ angular.module("umbraco") return t.name === $scope.model.value.name; }); - if (found && angular.isArray(found.sections) && found.sections.length === $scope.model.value.sections.length) { + if (found && Utilities.isArray(found.sections) && found.sections.length === $scope.model.value.sections.length) { //Cool, we've found the template associated with our current value with matching sections counts, now we need to // merge this template data on to our current value (as if it was new) so that we can preserve what is and isn't diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/listview.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/listview.controller.js index fd206c1bc5..16c1be98a0 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/listview.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/listview/listview.controller.js @@ -382,7 +382,7 @@ function listViewController($scope, $interpolate, $routeParams, $injector, $time return serial(selected, fn, getStatusMsg, 0).then(function (result) { // executes once the whole selection has been processed // in case of an error (caught by serial), result will be the error - if (!(result.data && angular.isArray(result.data.notifications))) + if (!(result.data && Utilities.isArray(result.data.notifications))) showNotificationsAndReset(result, true, getSuccessMsg(selected.length)); }); } diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/memberpicker/memberpicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/memberpicker/memberpicker.controller.js index c3acf020b8..95e595a97a 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/memberpicker/memberpicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/memberpicker/memberpicker.controller.js @@ -20,7 +20,7 @@ function memberPickerController($scope, entityResource, iconHelper, angularHelpe }, filterCssClass: "not-allowed", callback: function(data) { - if (angular.isArray(data)) { + if (Utilities.isArray(data)) { _.each(data, function (item, i) { $scope.add(item); }); diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/relatedlinks/relatedlinks.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/relatedlinks/relatedlinks.controller.js index 6a5a76b800..e642051733 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/relatedlinks/relatedlinks.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/relatedlinks/relatedlinks.controller.js @@ -80,7 +80,7 @@ }; $scope.add = function ($event) { - if (!angular.isArray($scope.model.value)) { + if (!Utilities.isArray($scope.model.value)) { $scope.model.value = []; } diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/urllist/urllist.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/urllist/urllist.controller.js index b147c4620b..1b913d7014 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/urllist/urllist.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/urllist/urllist.controller.js @@ -2,7 +2,7 @@ angular.module('umbraco').controller("Umbraco.PropertyEditors.UrlListController" function($rootScope, $scope, $filter) { function formatDisplayValue() { - if (angular.isArray($scope.model.value)) { + if (Utilities.isArray($scope.model.value)) { //it's the json value $scope.renderModel = _.map($scope.model.value, function (item) { return { @@ -42,4 +42,4 @@ angular.module('umbraco').controller("Umbraco.PropertyEditors.UrlListController" formatDisplayValue(); }; - }); \ No newline at end of file + }); diff --git a/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js b/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js index 5eca59d741..965fcdce71 100644 --- a/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js +++ b/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js @@ -692,7 +692,7 @@ angular.mock.dump = function (object) { out.append(angular.element(element).clone()); }); out = out.html(); - } else if (angular.isArray(object)) { + } else if (Utilities.isArray(object)) { out = []; angular.forEach(object, function (o) { out.push(serialize(o)); From 23e32d2b5921ee5fe53db483fd1859417bffe5cb Mon Sep 17 00:00:00 2001 From: Mike Masey Date: Fri, 10 Apr 2020 19:42:43 +0100 Subject: [PATCH 20/46] improvement: update umb-tabs to use better semantic markup (#7926) --- .../components/application/umb-dashboard.less | 2 +- .../src/less/components/umb-tabs.less | 61 ++++++++++--------- .../views/components/tabs/umb-tabs-nav.html | 15 +++-- src/Umbraco.Web.UI/Umbraco/config/lang/en.xml | 3 +- .../Umbraco/config/lang/en_us.xml | 1 + 5 files changed, 46 insertions(+), 36 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/less/components/application/umb-dashboard.less b/src/Umbraco.Web.UI.Client/src/less/components/application/umb-dashboard.less index 52ff2c2b01..03153973ff 100644 --- a/src/Umbraco.Web.UI.Client/src/less/components/application/umb-dashboard.less +++ b/src/Umbraco.Web.UI.Client/src/less/components/application/umb-dashboard.less @@ -31,6 +31,6 @@ border: none; } -.umb-dashboard__header .umb-tabs-nav .umb-tab > a { +.umb-dashboard__header .umb-tabs-nav .umb-tab > .umb-tab-button { padding-bottom: 25px; } diff --git a/src/Umbraco.Web.UI.Client/src/less/components/umb-tabs.less b/src/Umbraco.Web.UI.Client/src/less/components/umb-tabs.less index ee784787fa..15b317aa45 100644 --- a/src/Umbraco.Web.UI.Client/src/less/components/umb-tabs.less +++ b/src/Umbraco.Web.UI.Client/src/less/components/umb-tabs.less @@ -13,25 +13,31 @@ top: 1px; } -.umb-tab > a { - +.umb-tab-button { display: flex; justify-content: center; align-items: center; position: relative; - + cursor: pointer; //border-bottom: 4px solid transparent; color: @ui-light-type; padding: 5px 20px 15px 20px; transition: color 150ms ease-in-out; + &:focus { color: @ui-light-type-hover; + + body:not(.tabbing-active) &{ + outline: none; + } } + &:hover { color: @ui-light-type-hover; text-decoration: none; } + &::after { content: ""; height: 0px; @@ -42,12 +48,21 @@ bottom: 0; border-radius: 3px 3px 0 0; opacity: 0; - transition: all .2s linear; + transition: all 0.2s linear; + } + + &--expand > i { + height: 5px; + width: 5px; + border-radius: 50%; + background: @black; + display: inline-block; + margin: 0 5px 0 0; + opacity: 0.6; } } - -.umb-tab--active > a { +.umb-tab--active > .umb-tab-button { color: @ui-light-active-type; //border-bottom-color: @ui-active; /* @@ -64,19 +79,19 @@ } } -.show-validation .umb-tab--error > a, -.show-validation .umb-tab--error > a:hover, -.show-validation .umb-tab--error > a:focus { - color: @white !important; - background-color: @red !important; - border-color: @errorBorder; +.show-validation .umb-tab--error > .umb-tab-button, +.show-validation .umb-tab--error > .umb-tab-button:hover, +.show-validation .umb-tab--error > .umb-tab-button:focus { + color: @white !important; + background-color: @red !important; + border-color: @errorBorder; } -.show-validation .umb-tab--error a:before { - content: "\e25d"; - font-family: 'icomoon'; - margin-right: 5px; - vertical-align: top; +.show-validation .umb-tab--error .umb-tab-button:before { + content: "\e25d"; + font-family: "icomoon"; + margin-right: 5px; + vertical-align: top; } // tabs tray @@ -86,20 +101,10 @@ left: auto; } -.umb-tabs-tray > a { +.umb-tabs-tray > .umb-tab-button { cursor: pointer; } .umb-tabs-tray-item--active { border-left: 2px solid @ui-active; } - -.umb-tab--expand > a > i { - height: 5px; - width: 5px; - border-radius: 50%; - background: @black; - display: inline-block; - margin: 0 5px 0 0; - opacity: .6; -} diff --git a/src/Umbraco.Web.UI.Client/src/views/components/tabs/umb-tabs-nav.html b/src/Umbraco.Web.UI.Client/src/views/components/tabs/umb-tabs-nav.html index bc0f2cb001..36a9271818 100644 --- a/src/Umbraco.Web.UI.Client/src/views/components/tabs/umb-tabs-nav.html +++ b/src/Umbraco.Web.UI.Client/src/views/components/tabs/umb-tabs-nav.html @@ -1,13 +1,16 @@
    -
  • +
  • -
  • - +
  • + - - {{ tab.label }} + +
  • diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml index dc8dc0d7ef..9457ea9271 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml @@ -2223,7 +2223,8 @@ To manage your website, simply open the Umbraco back office and start adding con Create Edit Name - Add new row + Add new row + View more options References diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml index 7a3ec88bd3..4e254d1681 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml @@ -2236,6 +2236,7 @@ To manage your website, simply open the Umbraco back office and start adding con Edit Name Add new row + View more options References From 18e4299fb3ce45ac82c425a5903f09719735834f Mon Sep 17 00:00:00 2001 From: Carole Rennie Logan Date: Fri, 10 Apr 2020 16:51:47 +0100 Subject: [PATCH 21/46] Adding Git command line to contrib guidelines Adding Git command line to contrib guidelines after an issue someone had at #canConHackathon --- .github/CONTRIBUTING.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 5634b5bda5..e85c0add9c 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -126,6 +126,7 @@ In order to build the Umbraco source code locally, first make sure you have the * Visual Studio 2017 v15.9.7+ * Node v10+ * npm v6.4.1+ + * Git command line The easiest way to get started is to open `src\umbraco.sln` in Visual Studio 2017 (version 15.9.7 or higher, [the community edition is free](https://www.visualstudio.com/thank-you-downloading-visual-studio/?sku=Community&rel=15) for you to use to contribute to Open Source projects). In Visual Studio, find the Task Runner Explorer (in the View menu under Other Windows) and run the build task under the gulpfile. From 7a1bd34fa5716ff54d8fe0080470b19d0af25665 Mon Sep 17 00:00:00 2001 From: BatJan Date: Sat, 11 Apr 2020 00:35:31 +0200 Subject: [PATCH 22/46] Remove code that does UA sniffing and explicit stuff for IE11 only --- .../forms/umbautoresize.directive.js | 233 ++++++------------ 1 file changed, 80 insertions(+), 153 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbautoresize.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbautoresize.directive.js index 69ec1be805..2ec3960a59 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbautoresize.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbautoresize.directive.js @@ -1,161 +1,88 @@ angular.module("umbraco.directives") - .directive('umbAutoResize', function($timeout) { - return { - require: ["^?umbTabs", "ngModel"], - link: function(scope, element, attr, controllersArr) { + .directive('umbAutoResize', function ($timeout) { + return { + require: ["^?umbTabs", "ngModel"], + link: function (scope, element, attr, controllersArr) { - var domEl = element[0]; - var domElType = domEl.type; - var umbTabsController = controllersArr[0]; - var ngModelController = controllersArr[1]; + var domEl = element[0]; + var domElType = domEl.type; + var umbTabsController = controllersArr[0]; + var ngModelController = controllersArr[1]; - // IE elements - var isIEFlag = false; - var wrapper = angular.element('#umb-ie-resize-input-wrapper'); - var mirror = angular.element(''); + function resizeInput() { - function isIE() { - - var ua = window.navigator.userAgent; - var msie = ua.indexOf("MSIE "); - - if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./) || navigator.userAgent.match(/Edge\/\d+/)) { - return true; - } else { - return false; - } - - } - - function activate() { - - // check if browser is Internet Explorere - isIEFlag = isIE(); - - // scrollWidth on element does not work in IE on inputs - // we have to do some dirty dom element copying. - if (isIEFlag === true && domElType === "text") { - setupInternetExplorerElements(); - } - - } - - function setupInternetExplorerElements() { - - if (!wrapper.length) { - wrapper = angular.element('
    '); - angular.element('body').append(wrapper); - } - - angular.forEach(['fontFamily', 'fontSize', 'fontWeight', 'fontStyle', - 'letterSpacing', 'textTransform', 'wordSpacing', 'textIndent', - 'boxSizing', 'borderRightWidth', 'borderLeftWidth', 'borderLeftStyle', 'borderRightStyle', - 'paddingLeft', 'paddingRight', 'marginLeft', 'marginRight' - ], function(value) { - mirror.css(value, element.css(value)); - }); - - wrapper.append(mirror); - - } - - function resizeInternetExplorerInput() { - - mirror.text(element.val() || attr.placeholder); - element.css('width', mirror.outerWidth() + 1); - - } - - function resizeInput() { - - if (domEl.scrollWidth !== domEl.clientWidth) { - if (ngModelController.$modelValue) { - element.width(domEl.scrollWidth); - } - } - - if(!ngModelController.$modelValue && attr.placeholder) { - attr.$set('size', attr.placeholder.length); - element.width('auto'); - } - - } - - function resizeTextarea() { - - if(domEl.scrollHeight !== domEl.clientHeight) { - - element.height(domEl.scrollHeight); - - } - - } - - var update = function(force) { - - - if (force === true) { - - if (domElType === "textarea") { - element.height(0); - } else if (domElType === "text") { - element.width(0); - } - - } - - - if (isIEFlag === true && domElType === "text") { - - resizeInternetExplorerInput(); - - } else { - - if (domElType === "textarea") { - - resizeTextarea(); - - } else if (domElType === "text") { - - resizeInput(); - - } - - } - - }; - - activate(); - - //listen for tab changes - if (umbTabsController != null) { - umbTabsController.onTabShown(function(args) { - update(); - }); - } - - // listen for ng-model changes - var unbindModelWatcher = scope.$watch(function() { - return ngModelController.$modelValue; - }, function(newValue) { - $timeout( - function() { - update(true); + if (domEl.scrollWidth !== domEl.clientWidth) { + if (ngModelController.$modelValue) { + element.width(domEl.scrollWidth); + } } - ); - }); - scope.$on('$destroy', function() { - element.off('keyup keydown keypress change', update); - element.off('blur', update(true)); - unbindModelWatcher(); + if (!ngModelController.$modelValue && attr.placeholder) { + attr.$set('size', attr.placeholder.length); + element.width('auto'); + } - // clean up IE dom element - if (isIEFlag === true && domElType === "text") { - mirror.remove(); - } + } - }); - } - }; - }); + function resizeTextarea() { + + if (domEl.scrollHeight !== domEl.clientHeight) { + + element.height(domEl.scrollHeight); + + } + + } + + var update = function (force) { + + + if (force === true) { + + if (domElType === "textarea") { + element.height(0); + } else if (domElType === "text") { + element.width(0); + } + + } + + + if (domElType === "textarea") { + + resizeTextarea(); + + } else if (domElType === "text") { + + resizeInput(); + + } + + }; + + //listen for tab changes + if (umbTabsController != null) { + umbTabsController.onTabShown(function (args) { + update(); + }); + } + + // listen for ng-model changes + var unbindModelWatcher = scope.$watch(function () { + return ngModelController.$modelValue; + }, function (newValue) { + $timeout( + function () { + update(true); + } + ); + }); + + scope.$on('$destroy', function () { + element.off('keyup keydown keypress change', update); + element.off('blur', update(true)); + unbindModelWatcher(); + }); + } + }; + }); From d6723554fc8394e1816face752f89f1b98121500 Mon Sep 17 00:00:00 2001 From: James Wilkinson Date: Tue, 14 Apr 2020 08:50:48 +0100 Subject: [PATCH 23/46] =?UTF-8?q?Added=20links=20to=20the=20required=20too?= =?UTF-8?q?ls.=20Added=20more=20detail=20to=20the=20PR=E2=80=A6=20(#7944)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/CONTRIBUTING.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index e85c0add9c..5537a46ef8 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -72,7 +72,7 @@ Great question! The short version goes like this: ### Pull requests The most successful pull requests usually look a like this: - * Fill in the required template, linking your pull request to an issue on the [issue tracker,](https://github.com/umbraco/Umbraco-CMS/issues) if applicable. + * Fill in the required template (shown when starting a PR on GitHub), and link your pull request to an issue on the [issue tracker,](https://github.com/umbraco/Umbraco-CMS/issues) if applicable. * Include screenshots and animated GIFs in your pull request whenever possible. * Unit tests, while optional, are awesome. Thank you! * New code is commented with documentation from which [the reference documentation](https://our.umbraco.com/documentation/Reference/) is generated. @@ -123,10 +123,10 @@ You can get in touch with [the core contributors team](#the-core-contributors-te In order to build the Umbraco source code locally, first make sure you have the following installed. - * Visual Studio 2017 v15.9.7+ - * Node v10+ - * npm v6.4.1+ - * Git command line + * [Visual Studio 2017 v15.9.7+](https://visualstudio.microsoft.com/vs/) + * [Node.js v10+](https://nodejs.org/en/download/) + * npm v6.4.1+ (installed with Node.js) + * [Git command line](https://git-scm.com/download/) The easiest way to get started is to open `src\umbraco.sln` in Visual Studio 2017 (version 15.9.7 or higher, [the community edition is free](https://www.visualstudio.com/thank-you-downloading-visual-studio/?sku=Community&rel=15) for you to use to contribute to Open Source projects). In Visual Studio, find the Task Runner Explorer (in the View menu under Other Windows) and run the build task under the gulpfile. From 021b39378a9d8302fe9a431372128274de9206c3 Mon Sep 17 00:00:00 2001 From: BatJan Date: Sun, 12 Apr 2020 00:46:56 +0200 Subject: [PATCH 24/46] Remove unused directive --- .../components/umbpasswordtoggle.directive.js | 37 ------------------- 1 file changed, 37 deletions(-) delete mode 100644 src/Umbraco.Web.UI.Client/src/common/directives/components/umbpasswordtoggle.directive.js diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbpasswordtoggle.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbpasswordtoggle.directive.js deleted file mode 100644 index aac1b8dac1..0000000000 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbpasswordtoggle.directive.js +++ /dev/null @@ -1,37 +0,0 @@ -/** -@ngdoc directive -@name umbraco.directives.directive:umbPasswordToggle -@restrict E -@scope - -@description -Added in Umbraco v. 7.7.4: Use this directive to render a password toggle. - -**/ - -(function () { - 'use strict'; - - // comes from https://codepen.io/jakob-e/pen/eNBQaP - // works fine with Angular 1.6.5 - alas not with 1.1.5 - binding issue - - function PasswordToggleDirective($compile) { - - var directive = { - restrict: 'A', - scope: {}, - link: function(scope, elem, attrs) { - scope.tgl = function () { elem.attr("type", (elem.attr("type") === "text" ? "password" : "text")); } - var lnk = angular.element("Toggle"); - $compile(lnk)(scope); - elem.wrap("
    ").after(lnk); - } - }; - - return directive; - - } - - angular.module('umbraco.directives').directive('umbPasswordToggle', PasswordToggleDirective); - -})(); From d74d9ffb2b16b1bbd67531121ab1a86d2cc807de Mon Sep 17 00:00:00 2001 From: Jan Skovgaard Date: Tue, 14 Apr 2020 10:14:25 +0200 Subject: [PATCH 25/46] Replace instances of angular.forEach with vanilla JS forEach (#7928) --- .../localization/localize.directive.js | 20 +++---- .../umbkeyboardshortcutsoverview.directive.js | 33 ++++++----- .../src/common/services/tour.service.js | 41 +++++++------- .../src/navigation.controller.js | 23 ++++---- .../mediapicker/mediapicker.controller.js | 48 ++++++++-------- .../settings/healthcheck.controller.js | 55 +++++++++---------- 6 files changed, 111 insertions(+), 109 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/localization/localize.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/localization/localize.directive.js index df3770056e..34bfb01019 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/localization/localize.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/localization/localize.directive.js @@ -30,7 +30,7 @@ angular.module("umbraco.directives") .directive('localize', function ($log, localizationService) { return { restrict: 'E', - scope:{ + scope: { key: '@', tokens: '=', watchTokens: '@' @@ -40,13 +40,13 @@ angular.module("umbraco.directives") link: function (scope, element, attrs) { var key = scope.key; scope.text = ""; - + // A render function to be able to update tokens as values update. function render() { element.html(localizationService.tokenReplace(scope.text, scope.tokens || null)); } - - localizationService.localize(key).then(function(value){ + + localizationService.localize(key).then(function (value) { scope.text = value; render(); }); @@ -64,19 +64,19 @@ angular.module("umbraco.directives") //Support one or more attribute properties to update var keys = attrs.localize.split(','); - angular.forEach(keys, function(value, key){ + keys.forEach((value, key) => { var attr = element.attr(value); - if(attr){ - if(attr[0] === '@'){ + if (attr) { + if (attr[0] === '@') { //If the translation key starts with @ then remove it attr = attr.substring(1); } var t = localizationService.tokenize(attr, scope); - - localizationService.localize(t.key, t.tokens).then(function(val){ - element.attr(value, val); + + localizationService.localize(t.key, t.tokens).then(function (val) { + element.attr(value, val); }); } }); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbkeyboardshortcutsoverview.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbkeyboardshortcutsoverview.directive.js index 953a28bd99..2d3db7c162 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbkeyboardshortcutsoverview.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbkeyboardshortcutsoverview.directive.js @@ -120,26 +120,26 @@ When this combination is hit an overview is opened with shortcuts based on the m scope.toggleShortcutsOverlay = function () { - if(overlay) { + if (overlay) { scope.close(); } else { scope.open(); } - if(scope.onToggle) { + if (scope.onToggle) { scope.onToggle(); } }; - scope.open = function() { - if(!overlay) { + scope.open = function () { + if (!overlay) { overlay = { title: "Keyboard shortcuts", view: "keyboardshortcuts", hideSubmitButton: true, shortcuts: scope.model, - close: function() { + close: function () { scope.close(); } }; @@ -147,20 +147,20 @@ When this combination is hit an overview is opened with shortcuts based on the m } }; - scope.close = function() { - if(overlay) { + scope.close = function () { + if (overlay) { overlayService.close(); overlay = null; - if(scope.onClose) { + if (scope.onClose) { scope.onClose(); } } }; function onInit() { - angular.forEach(scope.model, function (shortcutGroup) { - angular.forEach(shortcutGroup.shortcuts, function (shortcut) { + scope.model.forEach(shortcutGroup => { + shortcutGroup.shortcuts.forEach(shortcut => { shortcut.platformKeys = []; // get shortcut keys for mac @@ -173,30 +173,29 @@ When this combination is hit an overview is opened with shortcuts based on the m } else if (shortcut.keys && shortcut && shortcut.keys.length > 0) { shortcut.platformKeys = shortcut.keys; } - - }); + }) }); } onInit(); - eventBindings.push(scope.$watch('model', function(newValue, oldValue){ + eventBindings.push(scope.$watch('model', function (newValue, oldValue) { if (newValue !== oldValue) { onInit(); } })); - eventBindings.push(scope.$watch('showOverlay', function(newValue, oldValue){ + eventBindings.push(scope.$watch('showOverlay', function (newValue, oldValue) { - if(newValue === oldValue) { + if (newValue === oldValue) { return; } - if(newValue === true) { + if (newValue === true) { scope.open(); } - if(newValue === false) { + if (newValue === false) { scope.close(); } diff --git a/src/Umbraco.Web.UI.Client/src/common/services/tour.service.js b/src/Umbraco.Web.UI.Client/src/common/services/tour.service.js index 8fcab445b3..a11a9d6c82 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/tour.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/tour.service.js @@ -9,7 +9,7 @@ 'use strict'; function tourService(eventsService, currentUserResource, $q, tourResource) { - + var tours = []; var currentTour = null; @@ -18,14 +18,16 @@ */ function registerAllTours() { tours = []; - return tourResource.getTours().then(function(tourFiles) { - angular.forEach(tourFiles, function (tourFile) { - angular.forEach(tourFile.tours, function(newTour) { + return tourResource.getTours().then(function (tourFiles) { + tourFiles.forEach(tourFile => { + + tourFile.tours.forEach(newTour => { validateTour(newTour); validateTourRegistration(newTour); - tours.push(newTour); + tours.push(newTour); }); }); + eventsService.emit("appState.tour.updatedTours", tours); }); } @@ -74,7 +76,7 @@ tour.disabled = true; currentUserResource .saveTourStatus({ alias: tour.alias, disabled: tour.disabled, completed: tour.completed }).then( - function() { + function () { eventsService.emit("appState.tour.end", tour); currentTour = null; deferred.resolve(tour); @@ -96,7 +98,7 @@ tour.completed = true; currentUserResource .saveTourStatus({ alias: tour.alias, disabled: tour.disabled, completed: tour.completed }).then( - function() { + function () { eventsService.emit("appState.tour.complete", tour); currentTour = null; deferred.resolve(tour); @@ -130,10 +132,10 @@ function getGroupedTours() { var deferred = $q.defer(); var tours = getTours(); - setTourStatuses(tours).then(function() { + setTourStatuses(tours).then(function () { var groupedTours = []; tours.forEach(function (item) { - + if (item.contentType === null || item.contentType === '') { var groupExists = false; var newGroup = { @@ -149,9 +151,9 @@ } groupExists = true; - if(item.hidden === false){ - group.tours.push(item); - } + if (item.hidden === false) { + group.tours.push(item); + } } }); @@ -162,7 +164,7 @@ newGroup.groupOrder = item.groupOrder; } - if(item.hidden === false){ + if (item.hidden === false) { newGroup.tours.push(item); groupedTours.push(newGroup); } @@ -242,14 +244,14 @@ throw "Tour " + tour.alias + " is missing the required sections"; } } - + /** * Validates a tour before it gets registered in the service * @param {any} tour */ function validateTourRegistration(tour) { // check for existing tours with the same alias - angular.forEach(tours, function (existingTour) { + tours.forEach(existingTour => { if (existingTour.alias === tour.alias) { throw "A tour with the alias " + tour.alias + " is already registered"; } @@ -265,16 +267,17 @@ var deferred = $q.defer(); currentUserResource.getTours().then(function (storedTours) { - angular.forEach(storedTours, function (storedTour) { + storedTours.forEach(storedTour => { + if (storedTour.completed === true) { - angular.forEach(tours, function (tour) { + tours.forEach(tour => { if (storedTour.alias === tour.alias) { tour.completed = true; } }); } if (storedTour.disabled === true) { - angular.forEach(tours, function (tour) { + tours.forEach(tour => { if (storedTour.alias === tour.alias) { tour.disabled = true; } @@ -296,7 +299,7 @@ getCurrentTour: getCurrentTour, getGroupedTours: getGroupedTours, getTourByAlias: getTourByAlias, - getToursForDoctype : getToursForDoctype + getToursForDoctype: getToursForDoctype }; return service; diff --git a/src/Umbraco.Web.UI.Client/src/navigation.controller.js b/src/Umbraco.Web.UI.Client/src/navigation.controller.js index 425cdb3054..ee8d13e320 100644 --- a/src/Umbraco.Web.UI.Client/src/navigation.controller.js +++ b/src/Umbraco.Web.UI.Client/src/navigation.controller.js @@ -142,7 +142,7 @@ function NavigationController($scope, $rootScope, $location, $log, $q, $routePar var isInit = false; var evts = []; - + //Listen for global state changes evts.push(eventsService.on("appState.globalState.changed", function (e, args) { if (args.key === "showNavigation") { @@ -200,7 +200,7 @@ function NavigationController($scope, $rootScope, $location, $log, $q, $routePar $scope.treeApi.load({ section: $scope.currentSection, customTreeParams: $scope.customTreeParams, cacheKey: $scope.treeCacheKey }); }); } - + //show/hide search results if (args.key === "showSearchResults") { $scope.showSearchResults = args.value; @@ -222,7 +222,7 @@ function NavigationController($scope, $rootScope, $location, $log, $q, $routePar } else { $location.search("mculture", null); } - + var currentEditorState = editorState.getCurrent(); if (currentEditorState && currentEditorState.path) { $scope.treeApi.syncTree({ path: currentEditorState.path, activate: true }); @@ -233,13 +233,13 @@ function NavigationController($scope, $rootScope, $location, $log, $q, $routePar //Emitted when a language is created or an existing one saved/edited evts.push(eventsService.on("editors.languages.languageSaved", function (e, args) { - if(args.isNew){ + if (args.isNew) { //A new language has been created - reload languages for tree loadLanguages().then(function (languages) { $scope.languages = languages; }); } - else if(args.language.isDefault){ + else if (args.language.isDefault) { //A language was saved and was set to be the new default (refresh the tree, so its at the top) loadLanguages().then(function (languages) { $scope.languages = languages; @@ -282,7 +282,7 @@ function NavigationController($scope, $rootScope, $location, $log, $q, $routePar /** * For multi language sites, this ensures that mculture is set to either the last selected language or the default one - */ + */ function ensureMainCulture() { if ($location.search().mculture) { return; @@ -295,7 +295,7 @@ function NavigationController($scope, $rootScope, $location, $log, $q, $routePar $timeout(function () { $scope.selectLanguage(language); }); - } + } /** * Based on the current state of the application, this configures the scope variables that control the main tree and language drop down @@ -432,7 +432,7 @@ function NavigationController($scope, $rootScope, $location, $log, $q, $routePar //the nav is ready, let the app know eventsService.emit("app.navigationReady", { treeApi: $scope.treeApi }); - + } }); }); @@ -469,7 +469,7 @@ function NavigationController($scope, $rootScope, $location, $log, $q, $routePar // add the selected culture to a cookie so the user will log back into the same culture later on (cookie lifetime = one year) var expireDate = new Date(); expireDate.setDate(expireDate.getDate() + 365); - $cookies.put("UMB_MCULTURE", language.culture, {path: "/", expires: expireDate}); + $cookies.put("UMB_MCULTURE", language.culture, { path: "/", expires: expireDate }); // close the language selector $scope.page.languageSelectorIsOpen = false; @@ -495,9 +495,10 @@ function NavigationController($scope, $rootScope, $location, $log, $q, $routePar //execute them sequentially // set selected language to active - angular.forEach($scope.languages, function(language){ + $scope.languages.forEach(language => { language.active = false; }); + language.active = true; angularHelper.executeSequentialPromises(promises); @@ -538,7 +539,7 @@ function NavigationController($scope, $rootScope, $location, $log, $q, $routePar closeTree(); }; - $scope.onOutsideClick = function() { + $scope.onOutsideClick = function () { closeTree(); }; diff --git a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js index 62b675b28b..89e55d2f2c 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js @@ -1,13 +1,13 @@ //used for the media picker dialog angular.module("umbraco") .controller("Umbraco.Editors.MediaPickerController", - function ($scope, $timeout, mediaResource, entityResource, userService, mediaHelper, mediaTypeHelper, eventsService, treeService, localStorageService, localizationService, editorService, umbSessionStorage) { + function ($scope, $timeout, mediaResource, entityResource, userService, mediaHelper, mediaTypeHelper, eventsService, treeService, localStorageService, localizationService, editorService, umbSessionStorage) { var vm = this; - + vm.submit = submit; vm.close = close; - + vm.toggle = toggle; vm.upload = upload; vm.dragLeave = dragLeave; @@ -26,7 +26,7 @@ angular.module("umbraco") vm.shouldShowUrl = shouldShowUrl; var dialogOptions = $scope.model; - + $scope.disableFolderSelect = (dialogOptions.disableFolderSelect && dialogOptions.disableFolderSelect !== "0") ? true : false; $scope.disableFocalPoint = (dialogOptions.disableFocalPoint && dialogOptions.disableFocalPoint !== "0") ? true : false; $scope.onlyImages = (dialogOptions.onlyImages && dialogOptions.onlyImages !== "0") ? true : false; @@ -133,21 +133,21 @@ angular.module("umbraco") // media object so we need to look it up var id = $scope.target.udi ? $scope.target.udi : $scope.target.id; var altText = $scope.target.altText; - + // ID of a UDI or legacy int ID still could be null/undefinied here // As user may dragged in an image that has not been saved to media section yet if (id) { entityResource.getById(id, "Media") - .then(function (node) { - $scope.target = node; - if (ensureWithinStartNode(node)) { - selectMedia(node); - $scope.target.url = mediaHelper.resolveFileFromEntity(node); - $scope.target.thumbnail = mediaHelper.resolveFileFromEntity(node, true); - $scope.target.altText = altText; - openDetailsDialog(); - } - }, gotoStartNode); + .then(function (node) { + $scope.target = node; + if (ensureWithinStartNode(node)) { + selectMedia(node); + $scope.target.url = mediaHelper.resolveFileFromEntity(node); + $scope.target.thumbnail = mediaHelper.resolveFileFromEntity(node, true); + $scope.target.altText = altText; + openDetailsDialog(); + } + }, gotoStartNode); } else { // No ID set - then this is going to be a tmpimg that has not been uploaded // User editing this will want to be changing the ALT text @@ -240,16 +240,16 @@ angular.module("umbraco") } } else { if ($scope.showDetails) { - + $scope.target = media; - + // handle both entity and full media object if (media.image) { $scope.target.url = media.image; } else { $scope.target.url = mediaHelper.resolveFile(media); } - + openDetailsDialog(); } else { selectMedia(media); @@ -301,7 +301,7 @@ angular.module("umbraco") $timeout(function () { if ($scope.multiPicker) { var images = _.rest($scope.images, $scope.images.length - files.length); - _.each(images, function(image) { + _.each(images, function (image) { selectMedia(image); }); } else { @@ -373,7 +373,7 @@ angular.module("umbraco") if (vm.searchOptions.filter) { searchMedia(); } else { - + // reset pagination vm.searchOptions = { pageNumber: 1, @@ -383,7 +383,7 @@ angular.module("umbraco") filter: '', dataTypeKey: dataTypeKey }; - + getChildren($scope.currentFolder.id); } }); @@ -411,9 +411,9 @@ angular.module("umbraco") entityResource.getPagedDescendants($scope.filterOptions.excludeSubFolders ? $scope.currentFolder.id : $scope.startNodeId, "Media", vm.searchOptions) .then(function (data) { // update image data to work with image grid - angular.forEach(data.items, function (mediaItem) { - setMediaMetaData(mediaItem); - }); + if (data.items) { + data.items.forEach(mediaItem => setMediaMetaData(mediaItem)); + } // update images $scope.images = data.items ? data.items : []; diff --git a/src/Umbraco.Web.UI.Client/src/views/dashboard/settings/healthcheck.controller.js b/src/Umbraco.Web.UI.Client/src/views/dashboard/settings/healthcheck.controller.js index 8631b09a45..f5ceb877c8 100644 --- a/src/Umbraco.Web.UI.Client/src/views/dashboard/settings/healthcheck.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/dashboard/settings/healthcheck.controller.js @@ -1,4 +1,4 @@ -(function() { +(function () { "use strict"; function HealthCheckController($scope, healthCheckResource) { @@ -22,7 +22,7 @@ // Get a (grouped) list of all health checks healthCheckResource.getAllChecks() - .then(function(response) { + .then(function (response) { vm.groups = response; }); @@ -33,11 +33,11 @@ var totalInfo = 0; // count total number of statusses - angular.forEach(group.checks, - function(check) { - angular.forEach(check.status, - function(status) { - switch (status.resultType) { + group.checks.forEach(check => { + + if (check.status) { + check.status.forEach(status => { + switch (status.resultType) { case SUCCESS: totalSuccess = totalSuccess + 1; break; @@ -50,9 +50,10 @@ case INFO: totalInfo = totalInfo + 1; break; - } - }); - }); + } + }); + } + }); group.totalSuccess = totalSuccess; group.totalError = totalError; @@ -66,7 +67,7 @@ check.loading = true; check.status = null; healthCheckResource.getStatus(check.id) - .then(function(response) { + .then(function (response) { check.loading = false; check.status = response; }); @@ -75,7 +76,7 @@ function executeAction(check, index, action) { check.loading = true; healthCheckResource.executeAction(action) - .then(function(response) { + .then(function (response) { check.status[index] = response; check.loading = false; }); @@ -94,24 +95,22 @@ group.checkCounter = 0; group.loading = true; - angular.forEach(checks, - function(check) { + checks.forEach(check => { + check.loading = true; - check.loading = true; + healthCheckResource.getStatus(check.id) + .then(function (response) { + check.status = response; + group.checkCounter = group.checkCounter + 1; + check.loading = false; - healthCheckResource.getStatus(check.id) - .then(function(response) { - check.status = response; - group.checkCounter = group.checkCounter + 1; - check.loading = false; - - // when all checks are done, set global group result - if (group.checkCounter === checks.length) { - setGroupGlobalResultType(group); - group.loading = false; - } - }); - }); + // when all checks are done, set global group result + if (group.checkCounter === checks.length) { + setGroupGlobalResultType(group); + group.loading = false; + } + }); + }); } function openGroup(group) { From 7f64abb2243939c44e340caf132b7534f8863d4a Mon Sep 17 00:00:00 2001 From: Rachel Breeze Date: Sat, 11 Apr 2020 16:16:24 +0100 Subject: [PATCH 26/46] Upgraded TinyMCE to 4.9.9 --- src/Umbraco.Web.UI.Client/package-lock.json | 12 ++++++------ src/Umbraco.Web.UI.Client/package.json | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/package-lock.json b/src/Umbraco.Web.UI.Client/package-lock.json index c0dad5b736..b8087066c9 100644 --- a/src/Umbraco.Web.UI.Client/package-lock.json +++ b/src/Umbraco.Web.UI.Client/package-lock.json @@ -2467,9 +2467,9 @@ } }, "caniuse-lite": { - "version": "1.0.30001002", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001002.tgz", - "integrity": "sha512-pRuxPE8wdrWmVPKcDmJJiGBxr6lFJq4ivdSeo9FTmGj5Rb8NX3Mby2pARG57MXF15hYAhZ0nHV5XxT2ig4bz3g==", + "version": "1.0.30001040", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001040.tgz", + "integrity": "sha512-Ep0tEPeI5wCvmJNrXjE3etgfI+lkl1fTDU6Y3ZH1mhrjkPlVI9W4pcKbMo+BQLpEWKVYYp2EmYaRsqpPC3k7lQ==", "dev": true }, "caseless": { @@ -15313,9 +15313,9 @@ "integrity": "sha512-NB6Dk1A9xgQPMoGqC5CVXn123gWyte215ONT5Pp5a0yt4nlEoO1ZWeCwpncaekPHXO60i47ihFnZPiRPjRMq4Q==" }, "tinymce": { - "version": "4.9.7", - "resolved": "https://registry.npmjs.org/tinymce/-/tinymce-4.9.7.tgz", - "integrity": "sha512-cj0HvUuniTuIjOAJdRt5BUfeQqM5yHjbA2NOub9HUHXlCrT9OwD9WBPU6tGlaPC2l2I4eGoOnT8llosZRdQU5Q==" + "version": "4.9.9", + "resolved": "https://registry.npmjs.org/tinymce/-/tinymce-4.9.9.tgz", + "integrity": "sha512-7Wqh4PGSAWm6FyNwyI1uFAaZyzeQeiwd9Gg2R89SpFIqoMrSzNHIYBqnZnlDm4Bd2DJ0wcC6uJhwFrabIE8puw==" }, "tmp": { "version": "0.0.33", diff --git a/src/Umbraco.Web.UI.Client/package.json b/src/Umbraco.Web.UI.Client/package.json index 438052367e..8ab5980107 100644 --- a/src/Umbraco.Web.UI.Client/package.json +++ b/src/Umbraco.Web.UI.Client/package.json @@ -42,7 +42,7 @@ "npm": "6.13.6", "signalr": "2.4.0", "spectrum-colorpicker": "1.8.0", - "tinymce": "4.9.7", + "tinymce": "4.9.9", "typeahead.js": "0.11.1", "underscore": "1.9.1" }, From bd26cb36ecce2bbe86f11b61dd1a01c314378c89 Mon Sep 17 00:00:00 2001 From: BatJan Date: Sat, 11 Apr 2020 22:11:13 +0200 Subject: [PATCH 27/46] Replace angular.copy with Utilities.copy --- .../application/umbappheader.directive.js | 20 +- .../components/content/edit.controller.js | 20 +- .../umbvariantcontenteditors.directive.js | 38 +- .../components/forms/umbrawmodel.directive.js | 152 +- .../overlays/umboverlay.directive.js | 633 ++++---- .../components/umbgroupsbuilder.directive.js | 1338 ++++++++--------- .../components/umbnestedcontent.directive.js | 6 +- ...tpostdollarvariablesrequest.interceptor.js | 28 +- .../services/contenttypehelper.service.js | 312 ++-- .../src/common/services/editor.service.js | 52 +- .../src/common/services/navigation.service.js | 146 +- src/Umbraco.Web.UI.Client/src/init.js | 10 +- .../compositions/compositions.controller.js | 6 +- .../linkpicker/linkpicker.controller.js | 12 +- .../src/views/languages/edit.controller.js | 10 +- .../src/views/packages/edit.controller.js | 6 +- .../propertyeditors/grid/grid.controller.js | 42 +- .../grid/grid.prevalues.controller.js | 526 +++---- .../imagecropper/imagecropper.controller.js | 392 ++--- .../nestedcontent/nestedcontent.controller.js | 36 +- .../src/views/templates/edit.controller.js | 200 +-- .../src/views/users/group.controller.js | 20 +- .../src/views/users/user.controller.js | 105 +- .../users/views/users/users.controller.js | 44 +- .../test/lib/angular/angular-mocks.js | 32 +- 25 files changed, 2092 insertions(+), 2094 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js index 372a816dd5..2b9a96cf55 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js @@ -18,14 +18,14 @@ ]; // when a user logs out or timesout - evts.push(eventsService.on("app.notAuthenticated", function() { + evts.push(eventsService.on("app.notAuthenticated", function () { scope.authenticated = false; scope.user = null; })); // when the application is ready and the user is authorized setup the data - evts.push(eventsService.on("app.ready", function(evt, data) { - + evts.push(eventsService.on("app.ready", function (evt, data) { + scope.authenticated = true; scope.user = data.user; @@ -40,10 +40,10 @@ })); - evts.push(eventsService.on("app.userRefresh", function(evt) { - userService.refreshCurrentUser().then(function(data) { + evts.push(eventsService.on("app.userRefresh", function (evt) { + userService.refreshCurrentUser().then(function (data) { scope.user = data; - + if (scope.user.avatars) { scope.avatar = []; if (Utilities.isArray(scope.user.avatars)) { @@ -54,10 +54,10 @@ } }); })); - + scope.rememberFocus = focusService.rememberFocus; - - scope.searchClick = function() { + + scope.searchClick = function () { var showSearch = appState.getSearchState("show"); appState.setSearchState("show", !showSearch); }; @@ -71,7 +71,7 @@ }; scope.avatarClick = function () { - if(!scope.userDialog) { + if (!scope.userDialog) { scope.userDialog = { view: "user", show: true, diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/content/edit.controller.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/content/edit.controller.js index 91b0ba8754..d674b3d1e8 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/content/edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/content/edit.controller.js @@ -38,7 +38,7 @@ //watch for changes to isNew, set the page.isNew accordingly and load the breadcrumb if we can $scope.$watch('isNew', function (newVal, oldVal) { - + $scope.page.isNew = Object.toBoolean(newVal); //We fetch all ancestors of the node to generate the footer breadcrumb navigation @@ -182,32 +182,32 @@ } })); - evts.push(eventsService.on("editors.content.reload", function (name, args) { + evts.push(eventsService.on("editors.content.reload", function (name, args) { if (args && args.node && $scope.content.id === args.node.id) { reload(); loadBreadcrumb(); syncTreeNode($scope.content, $scope.content.path); } })); - - evts.push(eventsService.on("rte.file.uploading", function(){ + + evts.push(eventsService.on("rte.file.uploading", function () { $scope.page.saveButtonState = "busy"; $scope.page.buttonGroupState = "busy"; })); - evts.push(eventsService.on("rte.file.uploaded", function(){ + evts.push(eventsService.on("rte.file.uploaded", function () { $scope.page.saveButtonState = "success"; $scope.page.buttonGroupState = "success"; })); - evts.push(eventsService.on("rte.shortcut.save", function(){ + evts.push(eventsService.on("rte.shortcut.save", function () { if ($scope.page.showSaveButton) { $scope.save(); } })); - evts.push(eventsService.on("content.saved", function(){ + evts.push(eventsService.on("content.saved", function () { // Clear out localstorage keys that start with tinymce__ // When we save/perist a content node // NOTE: clearAll supports a RegEx pattern of items to remove @@ -323,7 +323,7 @@ .then(function (syncArgs) { $scope.page.menu.currentNode = syncArgs.node; if (reloadChildren && syncArgs.node.expanded) { - treeService.loadNodeChildren({node: syncArgs.node}); + treeService.loadNodeChildren({ node: syncArgs.node }); } }, function () { //handle the rejection @@ -784,7 +784,7 @@ var dialog = { parentScope: $scope, view: "views/content/overlays/schedule.html", - variants: angular.copy($scope.content.variants), //set a model property for the dialog + variants: Utilities.copy($scope.content.variants), //set a model property for the dialog skipFormValidation: true, //when submitting the overlay form, skip any client side validation submitButtonLabelKey: "buttons_schedulePublish", submit: function (model) { @@ -818,7 +818,7 @@ } model.submitButtonState = "error"; //re-map the dialog model since we've re-bound the properties - dialog.variants = angular.copy($scope.content.variants); + dialog.variants = Utilities.copy($scope.content.variants); //don't reject, we've handled the error return $q.when(err); }); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbvariantcontenteditors.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbvariantcontenteditors.directive.js index a4dac046e5..6aba1e6758 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbvariantcontenteditors.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbvariantcontenteditors.directive.js @@ -44,7 +44,7 @@ /** Called when the component initializes */ function onInit() { - prevContentDateUpdated = angular.copy(vm.content.updateDate); + prevContentDateUpdated = Utilities.copy(vm.content.updateDate); setActiveCulture(); } @@ -68,7 +68,7 @@ function doCheck() { if (!angular.equals(vm.content.updateDate, prevContentDateUpdated)) { setActiveCulture(); - prevContentDateUpdated = angular.copy(vm.content.updateDate); + prevContentDateUpdated = Utilities.copy(vm.content.updateDate); } } @@ -152,7 +152,7 @@ //copy the apps from the main model if not assigned yet to the variant if (!variant.apps) { - variant.apps = angular.copy(vm.content.apps); + variant.apps = Utilities.copy(vm.content.apps); } //if this is a variant has a culture/language than we need to assign the language drop down info @@ -185,7 +185,7 @@ // keep track of the open variants across the different split views // push the first variant then update the variant index based on the editor index - if(vm.openVariants && vm.openVariants.length === 0) { + if (vm.openVariants && vm.openVariants.length === 0) { vm.openVariants.push(variant.language.culture); } else { vm.openVariants[editorIndex] = variant.language.culture; @@ -205,10 +205,10 @@ } // make sure the same app it set to active in the new variant - if(activeAppAlias) { - angular.forEach(variant.apps, function(app) { + if (activeAppAlias) { + angular.forEach(variant.apps, function (app) { app.active = false; - if(app.alias === activeAppAlias) { + if (app.alias === activeAppAlias) { app.active = true; } }); @@ -283,10 +283,10 @@ function selectVariant(variant, editorIndex) { // prevent variants already open in a split view to be opened - if(vm.openVariants.indexOf(variant.language.culture) !== -1) { + if (vm.openVariants.indexOf(variant.language.culture) !== -1) { return; } - + //if the editor index is zero, then update the query string to track the lang selection, otherwise if it's part //of a 2nd split view editor then update the model directly. if (editorIndex === 0) { @@ -313,7 +313,7 @@ //update the editors collection insertVariantEditor(editorIndex, contentVariant); - + } } @@ -322,21 +322,21 @@ * @param {any} app This is the model of the selected app */ function selectApp(app) { - if(vm.onSelectApp) { - vm.onSelectApp({"app": app}); + if (vm.onSelectApp) { + vm.onSelectApp({ "app": app }); } } - + function selectAppAnchor(app, anchor) { - if(vm.onSelectAppAnchor) { - vm.onSelectAppAnchor({"app": app, "anchor": anchor}); + if (vm.onSelectAppAnchor) { + vm.onSelectAppAnchor({ "app": app, "anchor": anchor }); } } - - - $scope.$on("editors.apps.appChanged", function($event, $args) { + + + $scope.$on("editors.apps.appChanged", function ($event, $args) { var app = $args.app; - if(app && app.alias) { + if (app && app.alias) { activeAppAlias = app.alias; } }); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbrawmodel.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbrawmodel.directive.js index 406f65781c..ab92cfdb91 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbrawmodel.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbrawmodel.directive.js @@ -9,91 +9,91 @@ will override element type to textarea and add own attribute ngModel tied to jso */ angular.module("umbraco.directives") - .directive('umbRawModel', function () { - return { - restrict: 'A', - require: 'ngModel', - template: '', - replace : true, - scope: { - model: '=umbRawModel', - validateOn:'=' - }, - link: function (scope, element, attrs, ngModelCtrl) { + .directive('umbRawModel', function () { + return { + restrict: 'A', + require: 'ngModel', + template: '', + replace: true, + scope: { + model: '=umbRawModel', + validateOn: '=' + }, + link: function (scope, element, attrs, ngModelCtrl) { - function setEditing (value) { - scope.jsonEditing = angular.copy( jsonToString(value)); - } + function setEditing(value) { + scope.jsonEditing = Utilities.copy(jsonToString(value)); + } - function updateModel (value) { - scope.model = stringToJson(value); - } + function updateModel(value) { + scope.model = stringToJson(value); + } - function setValid() { - ngModelCtrl.$setValidity('json', true); - } + function setValid() { + ngModelCtrl.$setValidity('json', true); + } - function setInvalid () { - ngModelCtrl.$setValidity('json', false); - } + function setInvalid() { + ngModelCtrl.$setValidity('json', false); + } - function stringToJson(text) { - try { - return angular.fromJson(text); - } catch (err) { - setInvalid(); - return text; - } - } + function stringToJson(text) { + try { + return angular.fromJson(text); + } catch (err) { + setInvalid(); + return text; + } + } - function jsonToString(object) { - // better than JSON.stringify(), because it formats + filters $$hashKey etc. - // NOTE that this will remove all $-prefixed values - return Utilities.toJson(object, true); - } + function jsonToString(object) { + // better than JSON.stringify(), because it formats + filters $$hashKey etc. + // NOTE that this will remove all $-prefixed values + return Utilities.toJson(object, true); + } - function isValidJson(model) { - var flag = true; - try { - angular.fromJson(model); - } catch (err) { - flag = false; - } - return flag; - } + function isValidJson(model) { + var flag = true; + try { + angular.fromJson(model); + } catch (err) { + flag = false; + } + return flag; + } - //init - setEditing(scope.model); + //init + setEditing(scope.model); - var onInputChange = function(newval,oldval){ - if (newval !== oldval) { - if (isValidJson(newval)) { - setValid(); - updateModel(newval); - } else { - setInvalid(); - } - } - }; + var onInputChange = function (newval, oldval) { + if (newval !== oldval) { + if (isValidJson(newval)) { + setValid(); + updateModel(newval); + } else { + setInvalid(); + } + } + }; - if(scope.validateOn){ - element.on(scope.validateOn, function(){ - scope.$apply(function(){ - onInputChange(scope.jsonEditing); - }); - }); - }else{ - //check for changes going out - scope.$watch('jsonEditing', onInputChange, true); - } + if (scope.validateOn) { + element.on(scope.validateOn, function () { + scope.$apply(function () { + onInputChange(scope.jsonEditing); + }); + }); + } else { + //check for changes going out + scope.$watch('jsonEditing', onInputChange, true); + } - //check for changes coming in - scope.$watch('model', function (newval, oldval) { - if (newval !== oldval) { - setEditing(newval); - } - }, true); + //check for changes coming in + scope.$watch('model', function (newval, oldval) { + if (newval !== oldval) { + setEditing(newval); + } + }, true); - } - }; - }); + } + }; + }); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/overlays/umboverlay.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/overlays/umboverlay.directive.js index fa1f4227a2..ad396e7a9a 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/overlays/umboverlay.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/overlays/umboverlay.directive.js @@ -193,352 +193,351 @@ Opens an overlay to show a custom YSOD.
    @param {string} position The overlay position ("left", "right", "center": "target"). **/ -(function() { - 'use strict'; +(function () { + 'use strict'; function OverlayDirective($timeout, formHelper, overlayHelper, localizationService, $q, $templateCache, $http, $compile) { - function link(scope, el, attr, ctrl) { + function link(scope, el, attr, ctrl) { - scope.directive = { - enableConfirmButton: false - }; - - var overlayNumber = 0; - var numberOfOverlays = 0; - var isRegistered = false; - - - var modelCopy = {}; - var unsubscribe = []; - - function activate() { - setView(); - - setButtonText(); - - modelCopy = makeModelCopy(scope.model); - - $timeout(function() { - - if (scope.position === "target" && scope.model.event) { - setTargetPosition(); - - // update the position of the overlay on content changes - // as these affect the layout/size of the overlay - if ('ResizeObserver' in window) - { - var resizeObserver = new ResizeObserver(setTargetPosition); - var contentArea = document.getElementById("contentwrapper"); - resizeObserver.observe(el[0]); - if (contentArea) { - resizeObserver.observe(contentArea); - } - unsubscribe.push(function () { - resizeObserver.disconnect(); - }); - } - } - - // this has to be done inside a timeout to ensure the destroy - // event on other overlays is run before registering a new one - registerOverlay(); - - setOverlayIndent(); - - focusOnOverlayHeading() - }); - - } - - // Ideally this would focus on the first natively focusable element in the overlay, but as the content can be dynamic, it is focusing on the heading. - function focusOnOverlayHeading() { - var heading = el.find(".umb-overlay__title"); - - if(heading) { - heading.focus(); - } - } - - function setView() { - - if (scope.view) { - - if (scope.view.indexOf(".html") === -1) { - var viewAlias = scope.view.toLowerCase(); - scope.view = "views/common/overlays/" + viewAlias + "/" + viewAlias + ".html"; - } - - //if a custom parent scope is defined then we need to manually compile the view - if (scope.parentScope) { - var element = el.find(".scoped-view"); - $http.get(scope.view, { cache: $templateCache }) - .then(function (response) { - var templateScope = scope.parentScope.$new(); - unsubscribe.push(function() { - templateScope.$destroy(); - }); - templateScope.model = scope.model; - element.html(response.data); - element.show(); - $compile(element.contents())(templateScope); - }); - } - } - - } - - function setButtonText() { - - var labelKeys = [ - "general_close", - "general_submit" - ]; - - localizationService.localizeMany(labelKeys).then(function (values) { - if (!scope.model.closeButtonLabelKey && !scope.model.closeButtonLabel) { - scope.model.closeButtonLabel = values[0]; - } - if (!scope.model.submitButtonLabelKey && !scope.model.submitButtonLabel) { - scope.model.submitButtonLabel = values[1]; - } - }); - } - - function registerOverlay() { - - overlayNumber = overlayHelper.registerOverlay(); - - $(document).on("keydown.overlay-" + overlayNumber, function(event) { - - if (event.which === 27) { - - numberOfOverlays = overlayHelper.getNumberOfOverlays(); - - if (numberOfOverlays === overlayNumber && !scope.model.disableEscKey) { - scope.$apply(function () { - scope.closeOverLay(); - }); - } - - event.stopPropagation(); - event.preventDefault(); - } - - if (event.which === 13) { - - numberOfOverlays = overlayHelper.getNumberOfOverlays(); - - if(numberOfOverlays === overlayNumber) { - - var activeElementType = document.activeElement.tagName; - var clickableElements = ["A", "BUTTON"]; - var submitOnEnter = document.activeElement.hasAttribute("overlay-submit-on-enter"); - var submitOnEnterValue = submitOnEnter ? document.activeElement.getAttribute("overlay-submit-on-enter") : ""; - - if(clickableElements.indexOf(activeElementType) >= 0) { - // don't do anything, let the browser Enter key handle this - } else if(activeElementType === "TEXTAREA" && !submitOnEnter) { - - - } else if (submitOnEnter && submitOnEnterValue === "false") { - // don't do anything - }else { - scope.$apply(function () { - scope.submitForm(scope.model); - }); - event.preventDefault(); - } - - } - - } - - }); - - isRegistered = true; - - } - - function unregisterOverlay() { - - if(isRegistered) { - - overlayHelper.unregisterOverlay(); - - $(document).off("keydown.overlay-" + overlayNumber); - - isRegistered = false; - } - - } - - function makeModelCopy(object) { - - var newObject = {}; - - for (var key in object) { - if (key !== "event" && key !== "parentScope") { - newObject[key] = angular.copy(object[key]); - } - } - - return newObject; - - } - - function setOverlayIndent() { - - var overlayIndex = overlayNumber - 1; - var indentSize = overlayIndex * 20; - var overlayWidth = el[0].clientWidth; - - el.css('width', overlayWidth - indentSize); - - if(scope.position === "center" && overlayIndex > 0 || scope.position === "target" && overlayIndex > 0) { - var overlayTopPosition = el[0].offsetTop; - el.css('top', overlayTopPosition + indentSize); - } - - } - - function setTargetPosition() { - - var container = $("#contentwrapper"); - var containerLeft = container[0].offsetLeft; - var containerRight = containerLeft + container[0].offsetWidth; - var containerTop = container[0].offsetTop; - var containerBottom = containerTop + container[0].offsetHeight; - - var mousePositionClickX = null; - var mousePositionClickY = null; - var elementHeight = null; - var elementWidth = null; - - var position = { - right: "inherit", - left: "inherit", - top: "inherit", - bottom: "inherit" + scope.directive = { + enableConfirmButton: false }; - // click position - mousePositionClickX = scope.model.event.pageX; - mousePositionClickY = scope.model.event.pageY; + var overlayNumber = 0; + var numberOfOverlays = 0; + var isRegistered = false; - // element size - elementHeight = el[0].clientHeight; - elementWidth = el[0].clientWidth; - // move element to this position - position.left = mousePositionClickX - (elementWidth / 2); - position.top = mousePositionClickY - (elementHeight / 2); + var modelCopy = {}; + var unsubscribe = []; + + function activate() { + setView(); + + setButtonText(); + + modelCopy = makeModelCopy(scope.model); + + $timeout(function () { + + if (scope.position === "target" && scope.model.event) { + setTargetPosition(); + + // update the position of the overlay on content changes + // as these affect the layout/size of the overlay + if ('ResizeObserver' in window) { + var resizeObserver = new ResizeObserver(setTargetPosition); + var contentArea = document.getElementById("contentwrapper"); + resizeObserver.observe(el[0]); + if (contentArea) { + resizeObserver.observe(contentArea); + } + unsubscribe.push(function () { + resizeObserver.disconnect(); + }); + } + } + + // this has to be done inside a timeout to ensure the destroy + // event on other overlays is run before registering a new one + registerOverlay(); + + setOverlayIndent(); + + focusOnOverlayHeading() + }); - // check to see if element is outside screen - // outside right - if (position.left + elementWidth > containerRight) { - position.right = 10; - position.left = "inherit"; } - // outside bottom - if (position.top + elementHeight > containerBottom) { - position.bottom = 10; - position.top = "inherit"; + // Ideally this would focus on the first natively focusable element in the overlay, but as the content can be dynamic, it is focusing on the heading. + function focusOnOverlayHeading() { + var heading = el.find(".umb-overlay__title"); + + if (heading) { + heading.focus(); + } } - // outside left - if (position.left < containerLeft) { - position.left = containerLeft + 10; - position.right = "inherit"; + function setView() { + + if (scope.view) { + + if (scope.view.indexOf(".html") === -1) { + var viewAlias = scope.view.toLowerCase(); + scope.view = "views/common/overlays/" + viewAlias + "/" + viewAlias + ".html"; + } + + //if a custom parent scope is defined then we need to manually compile the view + if (scope.parentScope) { + var element = el.find(".scoped-view"); + $http.get(scope.view, { cache: $templateCache }) + .then(function (response) { + var templateScope = scope.parentScope.$new(); + unsubscribe.push(function () { + templateScope.$destroy(); + }); + templateScope.model = scope.model; + element.html(response.data); + element.show(); + $compile(element.contents())(templateScope); + }); + } + } + } - // outside top - if (position.top < containerTop) { - position.top = 10; - position.bottom = "inherit"; + function setButtonText() { + + var labelKeys = [ + "general_close", + "general_submit" + ]; + + localizationService.localizeMany(labelKeys).then(function (values) { + if (!scope.model.closeButtonLabelKey && !scope.model.closeButtonLabel) { + scope.model.closeButtonLabel = values[0]; + } + if (!scope.model.submitButtonLabelKey && !scope.model.submitButtonLabel) { + scope.model.submitButtonLabel = values[1]; + } + }); } - el.css(position); - } + function registerOverlay() { - scope.submitForm = function(model) { - if(scope.model.submit) { - if (formHelper.submitForm({ scope: scope, skipValidation: scope.model.skipFormValidation})) { - - if (scope.model.confirmSubmit && scope.model.confirmSubmit.enable && !scope.directive.enableConfirmButton) { - //wrap in a when since we don't know if this is a promise or not - $q.when(scope.model.submit(model, modelCopy, scope.directive.enableConfirmButton)).then( - function() { - formHelper.resetForm({ scope: scope }); - }); - } else { - unregisterOverlay(); - //wrap in a when since we don't know if this is a promise or not - $q.when(scope.model.submit(model, modelCopy, scope.directive.enableConfirmButton)).then( - function() { - formHelper.resetForm({ scope: scope }); - }); - } + overlayNumber = overlayHelper.registerOverlay(); - } - } - }; + $(document).on("keydown.overlay-" + overlayNumber, function (event) { - scope.cancelConfirmSubmit = function() { - scope.model.confirmSubmit.show = false; - }; + if (event.which === 27) { - scope.closeOverLay = function() { + numberOfOverlays = overlayHelper.getNumberOfOverlays(); - unregisterOverlay(); + if (numberOfOverlays === overlayNumber && !scope.model.disableEscKey) { + scope.$apply(function () { + scope.closeOverLay(); + }); + } + + event.stopPropagation(); + event.preventDefault(); + } + + if (event.which === 13) { + + numberOfOverlays = overlayHelper.getNumberOfOverlays(); + + if (numberOfOverlays === overlayNumber) { + + var activeElementType = document.activeElement.tagName; + var clickableElements = ["A", "BUTTON"]; + var submitOnEnter = document.activeElement.hasAttribute("overlay-submit-on-enter"); + var submitOnEnterValue = submitOnEnter ? document.activeElement.getAttribute("overlay-submit-on-enter") : ""; + + if (clickableElements.indexOf(activeElementType) >= 0) { + // don't do anything, let the browser Enter key handle this + } else if (activeElementType === "TEXTAREA" && !submitOnEnter) { + + + } else if (submitOnEnter && submitOnEnterValue === "false") { + // don't do anything + } else { + scope.$apply(function () { + scope.submitForm(scope.model); + }); + event.preventDefault(); + } + + } + + } + + }); + + isRegistered = true; - if (scope.model && scope.model.close) { - scope.model = modelCopy; - scope.model.close(scope.model); - } else { - scope.model.show = false; - scope.model = null; } - }; + function unregisterOverlay() { + + if (isRegistered) { + + overlayHelper.unregisterOverlay(); + + $(document).off("keydown.overlay-" + overlayNumber); + + isRegistered = false; + } - scope.outSideClick = function() { - if(!scope.model.disableBackdropClick) { - scope.closeOverLay(); } + + function makeModelCopy(object) { + + var newObject = {}; + + for (var key in object) { + if (key !== "event" && key !== "parentScope") { + newObject[key] = Utilities.copy(object[key]); + } + } + + return newObject; + + } + + function setOverlayIndent() { + + var overlayIndex = overlayNumber - 1; + var indentSize = overlayIndex * 20; + var overlayWidth = el[0].clientWidth; + + el.css('width', overlayWidth - indentSize); + + if (scope.position === "center" && overlayIndex > 0 || scope.position === "target" && overlayIndex > 0) { + var overlayTopPosition = el[0].offsetTop; + el.css('top', overlayTopPosition + indentSize); + } + + } + + function setTargetPosition() { + + var container = $("#contentwrapper"); + var containerLeft = container[0].offsetLeft; + var containerRight = containerLeft + container[0].offsetWidth; + var containerTop = container[0].offsetTop; + var containerBottom = containerTop + container[0].offsetHeight; + + var mousePositionClickX = null; + var mousePositionClickY = null; + var elementHeight = null; + var elementWidth = null; + + var position = { + right: "inherit", + left: "inherit", + top: "inherit", + bottom: "inherit" + }; + + // click position + mousePositionClickX = scope.model.event.pageX; + mousePositionClickY = scope.model.event.pageY; + + // element size + elementHeight = el[0].clientHeight; + elementWidth = el[0].clientWidth; + + // move element to this position + position.left = mousePositionClickX - (elementWidth / 2); + position.top = mousePositionClickY - (elementHeight / 2); + + // check to see if element is outside screen + // outside right + if (position.left + elementWidth > containerRight) { + position.right = 10; + position.left = "inherit"; + } + + // outside bottom + if (position.top + elementHeight > containerBottom) { + position.bottom = 10; + position.top = "inherit"; + } + + // outside left + if (position.left < containerLeft) { + position.left = containerLeft + 10; + position.right = "inherit"; + } + + // outside top + if (position.top < containerTop) { + position.top = 10; + position.bottom = "inherit"; + } + + el.css(position); + } + + scope.submitForm = function (model) { + if (scope.model.submit) { + if (formHelper.submitForm({ scope: scope, skipValidation: scope.model.skipFormValidation })) { + + if (scope.model.confirmSubmit && scope.model.confirmSubmit.enable && !scope.directive.enableConfirmButton) { + //wrap in a when since we don't know if this is a promise or not + $q.when(scope.model.submit(model, modelCopy, scope.directive.enableConfirmButton)).then( + function () { + formHelper.resetForm({ scope: scope }); + }); + } else { + unregisterOverlay(); + //wrap in a when since we don't know if this is a promise or not + $q.when(scope.model.submit(model, modelCopy, scope.directive.enableConfirmButton)).then( + function () { + formHelper.resetForm({ scope: scope }); + }); + } + + } + } + }; + + scope.cancelConfirmSubmit = function () { + scope.model.confirmSubmit.show = false; + }; + + scope.closeOverLay = function () { + + unregisterOverlay(); + + if (scope.model && scope.model.close) { + scope.model = modelCopy; + scope.model.close(scope.model); + } else { + scope.model.show = false; + scope.model = null; + } + + }; + + scope.outSideClick = function () { + if (!scope.model.disableBackdropClick) { + scope.closeOverLay(); + } + }; + + unsubscribe.push(unregisterOverlay); + scope.$on('$destroy', function () { + for (var i = 0; i < unsubscribe.length; i++) { + unsubscribe[i](); + } + }); + + activate(); + + } + + var directive = { + transclude: true, + restrict: 'E', + replace: true, + templateUrl: 'views/components/overlays/umb-overlay.html', + scope: { + ngShow: "=", + model: "=", + view: "=", + position: "@", + size: "=?", + parentScope: "=?" + }, + link: link }; - unsubscribe.push(unregisterOverlay); - scope.$on('$destroy', function () { - for (var i = 0; i < unsubscribe.length; i++) { - unsubscribe[i](); - } - }); + return directive; + } - activate(); - - } - - var directive = { - transclude: true, - restrict: 'E', - replace: true, - templateUrl: 'views/components/overlays/umb-overlay.html', - scope: { - ngShow: "=", - model: "=", - view: "=", - position: "@", - size: "=?", - parentScope: "=?" - }, - link: link - }; - - return directive; - } - - angular.module('umbraco.directives').directive('umbOverlay', OverlayDirective); + angular.module('umbraco.directives').directive('umbOverlay', OverlayDirective); })(); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbgroupsbuilder.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbgroupsbuilder.directive.js index a9b9cc52b1..762edefbd5 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbgroupsbuilder.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbgroupsbuilder.directive.js @@ -1,738 +1,738 @@ -(function() { - 'use strict'; +(function () { + 'use strict'; - function GroupsBuilderDirective(contentTypeHelper, contentTypeResource, mediaTypeResource, - dataTypeHelper, dataTypeResource, $filter, iconHelper, $q, $timeout, notificationsService, - localizationService, editorService, eventsService, overlayService) { - - function link(scope, el, attr, ctrl) { - - var eventBindings = []; - var validationTranslated = ""; - var tabNoSortOrderTranslated = ""; + function GroupsBuilderDirective(contentTypeHelper, contentTypeResource, mediaTypeResource, + dataTypeHelper, dataTypeResource, $filter, iconHelper, $q, $timeout, notificationsService, + localizationService, editorService, eventsService, overlayService) { - scope.dataTypeHasChanged = false; - scope.sortingMode = false; - scope.toolbar = []; - scope.sortableOptionsGroup = {}; - scope.sortableOptionsProperty = {}; - scope.sortingButtonKey = "general_reorder"; - scope.compositionsButtonState = "init"; + function link(scope, el, attr, ctrl) { - function activate() { + var eventBindings = []; + var validationTranslated = ""; + var tabNoSortOrderTranslated = ""; - setSortingOptions(); + scope.dataTypeHasChanged = false; + scope.sortingMode = false; + scope.toolbar = []; + scope.sortableOptionsGroup = {}; + scope.sortableOptionsProperty = {}; + scope.sortingButtonKey = "general_reorder"; + scope.compositionsButtonState = "init"; - // set placeholder property on each group - if (scope.model.groups.length !== 0) { - angular.forEach(scope.model.groups, function(group) { - addInitProperty(group); - }); - } + function activate() { - // add init tab - addInitGroup(scope.model.groups); + setSortingOptions(); - activateFirstGroup(scope.model.groups); - - // localize texts - localizationService.localize("validation_validation").then(function(value) { - validationTranslated = value; - }); - - localizationService.localize("contentTypeEditor_tabHasNoSortOrder").then(function(value) { - tabNoSortOrderTranslated = value; - }); - } - - function setSortingOptions() { - - scope.sortableOptionsGroup = { - axis: 'y', - distance: 10, - tolerance: "pointer", - opacity: 0.7, - scroll: true, - cursor: "move", - placeholder: "umb-group-builder__group-sortable-placeholder", - zIndex: 6000, - handle: ".umb-group-builder__group-handle", - items: ".umb-group-builder__group-sortable", - start: function(e, ui) { - ui.placeholder.height(ui.item.height()); - }, - stop: function(e, ui) { - updateTabsSortOrder(); - } - }; - - scope.sortableOptionsProperty = { - axis: 'y', - distance: 10, - tolerance: "pointer", - connectWith: ".umb-group-builder__properties", - opacity: 0.7, - scroll: true, - cursor: "move", - placeholder: "umb-group-builder__property_sortable-placeholder", - zIndex: 6000, - handle: ".umb-group-builder__property-handle", - items: ".umb-group-builder__property-sortable", - start: function(e, ui) { - ui.placeholder.height(ui.item.height()); - }, - stop: function(e, ui) { - updatePropertiesSortOrder(); - } - }; - - } - - function updateTabsSortOrder() { - - var first = true; - var prevSortOrder = 0; - - scope.model.groups.map(function(group){ - - var index = scope.model.groups.indexOf(group); - - if(group.tabState !== "init") { - - // set the first not inherited tab to sort order 0 - if(!group.inherited && first) { - - // set the first tab sort order to 0 if prev is 0 - if( prevSortOrder === 0 ) { - group.sortOrder = 0; - // when the first tab is inherited and sort order is not 0 - } else { - group.sortOrder = prevSortOrder + 1; - } - - first = false; - - } else if(!group.inherited && !first) { - - // find next group - var nextGroup = scope.model.groups[index + 1]; - - // if a groups is dropped in the middle of to groups with - // same sort order. Give it the dropped group same sort order - if( prevSortOrder === nextGroup.sortOrder ) { - group.sortOrder = prevSortOrder; - } else { - group.sortOrder = prevSortOrder + 1; + // set placeholder property on each group + if (scope.model.groups.length !== 0) { + angular.forEach(scope.model.groups, function (group) { + addInitProperty(group); + }); } + // add init tab + addInitGroup(scope.model.groups); + + activateFirstGroup(scope.model.groups); + + // localize texts + localizationService.localize("validation_validation").then(function (value) { + validationTranslated = value; + }); + + localizationService.localize("contentTypeEditor_tabHasNoSortOrder").then(function (value) { + tabNoSortOrderTranslated = value; + }); + } + + function setSortingOptions() { + + scope.sortableOptionsGroup = { + axis: 'y', + distance: 10, + tolerance: "pointer", + opacity: 0.7, + scroll: true, + cursor: "move", + placeholder: "umb-group-builder__group-sortable-placeholder", + zIndex: 6000, + handle: ".umb-group-builder__group-handle", + items: ".umb-group-builder__group-sortable", + start: function (e, ui) { + ui.placeholder.height(ui.item.height()); + }, + stop: function (e, ui) { + updateTabsSortOrder(); + } + }; + + scope.sortableOptionsProperty = { + axis: 'y', + distance: 10, + tolerance: "pointer", + connectWith: ".umb-group-builder__properties", + opacity: 0.7, + scroll: true, + cursor: "move", + placeholder: "umb-group-builder__property_sortable-placeholder", + zIndex: 6000, + handle: ".umb-group-builder__property-handle", + items: ".umb-group-builder__property-sortable", + start: function (e, ui) { + ui.placeholder.height(ui.item.height()); + }, + stop: function (e, ui) { + updatePropertiesSortOrder(); + } + }; + } - // store this tabs sort order as reference for the next - prevSortOrder = group.sortOrder; + function updateTabsSortOrder() { - } + var first = true; + var prevSortOrder = 0; - }); + scope.model.groups.map(function (group) { - } + var index = scope.model.groups.indexOf(group); - function filterAvailableCompositions(selectedContentType, selecting) { + if (group.tabState !== "init") { - //selecting = true if the user has check the item, false if the user has unchecked the item + // set the first not inherited tab to sort order 0 + if (!group.inherited && first) { + + // set the first tab sort order to 0 if prev is 0 + if (prevSortOrder === 0) { + group.sortOrder = 0; + // when the first tab is inherited and sort order is not 0 + } else { + group.sortOrder = prevSortOrder + 1; + } + + first = false; + + } else if (!group.inherited && !first) { + + // find next group + var nextGroup = scope.model.groups[index + 1]; + + // if a groups is dropped in the middle of to groups with + // same sort order. Give it the dropped group same sort order + if (prevSortOrder === nextGroup.sortOrder) { + group.sortOrder = prevSortOrder; + } else { + group.sortOrder = prevSortOrder + 1; + } + + } + + // store this tabs sort order as reference for the next + prevSortOrder = group.sortOrder; + + } - var selectedContentTypeAliases = selecting ? - //the user has selected the item so add to the current list - _.union(scope.compositionsDialogModel.compositeContentTypes, [selectedContentType.alias]) : - //the user has unselected the item so remove from the current list - _.reject(scope.compositionsDialogModel.compositeContentTypes, function(i) { - return i === selectedContentType.alias; }); - //get the currently assigned property type aliases - ensure we pass these to the server side filer - var propAliasesExisting = _.filter(_.flatten(_.map(scope.model.groups, function(g) { - return _.map(g.properties, function(p) { - return p.alias; - }); - })), function (f) { - return f !== null && f !== undefined; - }); + } - //use a different resource lookup depending on the content type type - var resourceLookup = scope.contentType === "documentType" ? contentTypeResource.getAvailableCompositeContentTypes : mediaTypeResource.getAvailableCompositeContentTypes; + function filterAvailableCompositions(selectedContentType, selecting) { - return resourceLookup(scope.model.id, selectedContentTypeAliases, propAliasesExisting).then(function (filteredAvailableCompositeTypes) { - _.each(scope.compositionsDialogModel.availableCompositeContentTypes, function (current) { - //reset first - current.allowed = true; - //see if this list item is found in the response (allowed) list - var found = _.find(filteredAvailableCompositeTypes, function (f) { - return current.contentType.alias === f.contentType.alias; + //selecting = true if the user has check the item, false if the user has unchecked the item + + var selectedContentTypeAliases = selecting ? + //the user has selected the item so add to the current list + _.union(scope.compositionsDialogModel.compositeContentTypes, [selectedContentType.alias]) : + //the user has unselected the item so remove from the current list + _.reject(scope.compositionsDialogModel.compositeContentTypes, function (i) { + return i === selectedContentType.alias; }); - //allow if the item was found in the response (allowed) list - - // and ensure its set to allowed if it is currently checked, - // DO not allow if it's a locked content type. - current.allowed = scope.model.lockedCompositeContentTypes.indexOf(current.contentType.alias) === -1 && - (selectedContentTypeAliases.indexOf(current.contentType.alias) !== -1) || ((found !== null && found !== undefined) ? found.allowed : false); - + //get the currently assigned property type aliases - ensure we pass these to the server side filer + var propAliasesExisting = _.filter(_.flatten(_.map(scope.model.groups, function (g) { + return _.map(g.properties, function (p) { + return p.alias; + }); + })), function (f) { + return f !== null && f !== undefined; }); - }); - } - function updatePropertiesSortOrder() { + //use a different resource lookup depending on the content type type + var resourceLookup = scope.contentType === "documentType" ? contentTypeResource.getAvailableCompositeContentTypes : mediaTypeResource.getAvailableCompositeContentTypes; - angular.forEach(scope.model.groups, function(group){ - if( group.tabState !== "init" ) { - group.properties = contentTypeHelper.updatePropertiesSortOrder(group.properties); - } - }); + return resourceLookup(scope.model.id, selectedContentTypeAliases, propAliasesExisting).then(function (filteredAvailableCompositeTypes) { + _.each(scope.compositionsDialogModel.availableCompositeContentTypes, function (current) { + //reset first + current.allowed = true; + //see if this list item is found in the response (allowed) list + var found = _.find(filteredAvailableCompositeTypes, function (f) { + return current.contentType.alias === f.contentType.alias; + }); - } + //allow if the item was found in the response (allowed) list - + // and ensure its set to allowed if it is currently checked, + // DO not allow if it's a locked content type. + current.allowed = scope.model.lockedCompositeContentTypes.indexOf(current.contentType.alias) === -1 && + (selectedContentTypeAliases.indexOf(current.contentType.alias) !== -1) || ((found !== null && found !== undefined) ? found.allowed : false); + + }); + }); + } + + function updatePropertiesSortOrder() { + + angular.forEach(scope.model.groups, function (group) { + if (group.tabState !== "init") { + group.properties = contentTypeHelper.updatePropertiesSortOrder(group.properties); + } + }); + + } + + function setupAvailableContentTypesModel(result) { + scope.compositionsDialogModel.availableCompositeContentTypes = result; + //iterate each one and set it up + _.each(scope.compositionsDialogModel.availableCompositeContentTypes, function (c) { + //enable it if it's part of the selected model + if (scope.compositionsDialogModel.compositeContentTypes.indexOf(c.contentType.alias) !== -1) { + c.allowed = true; + } + + //set the inherited flags + c.inherited = false; + if (scope.model.lockedCompositeContentTypes.indexOf(c.contentType.alias) > -1) { + c.inherited = true; + } + // convert icons for composite content types + iconHelper.formatContentTypeIcons([c.contentType]); + }); + } + + /* ---------- DELETE PROMT ---------- */ + + scope.togglePrompt = function (object) { + object.deletePrompt = !object.deletePrompt; + }; + + scope.hidePrompt = function (object) { + object.deletePrompt = false; + }; + + /* ---------- TOOLBAR ---------- */ + + scope.toggleSortingMode = function (tool) { + + if (scope.sortingMode === true) { + + var sortOrderMissing = false; + + for (var i = 0; i < scope.model.groups.length; i++) { + var group = scope.model.groups[i]; + if (group.tabState !== "init" && group.sortOrder === undefined) { + sortOrderMissing = true; + group.showSortOrderMissing = true; + notificationsService.error(validationTranslated + ": " + group.name + " " + tabNoSortOrderTranslated); + } + } + + if (!sortOrderMissing) { + scope.sortingMode = false; + scope.sortingButtonKey = "general_reorder"; + } + + } else { + + scope.sortingMode = true; + scope.sortingButtonKey = "general_reorderDone"; - function setupAvailableContentTypesModel(result) { - scope.compositionsDialogModel.availableCompositeContentTypes = result; - //iterate each one and set it up - _.each(scope.compositionsDialogModel.availableCompositeContentTypes, function (c) { - //enable it if it's part of the selected model - if (scope.compositionsDialogModel.compositeContentTypes.indexOf(c.contentType.alias) !== -1) { - c.allowed = true; } - //set the inherited flags - c.inherited = false; - if (scope.model.lockedCompositeContentTypes.indexOf(c.contentType.alias) > -1) { - c.inherited = true; - } - // convert icons for composite content types - iconHelper.formatContentTypeIcons([c.contentType]); - }); - } + }; - /* ---------- DELETE PROMT ---------- */ + scope.openCompositionsDialog = function () { - scope.togglePrompt = function (object) { - object.deletePrompt = !object.deletePrompt; - }; + scope.compositionsDialogModel = { + contentType: scope.model, + compositeContentTypes: scope.model.compositeContentTypes, + view: "views/common/infiniteeditors/compositions/compositions.html", + size: "small", + submit: function () { - scope.hidePrompt = function (object) { - object.deletePrompt = false; - }; + // make sure that all tabs has an init property + if (scope.model.groups.length !== 0) { + angular.forEach(scope.model.groups, function (group) { + addInitProperty(group); + }); + } - /* ---------- TOOLBAR ---------- */ + // remove overlay + editorService.close(); - scope.toggleSortingMode = function(tool) { + }, + close: function (oldModel) { - if (scope.sortingMode === true) { + // reset composition changes + scope.model.groups = oldModel.contentType.groups; + scope.model.compositeContentTypes = oldModel.contentType.compositeContentTypes; - var sortOrderMissing = false; + // remove overlay + editorService.close(); - for (var i = 0; i < scope.model.groups.length; i++) { - var group = scope.model.groups[i]; - if (group.tabState !== "init" && group.sortOrder === undefined) { - sortOrderMissing = true; - group.showSortOrderMissing = true; - notificationsService.error(validationTranslated + ": " + group.name + " " + tabNoSortOrderTranslated); - } - } + }, + selectCompositeContentType: function (selectedContentType) { - if (!sortOrderMissing) { - scope.sortingMode = false; - scope.sortingButtonKey = "general_reorder"; - } + //first check if this is a new selection - we need to store this value here before any further digests/async + // because after that the scope.model.compositeContentTypes will be populated with the selected value. + var newSelection = scope.model.compositeContentTypes.indexOf(selectedContentType.alias) === -1; - } else { + if (newSelection) { + //merge composition with content type - scope.sortingMode = true; - scope.sortingButtonKey = "general_reorderDone"; + //use a different resource lookup depending on the content type type + var resourceLookup = scope.contentType === "documentType" ? contentTypeResource.getById : mediaTypeResource.getById; - } + resourceLookup(selectedContentType.id).then(function (composition) { + //based on the above filtering we shouldn't be able to select an invalid one, but let's be safe and + // double check here. + var overlappingAliases = contentTypeHelper.validateAddingComposition(scope.model, composition); + if (overlappingAliases.length > 0) { + //this will create an invalid composition, need to uncheck it + scope.compositionsDialogModel.compositeContentTypes.splice( + scope.compositionsDialogModel.compositeContentTypes.indexOf(composition.alias), 1); + //dissallow this until something else is unchecked + selectedContentType.allowed = false; + } + else { + contentTypeHelper.mergeCompositeContentType(scope.model, composition); + } - }; - - scope.openCompositionsDialog = function() { - - scope.compositionsDialogModel = { - contentType: scope.model, - compositeContentTypes: scope.model.compositeContentTypes, - view: "views/common/infiniteeditors/compositions/compositions.html", - size: "small", - submit: function() { - - // make sure that all tabs has an init property - if (scope.model.groups.length !== 0) { - angular.forEach(scope.model.groups, function(group) { - addInitProperty(group); - }); - } - - // remove overlay - editorService.close(); - - }, - close: function(oldModel) { - - // reset composition changes - scope.model.groups = oldModel.contentType.groups; - scope.model.compositeContentTypes = oldModel.contentType.compositeContentTypes; - - // remove overlay - editorService.close(); - - }, - selectCompositeContentType: function (selectedContentType) { - - //first check if this is a new selection - we need to store this value here before any further digests/async - // because after that the scope.model.compositeContentTypes will be populated with the selected value. - var newSelection = scope.model.compositeContentTypes.indexOf(selectedContentType.alias) === -1; - - if (newSelection) { - //merge composition with content type - - //use a different resource lookup depending on the content type type - var resourceLookup = scope.contentType === "documentType" ? contentTypeResource.getById : mediaTypeResource.getById; - - resourceLookup(selectedContentType.id).then(function (composition) { - //based on the above filtering we shouldn't be able to select an invalid one, but let's be safe and - // double check here. - var overlappingAliases = contentTypeHelper.validateAddingComposition(scope.model, composition); - if (overlappingAliases.length > 0) { - //this will create an invalid composition, need to uncheck it - scope.compositionsDialogModel.compositeContentTypes.splice( - scope.compositionsDialogModel.compositeContentTypes.indexOf(composition.alias), 1); - //dissallow this until something else is unchecked - selectedContentType.allowed = false; + //based on the selection, we need to filter the available composite types list + filterAvailableCompositions(selectedContentType, newSelection).then(function () { + // TODO: Here we could probably re-enable selection if we previously showed a throbber or something + }); + }); } else { - contentTypeHelper.mergeCompositeContentType(scope.model, composition); + // split composition from content type + contentTypeHelper.splitCompositeContentType(scope.model, selectedContentType); + + //based on the selection, we need to filter the available composite types list + filterAvailableCompositions(selectedContentType, newSelection).then(function () { + // TODO: Here we could probably re-enable selection if we previously showed a throbber or something + }); } - //based on the selection, we need to filter the available composite types list - filterAvailableCompositions(selectedContentType, newSelection).then(function () { - // TODO: Here we could probably re-enable selection if we previously showed a throbber or something - }); - }); - } - else { - // split composition from content type - contentTypeHelper.splitCompositeContentType(scope.model, selectedContentType); + } + }; - //based on the selection, we need to filter the available composite types list - filterAvailableCompositions(selectedContentType, newSelection).then(function () { - // TODO: Here we could probably re-enable selection if we previously showed a throbber or something + //select which resource methods to use, eg document Type or Media Type versions + var availableContentTypeResource = scope.contentType === "documentType" ? contentTypeResource.getAvailableCompositeContentTypes : mediaTypeResource.getAvailableCompositeContentTypes; + var whereUsedContentTypeResource = scope.contentType === "documentType" ? contentTypeResource.getWhereCompositionIsUsedInContentTypes : mediaTypeResource.getWhereCompositionIsUsedInContentTypes; + var countContentTypeResource = scope.contentType === "documentType" ? contentTypeResource.getCount : mediaTypeResource.getCount; + + //get the currently assigned property type aliases - ensure we pass these to the server side filer + var propAliasesExisting = _.filter(_.flatten(_.map(scope.model.groups, function (g) { + return _.map(g.properties, function (p) { + return p.alias; }); + })), function (f) { + return f !== null && f !== undefined; + }); + scope.compositionsButtonState = "busy"; + $q.all([ + //get available composite types + availableContentTypeResource(scope.model.id, [], propAliasesExisting, scope.model.isElement).then(function (result) { + setupAvailableContentTypesModel(result); + }), + //get where used document types + whereUsedContentTypeResource(scope.model.id).then(function (whereUsed) { + //pass to the dialog model the content type eg documentType or mediaType + scope.compositionsDialogModel.section = scope.contentType; + //pass the list of 'where used' document types + scope.compositionsDialogModel.whereCompositionUsed = whereUsed; + }), + //get content type count + countContentTypeResource().then(function (result) { + scope.compositionsDialogModel.totalContentTypes = parseInt(result, 10); + }) + ]).then(function () { + //resolves when both other promises are done, now show it + editorService.open(scope.compositionsDialogModel); + scope.compositionsButtonState = "init"; + }); + + }; + + + scope.openDocumentType = function (documentTypeId) { + const editor = { + id: documentTypeId, + submit: function (model) { + const args = { node: scope.model }; + eventsService.emit("editors.documentType.reload", args); + editorService.close(); + }, + close: function () { + editorService.close(); + } + }; + editorService.documentTypeEditor(editor); + + }; + + /* ---------- GROUPS ---------- */ + + scope.addGroup = function (group) { + + // set group sort order + var index = scope.model.groups.indexOf(group); + var prevGroup = scope.model.groups[index - 1]; + + if (index > 0) { + // set index to 1 higher than the previous groups sort order + group.sortOrder = prevGroup.sortOrder + 1; + + } else { + // first group - sort order will be 0 + group.sortOrder = 0; } + // activate group + scope.activateGroup(group); + + // push new init tab to the scope + addInitGroup(scope.model.groups); + }; + + scope.activateGroup = function (selectedGroup) { + + // set all other groups that are inactive to active + angular.forEach(scope.model.groups, function (group) { + // skip init tab + if (group.tabState !== "init") { + group.tabState = "inActive"; + } + }); + + selectedGroup.tabState = "active"; + + }; + + scope.canRemoveGroup = function (group) { + return group.inherited !== true && _.find(group.properties, function (property) { return property.locked === true; }) == null; } - }; - //select which resource methods to use, eg document Type or Media Type versions - var availableContentTypeResource = scope.contentType === "documentType" ? contentTypeResource.getAvailableCompositeContentTypes : mediaTypeResource.getAvailableCompositeContentTypes; - var whereUsedContentTypeResource = scope.contentType === "documentType" ? contentTypeResource.getWhereCompositionIsUsedInContentTypes : mediaTypeResource.getWhereCompositionIsUsedInContentTypes; - var countContentTypeResource = scope.contentType === "documentType" ? contentTypeResource.getCount : mediaTypeResource.getCount; + scope.removeGroup = function (groupIndex) { + scope.model.groups.splice(groupIndex, 1); + }; - //get the currently assigned property type aliases - ensure we pass these to the server side filer - var propAliasesExisting = _.filter(_.flatten(_.map(scope.model.groups, function(g) { - return _.map(g.properties, function(p) { - return p.alias; - }); - })), function(f) { - return f !== null && f !== undefined; - }); - scope.compositionsButtonState = "busy"; - $q.all([ - //get available composite types - availableContentTypeResource(scope.model.id, [], propAliasesExisting, scope.model.isElement).then(function (result) { - setupAvailableContentTypesModel(result); - }), - //get where used document types - whereUsedContentTypeResource(scope.model.id).then(function (whereUsed) { - //pass to the dialog model the content type eg documentType or mediaType - scope.compositionsDialogModel.section = scope.contentType; - //pass the list of 'where used' document types - scope.compositionsDialogModel.whereCompositionUsed = whereUsed; - }), - //get content type count - countContentTypeResource().then(function(result) { - scope.compositionsDialogModel.totalContentTypes = parseInt(result, 10); - }) - ]).then(function() { - //resolves when both other promises are done, now show it - editorService.open(scope.compositionsDialogModel); - scope.compositionsButtonState = "init"; - }); + scope.updateGroupTitle = function (group) { + if (group.properties.length === 0) { + addInitProperty(group); + } + }; - }; + scope.changeSortOrderValue = function (group) { + + if (group.sortOrder !== undefined) { + group.showSortOrderMissing = false; + } + scope.model.groups = $filter('orderBy')(scope.model.groups, 'sortOrder'); + }; + + function addInitGroup(groups) { + + // check i init tab already exists + var addGroup = true; + + angular.forEach(groups, function (group) { + if (group.tabState === "init") { + addGroup = false; + } + }); + + if (addGroup) { + groups.push({ + properties: [], + parentTabContentTypes: [], + parentTabContentTypeNames: [], + name: "", + tabState: "init" + }); + } + + return groups; + } + + function activateFirstGroup(groups) { + if (groups && groups.length > 0) { + var firstGroup = groups[0]; + if (!firstGroup.tabState || firstGroup.tabState === "inActive") { + firstGroup.tabState = "active"; + } + } + } + + /* ---------- PROPERTIES ---------- */ + + scope.addPropertyToActiveGroup = function () { + var group = _.find(scope.model.groups, group => group.tabState === "active"); + if (!group && scope.model.groups.length) { + group = scope.model.groups[0]; + } + + if (!group || !group.name) { + return; + } + + var property = _.find(group.properties, property => property.propertyState === "init"); + if (!property) { + return; + } + scope.addProperty(property, group); + } + + scope.addProperty = function (property, group) { + + // set property sort order + var index = group.properties.indexOf(property); + var prevProperty = group.properties[index - 1]; + + if (index > 0) { + // set index to 1 higher than the previous property sort order + property.sortOrder = prevProperty.sortOrder + 1; + + } else { + // first property - sort order will be 0 + property.sortOrder = 0; + } + + // open property settings dialog + scope.editPropertyTypeSettings(property, group); + + }; + + scope.editPropertyTypeSettings = function (property, group) { + + if (!property.inherited) { + + var oldPropertyModel = Utilities.copy(property); + if (oldPropertyModel.allowCultureVariant === undefined) { + // this is necessary for comparison when detecting changes to the property + oldPropertyModel.allowCultureVariant = scope.model.allowCultureVariant; + oldPropertyModel.alias = ""; + } + var propertyModel = Utilities.copy(property); + + var propertySettings = { + title: "Property settings", + property: propertyModel, + contentType: scope.contentType, + contentTypeName: scope.model.name, + contentTypeAllowCultureVariant: scope.model.allowCultureVariant, + view: "views/common/infiniteeditors/propertysettings/propertysettings.html", + size: "small", + submit: function (model) { + + property.inherited = false; + property.dialogIsOpen = false; + property.propertyState = "active"; + + // apply all property changes + property.label = propertyModel.label; + property.alias = propertyModel.alias; + property.description = propertyModel.description; + property.config = propertyModel.config; + property.editor = propertyModel.editor; + property.view = propertyModel.view; + property.dataTypeId = propertyModel.dataTypeId; + property.dataTypeIcon = propertyModel.dataTypeIcon; + property.dataTypeName = propertyModel.dataTypeName; + property.validation.mandatory = propertyModel.validation.mandatory; + property.validation.mandatoryMessage = propertyModel.validation.mandatoryMessage; + property.validation.pattern = propertyModel.validation.pattern; + property.validation.patternMessage = propertyModel.validation.patternMessage; + property.showOnMemberProfile = propertyModel.showOnMemberProfile; + property.memberCanEdit = propertyModel.memberCanEdit; + property.isSensitiveData = propertyModel.isSensitiveData; + property.isSensitiveValue = propertyModel.isSensitiveValue; + property.allowCultureVariant = propertyModel.allowCultureVariant; + + // update existing data types + if (model.updateSameDataTypes) { + updateSameDataTypes(property); + } + + // close the editor + editorService.close(); + + // push new init property to group + addInitProperty(group); + + // set focus on init property + var numberOfProperties = group.properties.length; + group.properties[numberOfProperties - 1].focus = true; + + notifyChanged(); + }, + close: function () { + if (_.isEqual(oldPropertyModel, propertyModel) === false) { + localizationService.localizeMany(["general_confirm", "contentTypeEditor_propertyHasChanges", "general_cancel", "general_ok"]).then(function (data) { + const overlay = { + title: data[0], + content: data[1], + closeButtonLabel: data[2], + submitButtonLabel: data[3], + submitButtonStyle: "danger", + close: function () { + overlayService.close(); + }, + submit: function () { + // close the confirmation + overlayService.close(); + // close the editor + editorService.close(); + } + }; + + overlayService.open(overlay); + }); + } + else { + // remove the editor + editorService.close(); + } + } + }; + + // open property settings editor + editorService.open(propertySettings); + + // set property states + property.dialogIsOpen = true; + + } + }; + + scope.deleteProperty = function (tab, propertyIndex) { + + // remove property + tab.properties.splice(propertyIndex, 1); + + notifyChanged(); + }; + + function notifyChanged() { + eventsService.emit("editors.groupsBuilder.changed"); + } + + function addInitProperty(group) { + + var addInitPropertyBool = true; + var initProperty = { + label: null, + alias: null, + propertyState: "init", + validation: { + mandatory: false, + mandatoryMessage: null, + pattern: null, + patternMessage: null + } + }; + + // check if there already is an init property + angular.forEach(group.properties, function (property) { + if (property.propertyState === "init") { + addInitPropertyBool = false; + } + }); + + if (addInitPropertyBool) { + group.properties.push(initProperty); + } + + return group; + } + + function updateSameDataTypes(newProperty) { + + // find each property + angular.forEach(scope.model.groups, function (group) { + angular.forEach(group.properties, function (property) { + + if (property.dataTypeId === newProperty.dataTypeId) { + + // update property data + property.config = newProperty.config; + property.editor = newProperty.editor; + property.view = newProperty.view; + property.dataTypeId = newProperty.dataTypeId; + property.dataTypeIcon = newProperty.dataTypeIcon; + property.dataTypeName = newProperty.dataTypeName; + + } + + }); + }); + } + + function hasPropertyOfDataTypeId(dataTypeId) { + + // look at each property + var result = _.filter(scope.model.groups, function (group) { + return _.filter(group.properties, function (property) { + return (property.dataTypeId === dataTypeId); + }); + }); + + return (result.length > 0); + } - scope.openDocumentType = function (documentTypeId) { - const editor = { - id: documentTypeId, - submit: function (model) { - const args = { node: scope.model }; - eventsService.emit("editors.documentType.reload", args); - editorService.close(); - }, - close: function () { - editorService.close(); - } - }; - editorService.documentTypeEditor(editor); + eventBindings.push(scope.$watch('model', function (newValue, oldValue) { + if (newValue !== undefined && newValue.groups !== undefined) { + activate(); + } + })); - }; + // clean up + eventBindings.push(eventsService.on("editors.dataTypeSettings.saved", function (name, args) { + if (hasPropertyOfDataTypeId(args.dataType.id)) { + scope.dataTypeHasChanged = true; + } + })); - /* ---------- GROUPS ---------- */ + // clean up + eventBindings.push(scope.$on('$destroy', function () { + for (var e in eventBindings) { + eventBindings[e](); + } + // if a dataType has changed, we want to notify which properties that are affected by this dataTypeSettings change + if (scope.dataTypeHasChanged === true) { + var args = { documentType: scope.model }; + eventsService.emit("editors.documentType.saved", args); + } + })); - scope.addGroup = function(group) { - - // set group sort order - var index = scope.model.groups.indexOf(group); - var prevGroup = scope.model.groups[index - 1]; - - if( index > 0) { - // set index to 1 higher than the previous groups sort order - group.sortOrder = prevGroup.sortOrder + 1; - - } else { - // first group - sort order will be 0 - group.sortOrder = 0; } - // activate group - scope.activateGroup(group); - - // push new init tab to the scope - addInitGroup(scope.model.groups); - }; - - scope.activateGroup = function(selectedGroup) { - - // set all other groups that are inactive to active - angular.forEach(scope.model.groups, function(group) { - // skip init tab - if (group.tabState !== "init") { - group.tabState = "inActive"; - } - }); - - selectedGroup.tabState = "active"; - - }; - - scope.canRemoveGroup = function(group){ - return group.inherited !== true && _.find(group.properties, function(property) { return property.locked === true; }) == null; - } - - scope.removeGroup = function(groupIndex) { - scope.model.groups.splice(groupIndex, 1); - }; - - scope.updateGroupTitle = function(group) { - if (group.properties.length === 0) { - addInitProperty(group); - } - }; - - scope.changeSortOrderValue = function(group) { - - if (group.sortOrder !== undefined) { - group.showSortOrderMissing = false; - } - scope.model.groups = $filter('orderBy')(scope.model.groups, 'sortOrder'); - }; - - function addInitGroup(groups) { - - // check i init tab already exists - var addGroup = true; - - angular.forEach(groups, function(group) { - if (group.tabState === "init") { - addGroup = false; - } - }); - - if (addGroup) { - groups.push({ - properties: [], - parentTabContentTypes: [], - parentTabContentTypeNames: [], - name: "", - tabState: "init" - }); - } - - return groups; - } - - function activateFirstGroup(groups) { - if (groups && groups.length > 0) { - var firstGroup = groups[0]; - if(!firstGroup.tabState || firstGroup.tabState === "inActive") { - firstGroup.tabState = "active"; - } - } - } - - /* ---------- PROPERTIES ---------- */ - - scope.addPropertyToActiveGroup = function () { - var group = _.find(scope.model.groups, group => group.tabState === "active"); - if (!group && scope.model.groups.length) { - group = scope.model.groups[0]; - } - - if (!group || !group.name) { - return; - } - - var property = _.find(group.properties, property => property.propertyState === "init"); - if (!property) { - return; - } - scope.addProperty(property, group); - } - - scope.addProperty = function(property, group) { - - // set property sort order - var index = group.properties.indexOf(property); - var prevProperty = group.properties[index - 1]; - - if( index > 0) { - // set index to 1 higher than the previous property sort order - property.sortOrder = prevProperty.sortOrder + 1; - - } else { - // first property - sort order will be 0 - property.sortOrder = 0; - } - - // open property settings dialog - scope.editPropertyTypeSettings(property, group); - - }; - - scope.editPropertyTypeSettings = function(property, group) { - - if (!property.inherited) { - - var oldPropertyModel = angular.copy(property); - if (oldPropertyModel.allowCultureVariant === undefined) { - // this is necessary for comparison when detecting changes to the property - oldPropertyModel.allowCultureVariant = scope.model.allowCultureVariant; - oldPropertyModel.alias = ""; - } - var propertyModel = angular.copy(property); - - var propertySettings = { - title: "Property settings", - property: propertyModel, - contentType: scope.contentType, - contentTypeName: scope.model.name, - contentTypeAllowCultureVariant: scope.model.allowCultureVariant, - view: "views/common/infiniteeditors/propertysettings/propertysettings.html", - size: "small", - submit: function(model) { - - property.inherited = false; - property.dialogIsOpen = false; - property.propertyState = "active"; - - // apply all property changes - property.label = propertyModel.label; - property.alias = propertyModel.alias; - property.description = propertyModel.description; - property.config = propertyModel.config; - property.editor = propertyModel.editor; - property.view = propertyModel.view; - property.dataTypeId = propertyModel.dataTypeId; - property.dataTypeIcon = propertyModel.dataTypeIcon; - property.dataTypeName = propertyModel.dataTypeName; - property.validation.mandatory = propertyModel.validation.mandatory; - property.validation.mandatoryMessage = propertyModel.validation.mandatoryMessage; - property.validation.pattern = propertyModel.validation.pattern; - property.validation.patternMessage = propertyModel.validation.patternMessage; - property.showOnMemberProfile = propertyModel.showOnMemberProfile; - property.memberCanEdit = propertyModel.memberCanEdit; - property.isSensitiveData = propertyModel.isSensitiveData; - property.isSensitiveValue = propertyModel.isSensitiveValue; - property.allowCultureVariant = propertyModel.allowCultureVariant; - - // update existing data types - if(model.updateSameDataTypes) { - updateSameDataTypes(property); - } - - // close the editor - editorService.close(); - - // push new init property to group - addInitProperty(group); - - // set focus on init property - var numberOfProperties = group.properties.length; - group.properties[numberOfProperties - 1].focus = true; - - notifyChanged(); + var directive = { + restrict: "E", + replace: true, + templateUrl: "views/components/umb-groups-builder.html", + scope: { + model: "=", + compositions: "=", + sorting: "=", + contentType: "@" }, - close: function() { - if(_.isEqual(oldPropertyModel, propertyModel) === false) { - localizationService.localizeMany(["general_confirm", "contentTypeEditor_propertyHasChanges", "general_cancel", "general_ok"]).then(function (data) { - const overlay = { - title: data[0], - content: data[1], - closeButtonLabel: data[2], - submitButtonLabel: data[3], - submitButtonStyle: "danger", - close: function () { - overlayService.close(); - }, - submit: function () { - // close the confirmation - overlayService.close(); - // close the editor - editorService.close(); - } - }; - - overlayService.open(overlay); - }); - } - else { - // remove the editor - editorService.close(); - } - } - }; - - // open property settings editor - editorService.open(propertySettings); - - // set property states - property.dialogIsOpen = true; - - } - }; - - scope.deleteProperty = function(tab, propertyIndex) { - - // remove property - tab.properties.splice(propertyIndex, 1); - - notifyChanged(); - }; - - function notifyChanged() { - eventsService.emit("editors.groupsBuilder.changed"); - } - - function addInitProperty(group) { - - var addInitPropertyBool = true; - var initProperty = { - label: null, - alias: null, - propertyState: "init", - validation: { - mandatory: false, - mandatoryMessage: null, - pattern: null, - patternMessage: null - } + link: link }; - // check if there already is an init property - angular.forEach(group.properties, function(property) { - if (property.propertyState === "init") { - addInitPropertyBool = false; - } - }); - - if (addInitPropertyBool) { - group.properties.push(initProperty); - } - - return group; - } - - function updateSameDataTypes(newProperty) { - - // find each property - angular.forEach(scope.model.groups, function(group){ - angular.forEach(group.properties, function(property){ - - if(property.dataTypeId === newProperty.dataTypeId) { - - // update property data - property.config = newProperty.config; - property.editor = newProperty.editor; - property.view = newProperty.view; - property.dataTypeId = newProperty.dataTypeId; - property.dataTypeIcon = newProperty.dataTypeIcon; - property.dataTypeName = newProperty.dataTypeName; - - } - - }); - }); - } - - function hasPropertyOfDataTypeId(dataTypeId) { - - // look at each property - var result = _.filter(scope.model.groups, function(group) { - return _.filter(group.properties, function(property) { - return (property.dataTypeId === dataTypeId); - }); - }); - - return (result.length > 0); - } - - - eventBindings.push(scope.$watch('model', function(newValue, oldValue) { - if (newValue !== undefined && newValue.groups !== undefined) { - activate(); - } - })); - - // clean up - eventBindings.push(eventsService.on("editors.dataTypeSettings.saved", function (name, args) { - if(hasPropertyOfDataTypeId(args.dataType.id)) { - scope.dataTypeHasChanged = true; - } - })); - - // clean up - eventBindings.push(scope.$on('$destroy', function() { - for(var e in eventBindings) { - eventBindings[e](); - } - // if a dataType has changed, we want to notify which properties that are affected by this dataTypeSettings change - if(scope.dataTypeHasChanged === true) { - var args = {documentType: scope.model}; - eventsService.emit("editors.documentType.saved", args); - } - })); - + return directive; } - var directive = { - restrict: "E", - replace: true, - templateUrl: "views/components/umb-groups-builder.html", - scope: { - model: "=", - compositions: "=", - sorting: "=", - contentType: "@" - }, - link: link - }; - - return directive; - } - - angular.module('umbraco.directives').directive('umbGroupsBuilder', GroupsBuilderDirective); + angular.module('umbraco.directives').directive('umbGroupsBuilder', GroupsBuilderDirective); })(); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbnestedcontent.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbnestedcontent.directive.js index 471714d30b..72dba3ca2f 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbnestedcontent.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbnestedcontent.directive.js @@ -3,12 +3,12 @@ function () { var link = function ($scope) { - + // Clone the model because some property editors // do weird things like updating and config values // so we want to ensure we start from a fresh every // time, we'll just sync the value back when we need to - $scope.model = angular.copy($scope.ngModel); + $scope.model = Utilities.copy($scope.ngModel); $scope.nodeContext = $scope.model; // Find the selected tab @@ -31,7 +31,7 @@ // Tell inner controls we are submitting $scope.$broadcast("formSubmitting", { scope: $scope }); - + // Sync the values back angular.forEach($scope.ngModel.variants[0].tabs, function (tab) { if (tab.alias.toLowerCase() === selectedTab.alias.toLowerCase()) { diff --git a/src/Umbraco.Web.UI.Client/src/common/interceptors/donotpostdollarvariablesrequest.interceptor.js b/src/Umbraco.Web.UI.Client/src/common/interceptors/donotpostdollarvariablesrequest.interceptor.js index 03373089d7..f3dd60bdce 100644 --- a/src/Umbraco.Web.UI.Client/src/common/interceptors/donotpostdollarvariablesrequest.interceptor.js +++ b/src/Umbraco.Web.UI.Client/src/common/interceptors/donotpostdollarvariablesrequest.interceptor.js @@ -1,40 +1,40 @@ -(function() { - 'use strict'; - +(function () { + 'use strict'; + function removeProperty(obj, propertyPrefix) { for (var property in obj) { if (obj.hasOwnProperty(property)) { - + if (property.startsWith(propertyPrefix) && obj[property] !== undefined) { obj[property] = undefined; } - + if (typeof obj[property] === "object") { removeProperty(obj[property], propertyPrefix); } } } - + } - - function transform(data){ + + function transform(data) { removeProperty(data, "$"); } - + function doNotPostDollarVariablesRequestInterceptor($q, urlHelper) { return { //dealing with requests: - 'request': function(config) { - if(config.method === "POST"){ - var clone = angular.copy(config); + 'request': function (config) { + if (config.method === "POST") { + var clone = Utilities.copy(config); transform(clone.data); return clone; } - + return config; } }; - } + } angular.module('umbraco.interceptors').factory('doNotPostDollarVariablesOnPostRequestInterceptor', doNotPostDollarVariablesRequestInterceptor); })(); diff --git a/src/Umbraco.Web.UI.Client/src/common/services/contenttypehelper.service.js b/src/Umbraco.Web.UI.Client/src/common/services/contenttypehelper.service.js index 42431b751f..1be66cc68f 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/contenttypehelper.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/contenttypehelper.service.js @@ -7,21 +7,21 @@ function contentTypeHelper(contentTypeResource, dataTypeResource, $filter, $inje var contentTypeHelperService = { - createIdArray: function(array) { + createIdArray: function (array) { - var newArray = []; + var newArray = []; - angular.forEach(array, function(arrayItem){ + angular.forEach(array, function (arrayItem) { - if(Utilities.isObject(arrayItem)) { - newArray.push(arrayItem.id); - } else { - newArray.push(arrayItem); - } + if (Utilities.isObject(arrayItem)) { + newArray.push(arrayItem.id); + } else { + newArray.push(arrayItem); + } - }); + }); - return newArray; + return newArray; }, @@ -30,18 +30,18 @@ function contentTypeHelper(contentTypeResource, dataTypeResource, $filter, $inje var modelsResource = $injector.has("modelsBuilderManagementResource") ? $injector.get("modelsBuilderManagementResource") : null; var modelsBuilderEnabled = Umbraco.Sys.ServerVariables.umbracoPlugins.modelsBuilder.enabled; if (modelsBuilderEnabled && modelsResource) { - modelsResource.buildModels().then(function(result) { + modelsResource.buildModels().then(function (result) { deferred.resolve(result); //just calling this to get the servar back to life modelsResource.getModelsOutOfDateStatus(); - }, function(e) { + }, function (e) { deferred.reject(e); }); } - else { - deferred.resolve(false); + else { + deferred.resolve(false); } return deferred.promise; }, @@ -49,10 +49,10 @@ function contentTypeHelper(contentTypeResource, dataTypeResource, $filter, $inje checkModelsBuilderStatus: function () { var deferred = $q.defer(); var modelsResource = $injector.has("modelsBuilderManagementResource") ? $injector.get("modelsBuilderManagementResource") : null; - var modelsBuilderEnabled = (Umbraco && Umbraco.Sys && Umbraco.Sys.ServerVariables && Umbraco.Sys.ServerVariables.umbracoPlugins && Umbraco.Sys.ServerVariables.umbracoPlugins.modelsBuilder && Umbraco.Sys.ServerVariables.umbracoPlugins.modelsBuilder.enabled === true); - + var modelsBuilderEnabled = (Umbraco && Umbraco.Sys && Umbraco.Sys.ServerVariables && Umbraco.Sys.ServerVariables.umbracoPlugins && Umbraco.Sys.ServerVariables.umbracoPlugins.modelsBuilder && Umbraco.Sys.ServerVariables.umbracoPlugins.modelsBuilder.enabled === true); + if (modelsBuilderEnabled && modelsResource) { - modelsResource.getModelsOutOfDateStatus().then(function(result) { + modelsResource.getModelsOutOfDateStatus().then(function (result) { //Generate models buttons should be enabled if it is 0 deferred.resolve(result.status === 0); }); @@ -64,37 +64,37 @@ function contentTypeHelper(contentTypeResource, dataTypeResource, $filter, $inje }, makeObjectArrayFromId: function (idArray, objectArray) { - var newArray = []; + var newArray = []; - for (var idIndex = 0; idArray.length > idIndex; idIndex++) { - var id = idArray[idIndex]; + for (var idIndex = 0; idArray.length > idIndex; idIndex++) { + var id = idArray[idIndex]; - for (var objectIndex = 0; objectArray.length > objectIndex; objectIndex++) { - var object = objectArray[objectIndex]; - if (id === object.id) { - newArray.push(object); - } - } + for (var objectIndex = 0; objectArray.length > objectIndex; objectIndex++) { + var object = objectArray[objectIndex]; + if (id === object.id) { + newArray.push(object); + } + } - } + } - return newArray; + return newArray; }, - validateAddingComposition: function(contentType, compositeContentType) { + validateAddingComposition: function (contentType, compositeContentType) { //Validate that by adding this group that we are not adding duplicate property type aliases - var propertiesAdding = _.flatten(_.map(compositeContentType.groups, function(g) { - return _.map(g.properties, function(p) { + var propertiesAdding = _.flatten(_.map(compositeContentType.groups, function (g) { + return _.map(g.properties, function (p) { return p.alias; }); })); - var propAliasesExisting = _.filter(_.flatten(_.map(contentType.groups, function(g) { - return _.map(g.properties, function(p) { + var propAliasesExisting = _.filter(_.flatten(_.map(contentType.groups, function (g) { + return _.map(g.properties, function (p) { return p.alias; }); - })), function(f) { + })), function (f) { return f !== null && f !== undefined; }); @@ -108,7 +108,7 @@ function contentTypeHelper(contentTypeResource, dataTypeResource, $filter, $inje return []; }, - mergeCompositeContentType: function(contentType, compositeContentType) { + mergeCompositeContentType: function (contentType, compositeContentType) { //Validate that there are no overlapping aliases var overlappingAliases = this.validateAddingComposition(contentType, compositeContentType); @@ -116,107 +116,107 @@ function contentTypeHelper(contentTypeResource, dataTypeResource, $filter, $inje throw new Error("Cannot add this composition, these properties already exist on the content type: " + overlappingAliases.join()); } - angular.forEach(compositeContentType.groups, function(compositionGroup) { + angular.forEach(compositeContentType.groups, function (compositionGroup) { - // order composition groups based on sort order - compositionGroup.properties = $filter('orderBy')(compositionGroup.properties, 'sortOrder'); + // order composition groups based on sort order + compositionGroup.properties = $filter('orderBy')(compositionGroup.properties, 'sortOrder'); - // get data type details - angular.forEach(compositionGroup.properties, function(property) { - dataTypeResource.getById(property.dataTypeId) - .then(function(dataType) { - property.dataTypeIcon = dataType.icon; - property.dataTypeName = dataType.name; - }); - }); + // get data type details + angular.forEach(compositionGroup.properties, function (property) { + dataTypeResource.getById(property.dataTypeId) + .then(function (dataType) { + property.dataTypeIcon = dataType.icon; + property.dataTypeName = dataType.name; + }); + }); - // set inherited state on tab - compositionGroup.inherited = true; + // set inherited state on tab + compositionGroup.inherited = true; - // set inherited state on properties - angular.forEach(compositionGroup.properties, function(compositionProperty) { - compositionProperty.inherited = true; - }); + // set inherited state on properties + angular.forEach(compositionGroup.properties, function (compositionProperty) { + compositionProperty.inherited = true; + }); - // set tab state - compositionGroup.tabState = "inActive"; + // set tab state + compositionGroup.tabState = "inActive"; - // if groups are named the same - merge the groups - angular.forEach(contentType.groups, function(contentTypeGroup) { + // if groups are named the same - merge the groups + angular.forEach(contentType.groups, function (contentTypeGroup) { - if (contentTypeGroup.name === compositionGroup.name) { + if (contentTypeGroup.name === compositionGroup.name) { - // set flag to show if properties has been merged into a tab - compositionGroup.groupIsMerged = true; + // set flag to show if properties has been merged into a tab + compositionGroup.groupIsMerged = true; - // make group inherited - contentTypeGroup.inherited = true; + // make group inherited + contentTypeGroup.inherited = true; - // add properties to the top of the array - contentTypeGroup.properties = compositionGroup.properties.concat(contentTypeGroup.properties); + // add properties to the top of the array + contentTypeGroup.properties = compositionGroup.properties.concat(contentTypeGroup.properties); - // update sort order on all properties in merged group - contentTypeGroup.properties = contentTypeHelperService.updatePropertiesSortOrder(contentTypeGroup.properties); + // update sort order on all properties in merged group + contentTypeGroup.properties = contentTypeHelperService.updatePropertiesSortOrder(contentTypeGroup.properties); + + // make parentTabContentTypeNames to an array so we can push values + if (contentTypeGroup.parentTabContentTypeNames === null || contentTypeGroup.parentTabContentTypeNames === undefined) { + contentTypeGroup.parentTabContentTypeNames = []; + } + + // push name to array of merged composite content types + contentTypeGroup.parentTabContentTypeNames.push(compositeContentType.name); + + // make parentTabContentTypes to an array so we can push values + if (contentTypeGroup.parentTabContentTypes === null || contentTypeGroup.parentTabContentTypes === undefined) { + contentTypeGroup.parentTabContentTypes = []; + } + + // push id to array of merged composite content types + contentTypeGroup.parentTabContentTypes.push(compositeContentType.id); + + // get sort order from composition + contentTypeGroup.sortOrder = compositionGroup.sortOrder; + + // splice group to the top of the array + var contentTypeGroupCopy = Utilities.copy(contentTypeGroup); + var index = contentType.groups.indexOf(contentTypeGroup); + contentType.groups.splice(index, 1); + contentType.groups.unshift(contentTypeGroupCopy); + + } + + }); + + // if group is not merged - push it to the end of the array - before init tab + if (compositionGroup.groupIsMerged === false || compositionGroup.groupIsMerged === undefined) { // make parentTabContentTypeNames to an array so we can push values - if (contentTypeGroup.parentTabContentTypeNames === null || contentTypeGroup.parentTabContentTypeNames === undefined) { - contentTypeGroup.parentTabContentTypeNames = []; + if (compositionGroup.parentTabContentTypeNames === null || compositionGroup.parentTabContentTypeNames === undefined) { + compositionGroup.parentTabContentTypeNames = []; } // push name to array of merged composite content types - contentTypeGroup.parentTabContentTypeNames.push(compositeContentType.name); + compositionGroup.parentTabContentTypeNames.push(compositeContentType.name); // make parentTabContentTypes to an array so we can push values - if (contentTypeGroup.parentTabContentTypes === null || contentTypeGroup.parentTabContentTypes === undefined) { - contentTypeGroup.parentTabContentTypes = []; + if (compositionGroup.parentTabContentTypes === null || compositionGroup.parentTabContentTypes === undefined) { + compositionGroup.parentTabContentTypes = []; } // push id to array of merged composite content types - contentTypeGroup.parentTabContentTypes.push(compositeContentType.id); + compositionGroup.parentTabContentTypes.push(compositeContentType.id); - // get sort order from composition - contentTypeGroup.sortOrder = compositionGroup.sortOrder; + // push group before placeholder tab + contentType.groups.unshift(compositionGroup); - // splice group to the top of the array - var contentTypeGroupCopy = angular.copy(contentTypeGroup); - var index = contentType.groups.indexOf(contentTypeGroup); - contentType.groups.splice(index, 1); - contentType.groups.unshift(contentTypeGroupCopy); + } - } + }); - }); + // sort all groups by sortOrder property + contentType.groups = $filter('orderBy')(contentType.groups, 'sortOrder'); - // if group is not merged - push it to the end of the array - before init tab - if (compositionGroup.groupIsMerged === false || compositionGroup.groupIsMerged === undefined) { - - // make parentTabContentTypeNames to an array so we can push values - if (compositionGroup.parentTabContentTypeNames === null || compositionGroup.parentTabContentTypeNames === undefined) { - compositionGroup.parentTabContentTypeNames = []; - } - - // push name to array of merged composite content types - compositionGroup.parentTabContentTypeNames.push(compositeContentType.name); - - // make parentTabContentTypes to an array so we can push values - if (compositionGroup.parentTabContentTypes === null || compositionGroup.parentTabContentTypes === undefined) { - compositionGroup.parentTabContentTypes = []; - } - - // push id to array of merged composite content types - compositionGroup.parentTabContentTypes.push(compositeContentType.id); - - // push group before placeholder tab - contentType.groups.unshift(compositionGroup); - - } - - }); - - // sort all groups by sortOrder property - contentType.groups = $filter('orderBy')(contentType.groups, 'sortOrder'); - - return contentType; + return contentType; }, @@ -224,22 +224,22 @@ function contentTypeHelper(contentTypeResource, dataTypeResource, $filter, $inje var groups = []; - angular.forEach(contentType.groups, function(contentTypeGroup){ + angular.forEach(contentType.groups, function (contentTypeGroup) { - if( contentTypeGroup.tabState !== "init" ) { + if (contentTypeGroup.tabState !== "init") { var idIndex = contentTypeGroup.parentTabContentTypes.indexOf(compositeContentType.id); var nameIndex = contentTypeGroup.parentTabContentTypeNames.indexOf(compositeContentType.name); var groupIndex = contentType.groups.indexOf(contentTypeGroup); - if( idIndex !== -1 ) { + if (idIndex !== -1) { var properties = []; // remove all properties from composite content type - angular.forEach(contentTypeGroup.properties, function(property){ - if(property.contentTypeId !== compositeContentType.id) { + angular.forEach(contentTypeGroup.properties, function (property) { + if (property.contentTypeId !== compositeContentType.id) { properties.push(property); } }); @@ -252,22 +252,22 @@ function contentTypeHelper(contentTypeResource, dataTypeResource, $filter, $inje contentTypeGroup.parentTabContentTypeNames.splice(nameIndex, 1); // remove inherited state if there are no inherited properties - if(contentTypeGroup.parentTabContentTypes.length === 0) { + if (contentTypeGroup.parentTabContentTypes.length === 0) { contentTypeGroup.inherited = false; } // remove group if there are no properties left - if(contentTypeGroup.properties.length > 1) { + if (contentTypeGroup.properties.length > 1) { //contentType.groups.splice(groupIndex, 1); groups.push(contentTypeGroup); } } else { - groups.push(contentTypeGroup); + groups.push(contentTypeGroup); } } else { - groups.push(contentTypeGroup); + groups.push(contentTypeGroup); } // update sort order on properties @@ -281,67 +281,67 @@ function contentTypeHelper(contentTypeResource, dataTypeResource, $filter, $inje updatePropertiesSortOrder: function (properties) { - var sortOrder = 0; + var sortOrder = 0; - angular.forEach(properties, function(property) { - if( !property.inherited && property.propertyState !== "init") { - property.sortOrder = sortOrder; - } - sortOrder++; - }); + angular.forEach(properties, function (property) { + if (!property.inherited && property.propertyState !== "init") { + property.sortOrder = sortOrder; + } + sortOrder++; + }); - return properties; + return properties; }, - getTemplatePlaceholder: function() { + getTemplatePlaceholder: function () { - var templatePlaceholder = { - "name": "", - "icon": "icon-layout", - "alias": "templatePlaceholder", - "placeholder": true - }; + var templatePlaceholder = { + "name": "", + "icon": "icon-layout", + "alias": "templatePlaceholder", + "placeholder": true + }; - return templatePlaceholder; + return templatePlaceholder; }, - insertDefaultTemplatePlaceholder: function(defaultTemplate) { + insertDefaultTemplatePlaceholder: function (defaultTemplate) { - // get template placeholder - var templatePlaceholder = contentTypeHelperService.getTemplatePlaceholder(); + // get template placeholder + var templatePlaceholder = contentTypeHelperService.getTemplatePlaceholder(); - // add as default template - defaultTemplate = templatePlaceholder; + // add as default template + defaultTemplate = templatePlaceholder; - return defaultTemplate; + return defaultTemplate; }, - insertTemplatePlaceholder: function(array) { + insertTemplatePlaceholder: function (array) { - // get template placeholder - var templatePlaceholder = contentTypeHelperService.getTemplatePlaceholder(); + // get template placeholder + var templatePlaceholder = contentTypeHelperService.getTemplatePlaceholder(); - // add as selected item - array.push(templatePlaceholder); + // add as selected item + array.push(templatePlaceholder); - return array; + return array; - }, + }, - insertChildNodePlaceholder: function (array, name, icon, id) { + insertChildNodePlaceholder: function (array, name, icon, id) { - var placeholder = { - "name": name, - "icon": icon, - "id": id - }; + var placeholder = { + "name": name, + "icon": icon, + "id": id + }; - array.push(placeholder); + array.push(placeholder); - } + } }; diff --git a/src/Umbraco.Web.UI.Client/src/common/services/editor.service.js b/src/Umbraco.Web.UI.Client/src/common/services/editor.service.js index 9c935086a0..538bd41ce0 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/editor.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/editor.service.js @@ -164,14 +164,14 @@ When building a custom infinite editor view you can use the same components as a "use strict"; function editorService(eventsService, keyboardService, $timeout) { - - + + let editorsKeyboardShorcuts = []; var editors = []; var isEnabled = true; var lastElementInFocus = null; - - + + // events for backdrop eventsService.on("appState.backdrop", function (name, args) { if (args.show === true) { @@ -180,7 +180,7 @@ When building a custom infinite editor view you can use the same components as a focus(); } }); - + /** * @ngdoc method @@ -205,7 +205,7 @@ When building a custom infinite editor view you can use the same components as a function getNumberOfEditors() { return editors.length; }; - + /** * @ngdoc method * @name umbraco.services.editorService#blur @@ -232,7 +232,7 @@ When building a custom infinite editor view you can use the same components as a * Method to tell editors that they are gaining focus again. */ function focus() { - if(isEnabled === false) { + if (isEnabled === false) { /* keyboard shortcuts will be overwritten by the new infinite editor so we need to store the shortcuts for the current editor so they can be rebound when the infinite editor closes @@ -241,7 +241,7 @@ When building a custom infinite editor view you can use the same components as a isEnabled = true; } } - + /** * @ngdoc method * @name umbraco.services.editorService#open @@ -305,7 +305,7 @@ When building a custom infinite editor view you can use the same components as a // delay required to map the properties to the correct editor due // to another delay in the closing animation of the editor - $timeout(function() { + $timeout(function () { // rebind keyboard shortcuts for the new editor in focus rebindKeyboardShortcuts(); @@ -651,7 +651,7 @@ When building a custom infinite editor view you can use the same components as a editor.view = "views/mediatypes/edit.html"; open(editor); } - + /** * @ngdoc method * @name umbraco.services.editorService#memberTypeEditor @@ -928,21 +928,21 @@ When building a custom infinite editor view you can use the same components as a open(editor); } - /** - * @ngdoc method - * @name umbraco.services.editorService#memberPicker - * @methodOf umbraco.services.editorService - * - * @description - * Opens a member picker in infinite editing, the submit callback returns an array of selected items - * - * @param {Object} editor rendering options - * @param {Boolean} editor.multiPicker Pick one or multiple items - * @param {Function} editor.submit Callback function when the submit button is clicked. Returns the editor model object - * @param {Function} editor.close Callback function when the close button is clicked. - * - * @returns {Object} editor object - */ + /** + * @ngdoc method + * @name umbraco.services.editorService#memberPicker + * @methodOf umbraco.services.editorService + * + * @description + * Opens a member picker in infinite editing, the submit callback returns an array of selected items + * + * @param {Object} editor rendering options + * @param {Boolean} editor.multiPicker Pick one or multiple items + * @param {Function} editor.submit Callback function when the submit button is clicked. Returns the editor model object + * @param {Function} editor.close Callback function when the close button is clicked. + * + * @returns {Object} editor object + */ function memberPicker(editor) { editor.view = "views/common/infiniteeditors/treepicker/treepicker.html"; if (!editor.size) editor.size = "small"; @@ -985,7 +985,7 @@ When building a custom infinite editor view you can use the same components as a * */ function unbindKeyboardShortcuts() { - const shortcuts = angular.copy(keyboardService.keyboardEvent); + const shortcuts = Utilities.copy(keyboardService.keyboardEvent); editorsKeyboardShorcuts.push(shortcuts); // unbind the current shortcuts because we only want to diff --git a/src/Umbraco.Web.UI.Client/src/common/services/navigation.service.js b/src/Umbraco.Web.UI.Client/src/common/services/navigation.service.js index 6401fa3aef..0198907119 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/navigation.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/navigation.service.js @@ -26,60 +26,60 @@ function navigationService($routeParams, $location, $q, $injector, eventsService navReadyPromise.resolve(mainTreeApi); }); - + //A list of query strings defined that when changed will not cause a reload of the route var nonRoutingQueryStrings = ["mculture", "cculture", "lq", "sr"]; var retainedQueryStrings = ["mculture"]; - + function setMode(mode) { switch (mode) { - case 'tree': - appState.setGlobalState("navMode", "tree"); - appState.setGlobalState("showNavigation", true); - appState.setMenuState("showMenu", false); - appState.setMenuState("showMenuDialog", false); - appState.setGlobalState("stickyNavigation", false); - appState.setGlobalState("showTray", false); - break; - case 'menu': - appState.setGlobalState("navMode", "menu"); - appState.setGlobalState("showNavigation", true); - appState.setMenuState("showMenu", true); - appState.setMenuState("showMenuDialog", false); - appState.setGlobalState("stickyNavigation", true); - break; - case 'dialog': - appState.setGlobalState("navMode", "dialog"); - appState.setGlobalState("stickyNavigation", true); - appState.setGlobalState("showNavigation", true); - appState.setMenuState("showMenu", false); - appState.setMenuState("showMenuDialog", true); - appState.setMenuState("allowHideMenuDialog", true); - break; - case 'search': - appState.setGlobalState("navMode", "search"); - appState.setGlobalState("stickyNavigation", false); - appState.setGlobalState("showNavigation", true); - appState.setMenuState("showMenu", false); - appState.setSectionState("showSearchResults", true); - appState.setMenuState("showMenuDialog", false); - break; - default: - appState.setGlobalState("navMode", "default"); - appState.setMenuState("showMenu", false); - appState.setMenuState("showMenuDialog", false); - appState.setMenuState("allowHideMenuDialog", true); - appState.setSectionState("showSearchResults", false); - appState.setGlobalState("stickyNavigation", false); - appState.setGlobalState("showTray", false); - appState.setMenuState("currentNode", null); + case 'tree': + appState.setGlobalState("navMode", "tree"); + appState.setGlobalState("showNavigation", true); + appState.setMenuState("showMenu", false); + appState.setMenuState("showMenuDialog", false); + appState.setGlobalState("stickyNavigation", false); + appState.setGlobalState("showTray", false); + break; + case 'menu': + appState.setGlobalState("navMode", "menu"); + appState.setGlobalState("showNavigation", true); + appState.setMenuState("showMenu", true); + appState.setMenuState("showMenuDialog", false); + appState.setGlobalState("stickyNavigation", true); + break; + case 'dialog': + appState.setGlobalState("navMode", "dialog"); + appState.setGlobalState("stickyNavigation", true); + appState.setGlobalState("showNavigation", true); + appState.setMenuState("showMenu", false); + appState.setMenuState("showMenuDialog", true); + appState.setMenuState("allowHideMenuDialog", true); + break; + case 'search': + appState.setGlobalState("navMode", "search"); + appState.setGlobalState("stickyNavigation", false); + appState.setGlobalState("showNavigation", true); + appState.setMenuState("showMenu", false); + appState.setSectionState("showSearchResults", true); + appState.setMenuState("showMenuDialog", false); + break; + default: + appState.setGlobalState("navMode", "default"); + appState.setMenuState("showMenu", false); + appState.setMenuState("showMenuDialog", false); + appState.setMenuState("allowHideMenuDialog", true); + appState.setSectionState("showSearchResults", false); + appState.setGlobalState("stickyNavigation", false); + appState.setGlobalState("showTray", false); + appState.setMenuState("currentNode", null); - if (appState.getGlobalState("isTablet") === true) { - appState.setGlobalState("showNavigation", false); - } + if (appState.getGlobalState("isTablet") === true) { + appState.setGlobalState("showNavigation", false); + } - break; + break; } } @@ -114,7 +114,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService } var service = { - + /** * @ngdoc method * @name umbraco.services.navigationService#isRouteChangingNavigation @@ -151,7 +151,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService var nextRoutingKeys = _.difference(_.keys(nextUrlParams), nonRoutingQueryStrings); var diff1 = _.difference(currRoutingKeys, nextRoutingKeys); var diff2 = _.difference(nextRoutingKeys, currRoutingKeys); - + //if the routing parameter keys are the same, we'll compare their values to see if any have changed and if so then the routing will be allowed. if (diff1.length === 0 && diff2.length === 0) { var partsChanged = 0; @@ -223,7 +223,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService * @param {Object} nextRouteParams The next route parameters */ retainQueryStrings: function (currRouteParams, nextRouteParams) { - var toRetain = angular.copy(nextRouteParams); + var toRetain = Utilities.copy(nextRouteParams); var updated = false; _.each(retainedQueryStrings, function (r) { @@ -260,7 +260,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService * and load the dashboard related to the section * @param {string} sectionAlias The alias of the section */ - changeSection: function(sectionAlias, force) { + changeSection: function (sectionAlias, force) { setMode("default-opensection"); if (force && appState.getSectionState("currentSection") === sectionAlias) { @@ -360,19 +360,19 @@ function navigationService($routeParams, $location, $q, $injector, eventsService TODO: Delete this if not required */ - _syncPath: function(path, forceReload) { + _syncPath: function (path, forceReload) { return navReadyPromise.promise.then(function () { return mainTreeApi.syncTree({ path: path, forceReload: forceReload }); }); }, - - reloadNode: function(node) { + + reloadNode: function (node) { return navReadyPromise.promise.then(function () { return mainTreeApi.reloadNode(node); }); }, - - reloadSection: function(sectionAlias) { + + reloadSection: function (sectionAlias) { return navReadyPromise.promise.then(function () { treeService.clearCache({ section: sectionAlias }); return mainTreeApi.load(sectionAlias); @@ -387,11 +387,11 @@ function navigationService($routeParams, $location, $q, $injector, eventsService * @description * Hides the tree by hiding the containing dom element */ - hideTree: function() { + hideTree: function () { if (appState.getGlobalState("isTablet") === true && !appState.getGlobalState("stickyNavigation")) { //reset it to whatever is in the url - appState.setSectionState("currentSection", $routeParams.section); + appState.setSectionState("currentSection", $routeParams.section); setMode("default-hidesectiontree"); } @@ -409,19 +409,19 @@ function navigationService($routeParams, $location, $q, $injector, eventsService * * @param {Event} event the click event triggering the method, passed from the DOM element */ - showMenu: function(args) { - + showMenu: function (args) { + var self = this; return treeService.getMenu({ treeNode: args.node }) - .then(function(data) { + .then(function (data) { //check for a default //NOTE: event will be undefined when a call to hideDialog is made so it won't re-load the default again. // but perhaps there's a better way to deal with with an additional parameter in the args ? it works though. if (data.defaultAlias && !args.skipDefault) { - var found = _.find(data.menuItems, function(item) { + var found = _.find(data.menuItems, function (item) { return item.alias = data.defaultAlias; }); @@ -450,7 +450,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService return $q.resolve(); }); - + }, /** @@ -461,7 +461,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService * @description * Hides the menu by hiding the containing dom element */ - hideMenu: function() { + hideMenu: function () { //SD: Would we ever want to access the last action'd node instead of clearing it here? appState.setMenuState("currentNode", null); appState.setMenuState("menuActions", []); @@ -532,7 +532,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService }); } }, - + /** * @ngdoc method @@ -553,7 +553,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService * @param {Scope} args.scope current scope passed to the dialog * @param {Object} args.action the clicked action containing `name` and `alias` */ - showDialog: function(args) { + showDialog: function (args) { if (!args) { throw "showDialog is missing the args parameter"; @@ -578,20 +578,20 @@ function navigationService($routeParams, $location, $q, $injector, eventsService if (args.action.metaData["actionView"]) { templateUrl = args.action.metaData["actionView"]; } - else { + else { var treeAlias = treeService.getTreeAlias(args.node); if (!treeAlias) { throw "Could not get tree alias for node " + args.node.id; - } + } templateUrl = this.getTreeTemplateUrl(treeAlias, args.action.alias); } setMode("dialog"); - if(templateUrl) { + if (templateUrl) { appState.setMenuState("dialogTemplateUrl", templateUrl); } - + }, /** * @ngdoc method @@ -607,7 +607,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService * we will also check for a 'packageName' for the current tree, if it exists then the convention will be: * for example: /App_Plugins/{mypackage}/backoffice/{treetype}/create.html */ - getTreeTemplateUrl: function(treeAlias, action) { + getTreeTemplateUrl: function (treeAlias, action) { var packageTreeFolder = treeService.getTreePackageFolder(treeAlias); if (packageTreeFolder) { return Umbraco.Sys.ServerVariables.umbracoSettings.appPluginsPath + @@ -661,7 +661,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService * @description * shows the search pane */ - showSearch: function() { + showSearch: function () { setMode("search"); }, /** @@ -672,7 +672,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService * @description * hides the search pane */ - hideSearch: function() { + hideSearch: function () { setMode("default-hidesearch"); }, /** @@ -683,7 +683,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService * @description * hides any open navigation panes and resets the tree, actions and the currently selected node */ - hideNavigation: function() { + hideNavigation: function () { appState.setMenuState("menuActions", []); setMode("default"); } diff --git a/src/Umbraco.Web.UI.Client/src/init.js b/src/Umbraco.Web.UI.Client/src/init.js index d5c5166d21..ce824f63c0 100644 --- a/src/Umbraco.Web.UI.Client/src/init.js +++ b/src/Umbraco.Web.UI.Client/src/init.js @@ -34,7 +34,7 @@ app.run(['$rootScope', '$route', '$location', 'urlHelper', 'navigationService', else { const introTourShown = localStorageService.get("introTourShown"); - if(!introTourShown){ + if (!introTourShown) { // Go & show email marketing tour (ONLY when intro tour is completed or been dismissed) tourService.getTourByAlias("umbEmailMarketing").then(function (emailMarketingTour) { // Only show the email marketing tour one time - dismissing it or saying no will make sure it never appears again @@ -45,7 +45,7 @@ app.run(['$rootScope', '$route', '$location', 'urlHelper', 'navigationService', // Only show the email tour once per logged in session // The localstorage key is removed on logout or user session timeout const emailMarketingTourShown = localStorageService.get("emailMarketingTourShown"); - if(!emailMarketingTourShown){ + if (!emailMarketingTourShown) { tourService.startTour(emailMarketingTour); localStorageService.set("emailMarketingTourShown", true); } @@ -89,7 +89,7 @@ app.run(['$rootScope', '$route', '$location', 'urlHelper', 'navigationService', currentRouteParams = toRetain; } else { - currentRouteParams = angular.copy(current.params); + currentRouteParams = Utilities.copy(current.params); } @@ -183,7 +183,7 @@ app.run(['$rootScope', '$route', '$location', 'urlHelper', 'navigationService', currentRouteParams = toRetain; } else { - currentRouteParams = angular.copy(next.params); + currentRouteParams = Utilities.copy(next.params); } //always clear the 'sr' query string (soft redirect) if it exists @@ -191,7 +191,7 @@ app.run(['$rootScope', '$route', '$location', 'urlHelper', 'navigationService', currentRouteParams.sr = null; $route.updateParams(currentRouteParams); } - + } } }); diff --git a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/compositions/compositions.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/compositions/compositions.controller.js index 7cfa02f95a..aa0cd54dff 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/compositions/compositions.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/compositions/compositions.controller.js @@ -17,7 +17,7 @@ /* make a copy of the init model so it is possible to roll back the changes on cancel */ - oldModel = angular.copy($scope.model); + oldModel = Utilities.copy($scope.model); if (!$scope.model.title) { $scope.model.title = "Compositions"; @@ -39,7 +39,7 @@ }); } - + function isSelected(alias) { if ($scope.model.contentType.compositeContentTypes.indexOf(alias) !== -1) { @@ -68,7 +68,7 @@ or the confirm checkbox has been checked */ if (compositionRemoved) { vm.allowSubmit = false; - localizationService.localize("general_remove").then(function(value) { + localizationService.localize("general_remove").then(function (value) { const dialog = { view: "views/common/infiniteeditors/compositions/overlays/confirmremove.html", title: value, diff --git a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/linkpicker/linkpicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/linkpicker/linkpicker.controller.js index 47607b7f0b..a9803b70f9 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/linkpicker/linkpicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/linkpicker/linkpicker.controller.js @@ -1,7 +1,7 @@ //used for the media picker dialog angular.module("umbraco").controller("Umbraco.Editors.LinkPickerController", function ($scope, eventsService, entityResource, mediaResource, mediaHelper, udiParser, userService, localizationService, editorService) { - + var vm = this; var dialogOptions = $scope.model; @@ -16,7 +16,7 @@ angular.module("umbraco").controller("Umbraco.Editors.LinkPickerController", if (!$scope.model.title) { localizationService.localize("defaultdialogs_selectLink") - .then(function(value) { + .then(function (value) { $scope.model.title = value; }); } @@ -59,7 +59,7 @@ angular.module("umbraco").controller("Umbraco.Editors.LinkPickerController", if (dialogOptions.currentTarget) { // clone the current target so we don't accidentally update the caller's model while manipulating $scope.model.target - $scope.model.target = angular.copy(dialogOptions.currentTarget); + $scope.model.target = Utilities.copy(dialogOptions.currentTarget); // if we have a node ID, we fetch the current node to build the form data if ($scope.model.target.id || $scope.model.target.udi) { @@ -194,7 +194,7 @@ angular.module("umbraco").controller("Umbraco.Editors.LinkPickerController", tree: "content" }); }, - close: function() { + close: function () { editorService.close(); } }; @@ -251,13 +251,13 @@ angular.module("umbraco").controller("Umbraco.Editors.LinkPickerController", } function close() { - if($scope.model && $scope.model.close) { + if ($scope.model && $scope.model.close) { $scope.model.close(); } } function submit() { - if($scope.model && $scope.model.submit) { + if ($scope.model && $scope.model.submit) { $scope.model.submit($scope.model); } } diff --git a/src/Umbraco.Web.UI.Client/src/views/languages/edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/languages/edit.controller.js index 5f1c46de4c..96441e6101 100644 --- a/src/Umbraco.Web.UI.Client/src/views/languages/edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/languages/edit.controller.js @@ -57,7 +57,7 @@ }; if ($routeParams.create) { - vm.page.name = vm.labels.addLanguage; + vm.page.name = vm.labels.addLanguage; } }); @@ -87,14 +87,14 @@ if (!$routeParams.create) { - promises.push(languageResource.getById($routeParams.id).then(function(lang) { + promises.push(languageResource.getById($routeParams.id).then(function (lang) { vm.language = lang; vm.page.name = vm.language.name; /* we need to store the initial default state so we can disable the toggle if it is the default. we need to prevent from not having a default language. */ - vm.initIsDefault = angular.copy(vm.language.isDefault); + vm.initIsDefault = Utilities.copy(vm.language.isDefault); makeBreadcrumbs(); @@ -182,12 +182,12 @@ function toggleDefault() { // it shouldn't be possible to uncheck the default language - if(vm.initIsDefault) { + if (vm.initIsDefault) { return; } vm.language.isDefault = !vm.language.isDefault; - if(vm.language.isDefault) { + if (vm.language.isDefault) { vm.showDefaultLanguageInfo = true; } else { vm.showDefaultLanguageInfo = false; diff --git a/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js index 70688f045c..63750ff0f2 100644 --- a/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/packages/edit.controller.js @@ -40,7 +40,7 @@ vm.versionRegex = /^(\d+\.)(\d+\.)(\*|\d+)$/; function onInit() { - + if (create) { // Pre populate package with some values packageResource.getEmpty().then(scaffold => { @@ -78,7 +78,7 @@ }); - + localizationService.localizeMany(["buttons_save", "packager_includeAllChildNodes"]).then(function (values) { vm.labels.button = values[0]; vm.labels.includeAllChildNodes = values[1]; @@ -232,7 +232,7 @@ function openFilePicker() { - let selection = angular.copy(vm.package.files); + let selection = Utilities.copy(vm.package.files); const filePicker = { title: "Select files", diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.controller.js index 10b2f19e83..2568f62cf4 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.controller.js @@ -185,7 +185,7 @@ angular.module("umbraco") var rteId = value.id; if ($.inArray(rteId, notIncludedRte) < 0) { - + // remember this RTEs settings, cause we need to update it later. var editor = _.findWhere(tinyMCE.editors, { id: rteId }) if (editor) { @@ -197,17 +197,17 @@ angular.module("umbraco") } else { $(event.target).find(".umb-rte").each(function () { - + var rteId = $(this).attr("id"); - + if ($.inArray(rteId, notIncludedRte) < 0) { - + // remember this RTEs settings, cause we need to update it later. var editor = _.findWhere(tinyMCE.editors, { id: rteId }) if (editor) { draggedRteSettings[rteId] = editor.settings; } - + notIncludedRte.splice(0, 0, $(this).attr("id")); } }); @@ -227,12 +227,12 @@ angular.module("umbraco") // reset dragged RTE settings in case a RTE isn't dragged draggedRteSettings = {}; notIncludedRte = []; - + ui.item[0].style.display = "block"; ui.item.find(".umb-rte").each(function (key, value) { - + var rteId = value.id; - + // remember this RTEs settings, cause we need to update it later. var editor = _.findWhere(tinyMCE.editors, { id: rteId }); @@ -255,17 +255,17 @@ angular.module("umbraco") ui.item.offsetParent().find(".umb-rte").each(function (key, value) { var rteId = value.id; if ($.inArray(rteId, notIncludedRte) < 0) { - + var editor = _.findWhere(tinyMCE.editors, { id: rteId }); if (editor) { draggedRteSettings[rteId] = editor.settings; } - + // add all dragged's neighbouring RTEs in the new cell notIncludedRte.splice(0, 0, rteId); } }); - + // reconstruct the dragged RTE (could be undefined when dragging something else than RTE) if (draggedRteSettings !== undefined) { tinyMCE.init(draggedRteSettings); @@ -327,13 +327,13 @@ angular.module("umbraco") title: title, availableItems: area.$allowedEditors, event: event, - submit: function(model) { + submit: function (model) { if (model.selectedItem) { $scope.addControl(model.selectedItem, area, index); overlayService.close(); } }, - close: function() { + close: function () { overlayService.close(); } }); @@ -345,7 +345,7 @@ angular.module("umbraco") // ********************************************* $scope.addTemplate = function (template) { - $scope.model.value = angular.copy(template); + $scope.model.value = Utilities.copy(template); //default row data _.forEach($scope.model.value.sections, function (section) { @@ -387,7 +387,7 @@ angular.module("umbraco") $scope.addRow = function (section, layout, isInit) { //copy the selected layout into the rows collection - var row = angular.copy(layout); + var row = Utilities.copy(layout); // Init row value row = $scope.initRow(row); @@ -408,7 +408,7 @@ angular.module("umbraco") setTimeout(function () { var newRowEl = $element.find("[data-rowid='" + row.$uniqueId + "']"); - if(newRowEl !== null) { + if (newRowEl !== null) { newRowEl.focus(); } }, 0); @@ -467,10 +467,10 @@ angular.module("umbraco") var styles, config; if (itemType === 'control') { styles = null; - config = angular.copy(gridItem.editor.config.settings); + config = Utilities.copy(gridItem.editor.config.settings); } else { - styles = _.filter(angular.copy($scope.model.config.items.styles), function (item) { return shouldApply(item, itemType, gridItem); }); - config = _.filter(angular.copy($scope.model.config.items.config), function (item) { return shouldApply(item, itemType, gridItem); }); + styles = _.filter(Utilities.copy($scope.model.config.items.styles), function (item) { return shouldApply(item, itemType, gridItem); }); + config = _.filter(Utilities.copy($scope.model.config.items.config), function (item) { return shouldApply(item, itemType, gridItem); }); } if (Utilities.isObject(gridItem.config)) { @@ -763,7 +763,7 @@ angular.module("umbraco") // allowed for this template based on the current config. _.each(found.sections, function (templateSection, index) { - angular.extend($scope.model.value.sections[index], angular.copy(templateSection)); + angular.extend($scope.model.value.sections[index], Utilities.copy(templateSection)); }); } @@ -835,7 +835,7 @@ angular.module("umbraco") return null; } else { //make a copy to not touch the original config - original = angular.copy(original); + original = Utilities.copy(original); original.styles = row.styles; original.config = row.config; original.hasConfig = gridItemHasConfig(row.styles, row.config); diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.prevalues.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.prevalues.controller.js index 27ea819884..f273ea63e6 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.prevalues.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.prevalues.controller.js @@ -1,296 +1,296 @@ angular.module("umbraco") .controller("Umbraco.PropertyEditors.GridPrevalueEditorController", - function ($scope, gridService, editorService) { + function ($scope, gridService, editorService) { - var emptyModel = { - styles:[ - { - label: "Set a background image", - description: "Set a row background", - key: "background-image", - view: "imagepicker", - modifier: "url({0})" - } - ], - - config:[ - { - label: "Class", - description: "Set a css class", - key: "class", - view: "textstring" - } - ], - - columns: 12, - templates:[ - { - name: "1 column layout", - sections: [ - { - grid: 12 - } - ] - }, - { - name: "2 column layout", - sections: [ - { - grid: 4 - }, - { - grid: 8 - } - ] - } - ], - - - layouts:[ - { - label: "Headline", - name: "Headline", - areas: [ - { - grid: 12, - editors: ["headline"] - } - ] - }, - { - label: "Article", - name: "Article", - areas: [ - { - grid: 4 - }, - { - grid: 8 - } - ] - } - ] - }; - - /**************** - template - *****************/ - - $scope.configureTemplate = function(template) { - - var index = $scope.model.value.templates.indexOf(template); - - if (template === undefined) { - template = { - name: "", - sections: [ - - ] - }; - } - - var layoutConfigOverlay = { - currentLayout: angular.copy(template), - rows: $scope.model.value.layouts, - columns: $scope.model.value.columns, - view: "views/propertyEditors/grid/dialogs/layoutconfig.html", - size: "small", - submit: function (model) { - if (index === -1) { - $scope.model.value.templates.push(model); - } else { - $scope.model.value.templates[index] = model; + var emptyModel = { + styles: [ + { + label: "Set a background image", + description: "Set a row background", + key: "background-image", + view: "imagepicker", + modifier: "url({0})" } - editorService.close(); - }, - close: function(model) { - editorService.close(); - } + ], + + config: [ + { + label: "Class", + description: "Set a css class", + key: "class", + view: "textstring" + } + ], + + columns: 12, + templates: [ + { + name: "1 column layout", + sections: [ + { + grid: 12 + } + ] + }, + { + name: "2 column layout", + sections: [ + { + grid: 4 + }, + { + grid: 8 + } + ] + } + ], + + + layouts: [ + { + label: "Headline", + name: "Headline", + areas: [ + { + grid: 12, + editors: ["headline"] + } + ] + }, + { + label: "Article", + name: "Article", + areas: [ + { + grid: 4 + }, + { + grid: 8 + } + ] + } + ] }; - editorService.open(layoutConfigOverlay); - - }; + /**************** + template + *****************/ - $scope.deleteTemplate = function(index){ - $scope.model.value.templates.splice(index, 1); - }; - + $scope.configureTemplate = function (template) { - /**************** - Row - *****************/ + var index = $scope.model.value.templates.indexOf(template); - $scope.configureLayout = function(layout) { + if (template === undefined) { + template = { + name: "", + sections: [ - var index = $scope.model.value.layouts.indexOf(layout); - - if(layout === undefined){ - layout = { - name: "", - areas:[ + ] + }; + } - ] + var layoutConfigOverlay = { + currentLayout: Utilities.copy(template), + rows: $scope.model.value.layouts, + columns: $scope.model.value.columns, + view: "views/propertyEditors/grid/dialogs/layoutconfig.html", + size: "small", + submit: function (model) { + if (index === -1) { + $scope.model.value.templates.push(model); + } else { + $scope.model.value.templates[index] = model; + } + editorService.close(); + }, + close: function (model) { + editorService.close(); + } }; - } - - var rowConfigOverlay = { - currentRow: angular.copy(layout), - editors: $scope.editors, - columns: $scope.model.value.columns, - view: "views/propertyEditors/grid/dialogs/rowconfig.html", - size: "small", - submit: function (model) { - if (index === -1) { - $scope.model.value.layouts.push(model); - } else { - $scope.model.value.layouts[index] = model; - } - editorService.close(); - }, - close: function(model) { - editorService.close(); - } - }; - editorService.open(rowConfigOverlay); - - }; + editorService.open(layoutConfigOverlay); - //var rowDeletesPending = false; - $scope.deleteLayout = function(index) { - - var rowDeleteOverlay = { - dialogData: { - rowName: $scope.model.value.layouts[index].name - }, - view: "views/propertyEditors/grid/dialogs/rowdeleteconfirm.html", - size: "small", - submit: function(model) { - $scope.model.value.layouts.splice(index, 1); - editorService.close(); - }, - close: function(model) { - editorService.close(); + }; + + $scope.deleteTemplate = function (index) { + $scope.model.value.templates.splice(index, 1); + }; + + + /**************** + Row + *****************/ + + $scope.configureLayout = function (layout) { + + var index = $scope.model.value.layouts.indexOf(layout); + + if (layout === undefined) { + layout = { + name: "", + areas: [ + + ] + }; + } + + var rowConfigOverlay = { + currentRow: Utilities.copy(layout), + editors: $scope.editors, + columns: $scope.model.value.columns, + view: "views/propertyEditors/grid/dialogs/rowconfig.html", + size: "small", + submit: function (model) { + if (index === -1) { + $scope.model.value.layouts.push(model); + } else { + $scope.model.value.layouts[index] = model; + } + editorService.close(); + }, + close: function (model) { + editorService.close(); + } + }; + + editorService.open(rowConfigOverlay); + + }; + + //var rowDeletesPending = false; + $scope.deleteLayout = function (index) { + + var rowDeleteOverlay = { + dialogData: { + rowName: $scope.model.value.layouts[index].name + }, + view: "views/propertyEditors/grid/dialogs/rowdeleteconfirm.html", + size: "small", + submit: function (model) { + $scope.model.value.layouts.splice(index, 1); + editorService.close(); + }, + close: function (model) { + editorService.close(); + } + }; + + editorService.open(rowDeleteOverlay); + }; + + + /**************** + utillities + *****************/ + $scope.toggleCollection = function (collection, toggle) { + if (toggle) { + collection = []; + } else { + collection = null; } }; - editorService.open(rowDeleteOverlay); - }; + $scope.percentage = function (spans) { + return ((spans / $scope.model.value.columns) * 100).toFixed(8); + }; - - /**************** - utillities - *****************/ - $scope.toggleCollection = function(collection, toggle){ - if(toggle){ - collection = []; - }else{ - collection = null; - } - }; - - $scope.percentage = function(spans){ - return ((spans / $scope.model.value.columns) * 100).toFixed(8); - }; - - $scope.zeroWidthFilter = function (cell) { + $scope.zeroWidthFilter = function (cell) { return cell.grid > 0; - }; - - /**************** - Config - *****************/ - - $scope.removeConfigValue = function(collection, index){ - collection.splice(index, 1); - }; - - var editConfigCollection = function(configValues, title, callback) { - - var editConfigCollectionOverlay = { - config: configValues, - title: title, - view: "views/propertyeditors/grid/dialogs/editconfig.html", - size: "small", - submit: function(model) { - callback(model.config); - editorService.close(); - }, - close: function(model) { - editorService.close(); - } }; - editorService.open(editConfigCollectionOverlay); - }; + /**************** + Config + *****************/ - $scope.editConfig = function() { - editConfigCollection($scope.model.value.config, "Settings", function(data) { - $scope.model.value.config = data; - }); - }; + $scope.removeConfigValue = function (collection, index) { + collection.splice(index, 1); + }; - $scope.editStyles = function() { - editConfigCollection($scope.model.value.styles, "Styling", function(data){ - $scope.model.value.styles = data; - }); - }; + var editConfigCollection = function (configValues, title, callback) { - /**************** - editors - *****************/ - gridService.getGridEditors().then(function(response){ - $scope.editors = response.data; - }); + var editConfigCollectionOverlay = { + config: configValues, + title: title, + view: "views/propertyeditors/grid/dialogs/editconfig.html", + size: "small", + submit: function (model) { + callback(model.config); + editorService.close(); + }, + close: function (model) { + editorService.close(); + } + }; + editorService.open(editConfigCollectionOverlay); + }; - /* init grid data */ - if (!$scope.model.value || $scope.model.value === "" || !$scope.model.value.templates) { - $scope.model.value = emptyModel; - } else { + $scope.editConfig = function () { + editConfigCollection($scope.model.value.config, "Settings", function (data) { + $scope.model.value.config = data; + }); + }; - if (!$scope.model.value.columns) { - $scope.model.value.columns = emptyModel.columns; - } + $scope.editStyles = function () { + editConfigCollection($scope.model.value.styles, "Styling", function (data) { + $scope.model.value.styles = data; + }); + }; - - if (!$scope.model.value.config) { - $scope.model.value.config = []; - } - - if (!$scope.model.value.styles) { - $scope.model.value.styles = []; - } - } - - /**************** - Clean up - *****************/ - var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { - var ts = $scope.model.value.templates; - var ls = $scope.model.value.layouts; - - _.each(ts, function(t){ - _.each(t.sections, function(section, index){ - if(section.grid === 0){ - t.sections.splice(index, 1); - } - }); + /**************** + editors + *****************/ + gridService.getGridEditors().then(function (response) { + $scope.editors = response.data; }); - _.each(ls, function(l){ - _.each(l.areas, function(area, index){ - if(area.grid === 0){ - l.areas.splice(index, 1); - } - }); + + /* init grid data */ + if (!$scope.model.value || $scope.model.value === "" || !$scope.model.value.templates) { + $scope.model.value = emptyModel; + } else { + + if (!$scope.model.value.columns) { + $scope.model.value.columns = emptyModel.columns; + } + + + if (!$scope.model.value.config) { + $scope.model.value.config = []; + } + + if (!$scope.model.value.styles) { + $scope.model.value.styles = []; + } + } + + /**************** + Clean up + *****************/ + var unsubscribe = $scope.$on("formSubmitting", function (ev, args) { + var ts = $scope.model.value.templates; + var ls = $scope.model.value.layouts; + + _.each(ts, function (t) { + _.each(t.sections, function (section, index) { + if (section.grid === 0) { + t.sections.splice(index, 1); + } + }); + }); + + _.each(ls, function (l) { + _.each(l.areas, function (area, index) { + if (area.grid === 0) { + l.areas.splice(index, 1); + } + }); + }); }); - }); - //when the scope is destroyed we need to unsubscribe - $scope.$on('$destroy', function () { - unsubscribe(); - }); + //when the scope is destroyed we need to unsubscribe + $scope.$on('$destroy', function () { + unsubscribe(); + }); - }); + }); diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.controller.js index 68e7ea4f5c..30715dfd5e 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/imagecropper/imagecropper.controller.js @@ -1,223 +1,223 @@ angular.module('umbraco') .controller("Umbraco.PropertyEditors.ImageCropperController", - function ($scope, fileManager, $timeout) { + function ($scope, fileManager, $timeout) { - var config = angular.copy($scope.model.config); + var config = Utilities.copy($scope.model.config); - $scope.filesSelected = onFileSelected; - $scope.filesChanged = onFilesChanged; - $scope.fileUploaderInit = onFileUploaderInit; - $scope.imageLoaded = imageLoaded; - $scope.crop = crop; - $scope.done = done; - $scope.clear = clear; - $scope.reset = reset; - $scope.close = close; - $scope.isCustomCrop = isCustomCrop; - $scope.focalPointChanged = focalPointChanged; - //declare a special method which will be called whenever the value has changed from the server - $scope.model.onValueChanged = onValueChanged; + $scope.filesSelected = onFileSelected; + $scope.filesChanged = onFilesChanged; + $scope.fileUploaderInit = onFileUploaderInit; + $scope.imageLoaded = imageLoaded; + $scope.crop = crop; + $scope.done = done; + $scope.clear = clear; + $scope.reset = reset; + $scope.close = close; + $scope.isCustomCrop = isCustomCrop; + $scope.focalPointChanged = focalPointChanged; + //declare a special method which will be called whenever the value has changed from the server + $scope.model.onValueChanged = onValueChanged; - /** - * Called when the umgImageGravity component updates the focal point value - * @param {any} left - * @param {any} top - */ - function focalPointChanged(left, top) { - //update the model focalpoint value - $scope.model.value.focalPoint = { - left: left, - top: top + /** + * Called when the umgImageGravity component updates the focal point value + * @param {any} left + * @param {any} top + */ + function focalPointChanged(left, top) { + //update the model focalpoint value + $scope.model.value.focalPoint = { + left: left, + top: top + }; + + //set form to dirty to track changes + $scope.imageCropperForm.$setDirty(); + } + + /** + * Used to assign a new model value + * @param {any} src + */ + function setModelValueWithSrc(src) { + if (!$scope.model.value || !$scope.model.value.src) { + //we are copying to not overwrite the original config + $scope.model.value = angular.extend(Utilities.copy($scope.model.config), { src: src }); + } + } + + /** + * called whenever the value has changed from the server + * @param {any} newVal + * @param {any} oldVal + */ + function onValueChanged(newVal, oldVal) { + //clear current uploaded files + fileManager.setFiles({ + propertyAlias: $scope.model.alias, + culture: $scope.model.culture, + files: [] + }); + } + + /** + * Called when the a new file is selected + * @param {any} value + */ + function onFileSelected(value, files) { + setModelValueWithSrc(value); + //set form to dirty to track changes + $scope.imageCropperForm.$setDirty(); + } + + function imageLoaded(isCroppable, hasDimensions) { + $scope.isCroppable = isCroppable; + $scope.hasDimensions = hasDimensions; }; - //set form to dirty to track changes - $scope.imageCropperForm.$setDirty(); - } - - /** - * Used to assign a new model value - * @param {any} src - */ - function setModelValueWithSrc(src) { - if (!$scope.model.value || !$scope.model.value.src) { - //we are copying to not overwrite the original config - $scope.model.value = angular.extend(angular.copy($scope.model.config), { src: src }); - } - } - - /** - * called whenever the value has changed from the server - * @param {any} newVal - * @param {any} oldVal - */ - function onValueChanged(newVal, oldVal) { - //clear current uploaded files - fileManager.setFiles({ - propertyAlias: $scope.model.alias, - culture: $scope.model.culture, - files: [] - }); - } - - /** - * Called when the a new file is selected - * @param {any} value - */ - function onFileSelected(value, files) { - setModelValueWithSrc(value); - //set form to dirty to track changes - $scope.imageCropperForm.$setDirty(); - } - - function imageLoaded (isCroppable, hasDimensions) { - $scope.isCroppable = isCroppable; - $scope.hasDimensions = hasDimensions; - }; - - /** - * Called when the file collection changes - * @param {any} value - * @param {any} files - */ - function onFilesChanged(files) { - if (files && files[0]) { - $scope.imageSrc = files[0].fileSrc; - //set form to dirty to track changes - $scope.imageCropperForm.$setDirty(); - } - } - - /** - * Called when the file uploader initializes - * @param {any} value - */ - function onFileUploaderInit(value, files) { - //move previously saved value to the editor - if ($scope.model.value) { - //backwards compat with the old file upload (incase some-one swaps them..) - if (Utilities.isString($scope.model.value)) { - setModelValueWithSrc($scope.model.value); - } - else { - //sync any config changes with the editor and drop outdated crops - _.each($scope.model.value.crops, function (saved) { - var configured = _.find(config.crops, function (item) { return item.alias === saved.alias }); - - if (configured && configured.height === saved.height && configured.width === saved.width) { - configured.coordinates = saved.coordinates; - } - }); - $scope.model.value.crops = config.crops; - - //restore focalpoint if missing - if (!$scope.model.value.focalPoint) { - $scope.model.value.focalPoint = { left: 0.5, top: 0.5 }; - } - } - - //if there are already files in the client assigned then set the src + /** + * Called when the file collection changes + * @param {any} value + * @param {any} files + */ + function onFilesChanged(files) { if (files && files[0]) { $scope.imageSrc = files[0].fileSrc; + //set form to dirty to track changes + $scope.imageCropperForm.$setDirty(); + } + } + + /** + * Called when the file uploader initializes + * @param {any} value + */ + function onFileUploaderInit(value, files) { + //move previously saved value to the editor + if ($scope.model.value) { + //backwards compat with the old file upload (incase some-one swaps them..) + if (Utilities.isString($scope.model.value)) { + setModelValueWithSrc($scope.model.value); + } + else { + //sync any config changes with the editor and drop outdated crops + _.each($scope.model.value.crops, function (saved) { + var configured = _.find(config.crops, function (item) { return item.alias === saved.alias }); + + if (configured && configured.height === saved.height && configured.width === saved.width) { + configured.coordinates = saved.coordinates; + } + }); + $scope.model.value.crops = config.crops; + + //restore focalpoint if missing + if (!$scope.model.value.focalPoint) { + $scope.model.value.focalPoint = { left: 0.5, top: 0.5 }; + } + } + + //if there are already files in the client assigned then set the src + if (files && files[0]) { + $scope.imageSrc = files[0].fileSrc; + } + else { + $scope.imageSrc = $scope.model.value.src; + } + + } + } + + /** + * crop a specific crop + * @param {any} targetCrop + */ + function crop(targetCrop) { + if (!$scope.currentCrop) { + // clone the crop so we can discard the changes + $scope.currentCrop = Utilities.copy(targetCrop); + $scope.currentPoint = null; + + //set form to dirty to track changes + $scope.imageCropperForm.$setDirty(); } else { - $scope.imageSrc = $scope.model.value.src; - } - - } - } + // we have a crop open already - close the crop (this will discard any changes made) + close(); - /** - * crop a specific crop - * @param {any} targetCrop - */ - function crop(targetCrop) { - if (!$scope.currentCrop) { - // clone the crop so we can discard the changes - $scope.currentCrop = angular.copy(targetCrop); - $scope.currentPoint = null; + // the crop editor needs a digest cycle to close down properly, otherwise its state + // is reused for the new crop... and that's really bad + $timeout(function () { + crop(targetCrop); + $scope.pendingCrop = false; + }); + + // this is necessary to keep the screen from flickering too badly while we wait for the new crop to open + // - check the view for its usage (basically it makes sure we keep the space reserved for the new crop) + $scope.pendingCrop = true; + } + }; + + /** done cropping */ + function done() { + if (!$scope.currentCrop) { + return; + } + // find the original crop by crop alias and update its coordinates + var editedCrop = _.find($scope.model.value.crops, crop => crop.alias === $scope.currentCrop.alias); + editedCrop.coordinates = $scope.currentCrop.coordinates; + $scope.close(); //set form to dirty to track changes $scope.imageCropperForm.$setDirty(); - } - else { - // we have a crop open already - close the crop (this will discard any changes made) - close(); + }; - // the crop editor needs a digest cycle to close down properly, otherwise its state - // is reused for the new crop... and that's really bad - $timeout(function () { - crop(targetCrop); - $scope.pendingCrop = false; + function reset() { + $scope.currentCrop.coordinates = undefined; + $scope.done(); + } + + function close() { + $scope.currentCrop = undefined; + $scope.currentPoint = undefined; + } + + /** + * crop a specific crop + * @param {any} crop + */ + function clear(crop) { + //clear current uploaded files + fileManager.setFiles({ + propertyAlias: $scope.model.alias, + culture: $scope.model.culture, + files: [] }); - // this is necessary to keep the screen from flickering too badly while we wait for the new crop to open - // - check the view for its usage (basically it makes sure we keep the space reserved for the new crop) - $scope.pendingCrop = true; + //clear the ui + $scope.imageSrc = null; + if ($scope.model.value) { + $scope.model.value = null; + } + + //set form to dirty to track changes + $scope.imageCropperForm.$setDirty(); + }; + + function isCustomCrop(crop) { + return !!crop.coordinates; } - }; - /** done cropping */ - function done() { - if (!$scope.currentCrop) { - return; - } - // find the original crop by crop alias and update its coordinates - var editedCrop = _.find($scope.model.value.crops, crop => crop.alias === $scope.currentCrop.alias); - editedCrop.coordinates = $scope.currentCrop.coordinates; - $scope.close(); - - //set form to dirty to track changes - $scope.imageCropperForm.$setDirty(); - }; - - function reset() { - $scope.currentCrop.coordinates = undefined; - $scope.done(); - } - - function close() { - $scope.currentCrop = undefined; - $scope.currentPoint = undefined; - } - - /** - * crop a specific crop - * @param {any} crop - */ - function clear(crop) { - //clear current uploaded files - fileManager.setFiles({ - propertyAlias: $scope.model.alias, - culture: $scope.model.culture, - files: [] + var unsubscribe = $scope.$on("formSubmitting", function () { + $scope.currentCrop = null; + $scope.currentPoint = null; }); - //clear the ui - $scope.imageSrc = null; - if ($scope.model.value) { - $scope.model.value = null; - } - - //set form to dirty to track changes - $scope.imageCropperForm.$setDirty(); - }; - - function isCustomCrop(crop) { - return !!crop.coordinates; - } - - var unsubscribe = $scope.$on("formSubmitting", function () { - $scope.currentCrop = null; - $scope.currentPoint = null; - }); - - $scope.$on('$destroy', function () { - unsubscribe(); - }); - }) + $scope.$on('$destroy', function () { + unsubscribe(); + }); + }) .run(function (mediaHelper, umbRequestHelper) { if (mediaHelper && mediaHelper.registerFileResolver) { - + //NOTE: The 'entity' can be either a normal media entity or an "entity" returned from the entityResource // they contain different data structures so if we need to query against it we need to be aware of this. mediaHelper.registerFileResolver("Umbraco.ImageCropper", function (property, entity, thumbnail) { diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/nestedcontent/nestedcontent.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/nestedcontent/nestedcontent.controller.js index a25d5e798e..68c50c7ef7 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/nestedcontent/nestedcontent.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/nestedcontent/nestedcontent.controller.js @@ -14,7 +14,7 @@ }); function NestedContentController($scope, $interpolate, $filter, $timeout, contentResource, localizationService, iconHelper, clipboardService, eventsService, overlayService, $routeParams, editorState) { - + var vm = this; var model = $scope.$parent.$parent.model; @@ -58,9 +58,9 @@ updateModel(); vm.currentNode = node; } - - var copyAllEntries = function() { - + + var copyAllEntries = function () { + syncCurrentNode(); // list aliases @@ -68,14 +68,14 @@ // remove dublicates aliases = aliases.filter((item, index) => aliases.indexOf(item) === index); - + var nodeName = ""; - if(vm.umbVariantContent) { + if (vm.umbVariantContent) { nodeName = vm.umbVariantContent.editor.content.name; } - localizationService.localize("clipboard_labelForArrayOfItemsFrom", [model.label, nodeName]).then(function(data) { + localizationService.localize("clipboard_labelForArrayOfItemsFrom", [model.label, nodeName]).then(function (data) { clipboardService.copyArray("elementTypeArray", aliases, vm.nodes, data, "icon-thumbnail-list", model.id); }); } @@ -146,7 +146,7 @@ orderBy: "$index", view: "itempicker", event: $event, - clickPasteItem: function(item) { + clickPasteItem: function (item) { if (item.type === "elementTypeArray") { _.each(item.data, function (entry) { pasteFromClipboard(entry); @@ -183,9 +183,9 @@ if (vm.overlayMenu.availableItems.length === 0) { return; } - + vm.overlayMenu.size = vm.overlayMenu.availableItems.length > 6 ? "medium" : "small"; - + vm.overlayMenu.pasteItems = []; var singleEntriesForPaste = clipboardService.retriveEntriesOfType("elementType", contentTypeAliases); @@ -197,7 +197,7 @@ icon: entry.icon }); }); - + var arrayEntriesForPaste = clipboardService.retriveEntriesOfType("elementTypeArray", contentTypeAliases); _.each(arrayEntriesForPaste, function (entry) { vm.overlayMenu.pasteItems.push({ @@ -393,10 +393,10 @@ clipboardService.copy("elementType", node.contentTypeAlias, node); $event.stopPropagation(); } - - + + function pasteFromClipboard(newNode) { - + if (newNode === undefined) { return; } @@ -407,7 +407,7 @@ vm.nodes.push(newNode); setDirty(); //updateModel();// done by setting current node... - + setCurrentNode(newNode); } @@ -515,7 +515,7 @@ } function createNode(scaffold, fromNcEntry) { - var node = angular.copy(scaffold); + var node = Utilities.copy(scaffold); node.key = fromNcEntry && fromNcEntry.key ? fromNcEntry.key : String.CreateGuid(); @@ -596,12 +596,12 @@ } - + var propertyActions = [ copyAllEntriesAction, removeAllEntriesAction ]; - + this.$onInit = function () { if (this.umbProperty) { this.umbProperty.setPropertyActions(propertyActions); diff --git a/src/Umbraco.Web.UI.Client/src/views/templates/edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/templates/edit.controller.js index 30aa677b8b..781ff731d2 100644 --- a/src/Umbraco.Web.UI.Client/src/views/templates/edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/templates/edit.controller.js @@ -8,7 +8,7 @@ var infiniteMode = $scope.model && $scope.model.infiniteMode; var id = infiniteMode ? $scope.model.id : $routeParams.id; var create = infiniteMode ? $scope.model.create : $routeParams.create; - + vm.header = {}; vm.header.editorfor = "template_template"; vm.header.setPageTitle = true; @@ -26,7 +26,7 @@ vm.page.insertDefaultButton = { labelKey: "general_insert", addEllipsis: "true", - handler: function() { + handler: function () { vm.openInsertOverlay(); } }; @@ -68,16 +68,16 @@ //Keyboard shortcuts for help dialog vm.page.keyboardShortcutsOverview = []; - templateHelper.getGeneralShortcuts().then(function(data){ + templateHelper.getGeneralShortcuts().then(function (data) { vm.page.keyboardShortcutsOverview.push(data); }); - templateHelper.getEditorShortcuts().then(function(data){ + templateHelper.getEditorShortcuts().then(function (data) { vm.page.keyboardShortcutsOverview.push(data); }); - templateHelper.getTemplateEditorShortcuts().then(function(data){ + templateHelper.getTemplateEditorShortcuts().then(function (data) { vm.page.keyboardShortcutsOverview.push(data); }); - + vm.save = function (suppressNotification) { vm.page.saveButtonState = "busy"; @@ -87,36 +87,36 @@ saveMethod: templateResource.save, scope: $scope, content: vm.template, - rebindCallback: function (orignal, saved) {} + rebindCallback: function (orignal, saved) { } }).then(function (saved) { - if (!suppressNotification) { - localizationService.localizeMany(["speechBubbles_templateSavedHeader", "speechBubbles_templateSavedText"]).then(function(data){ + if (!suppressNotification) { + localizationService.localizeMany(["speechBubbles_templateSavedHeader", "speechBubbles_templateSavedText"]).then(function (data) { var header = data[0]; var message = data[1]; notificationsService.success(header, message); }); - } + } vm.page.saveButtonState = "success"; vm.template = saved; //sync state - if(!infiniteMode) { + if (!infiniteMode) { editorState.set(vm.template); } - + // sync tree // if master template alias has changed move the node to it's new location - if(!infiniteMode && oldMasterTemplateAlias !== vm.template.masterTemplateAlias) { - + if (!infiniteMode && oldMasterTemplateAlias !== vm.template.masterTemplateAlias) { + // When creating a new template the id is -1. Make sure We don't remove the root node. if (vm.page.menu.currentNode.id !== "-1") { // move node to new location in tree //first we need to remove the node that we're working on treeService.removeNode(vm.page.menu.currentNode); } - + // update stored alias to the new one so the node won't move again unless the alias is changed again oldMasterTemplateAlias = vm.template.masterTemplateAlias; @@ -127,7 +127,7 @@ } else { // normal tree sync - if(!infiniteMode) { + if (!infiniteMode) { navigationService.syncTree({ tree: "templates", path: vm.template.path, forceReload: true }).then(function (syncArgs) { vm.page.menu.currentNode = syncArgs.node; }); @@ -138,7 +138,7 @@ // clear $dirty state on form setFormState("pristine"); - if(infiniteMode) { + if (infiniteMode) { submit(); } @@ -164,16 +164,16 @@ // load templates - used in the master template picker templateResource.getAll() - .then(function(templates) { + .then(function (templates) { vm.templates = templates; }); - if(create) { + if (create) { templateResource.getScaffold((id)).then(function (template) { - vm.ready(template); - }); + vm.ready(template); + }); } else { - templateResource.getById(id).then(function(template){ + templateResource.getById(id).then(function (template) { vm.ready(template); }); } @@ -181,26 +181,26 @@ }; - vm.ready = function(template){ - vm.page.loading = false; + vm.ready = function (template) { + vm.page.loading = false; vm.template = template; - // if this is a new template, bind to the blur event on the name - if (create) { - $timeout(function() { - var nameField = angular.element(document.querySelector('[data-element="editor-name-field"]')); - if (nameField) { - nameField.on('blur', function(event) { - if (event.target.value) { - vm.save(true); - } - }); - } - }); - } - + // if this is a new template, bind to the blur event on the name + if (create) { + $timeout(function () { + var nameField = angular.element(document.querySelector('[data-element="editor-name-field"]')); + if (nameField) { + nameField.on('blur', function (event) { + if (event.target.value) { + vm.save(true); + } + }); + } + }); + } + // sync state - if(!infiniteMode) { + if (!infiniteMode) { editorState.set(vm.template); navigationService.syncTree({ tree: "templates", path: vm.template.path, forceReload: true }).then(function (syncArgs) { vm.page.menu.currentNode = syncArgs.node; @@ -208,7 +208,7 @@ } // save state of master template to use for comparison when syncing the tree on save - oldMasterTemplateAlias = angular.copy(template.masterTemplateAlias); + oldMasterTemplateAlias = Utilities.copy(template.masterTemplateAlias); // ace configuration vm.aceOption = { @@ -221,12 +221,12 @@ enableBasicAutocompletion: true, enableLiveAutocompletion: false }, - onLoad: function(_editor) { + onLoad: function (_editor) { vm.editor = _editor; - + //Update the auto-complete method to use ctrl+alt+space _editor.commands.bindKey("ctrl-alt-space", "startAutocomplete"); - + // Unassigns the keybinding (That was previously auto-complete) // As conflicts with our own tree search shortcut _editor.commands.bindKey("ctrl-space", null); @@ -238,20 +238,20 @@ { name: 'unSelectOrFindPrevious', bindKey: 'Alt-Shift-K', - exec: function() { + exec: function () { // Toggle the show keyboard shortcuts overlay - $scope.$apply(function(){ + $scope.$apply(function () { vm.showKeyboardShortcut = !vm.showKeyboardShortcut; }); - + }, readOnly: true }, { name: 'insertUmbracoValue', bindKey: 'Alt-Shift-V', - exec: function() { - $scope.$apply(function(){ + exec: function () { + $scope.$apply(function () { openPageFieldOverlay(); }); }, @@ -260,18 +260,18 @@ { name: 'insertPartialView', bindKey: 'Alt-Shift-P', - exec: function() { - $scope.$apply(function(){ + exec: function () { + $scope.$apply(function () { openPartialOverlay(); }); }, readOnly: true }, - { + { name: 'insertDictionary', bindKey: 'Alt-Shift-D', - exec: function() { - $scope.$apply(function(){ + exec: function () { + $scope.$apply(function () { openDictionaryItemOverlay(); }); }, @@ -280,8 +280,8 @@ { name: 'insertUmbracoMacro', bindKey: 'Alt-Shift-M', - exec: function() { - $scope.$apply(function(){ + exec: function () { + $scope.$apply(function () { openMacroOverlay(); }); }, @@ -290,8 +290,8 @@ { name: 'insertQuery', bindKey: 'Alt-Shift-Q', - exec: function() { - $scope.$apply(function(){ + exec: function () { + $scope.$apply(function () { openQueryBuilderOverlay(); }); }, @@ -300,8 +300,8 @@ { name: 'insertSection', bindKey: 'Alt-Shift-S', - exec: function() { - $scope.$apply(function(){ + exec: function () { + $scope.$apply(function () { openSectionsOverlay(); }); }, @@ -310,21 +310,21 @@ { name: 'chooseMasterTemplate', bindKey: 'Alt-Shift-T', - exec: function() { - $scope.$apply(function(){ + exec: function () { + $scope.$apply(function () { openMasterTemplateOverlay(); }); }, readOnly: true } - + ]); - + // initial cursor placement // Keep cursor in name field if we are create a new template // else set the cursor at the bottom of the code editor - if(!create) { - $timeout(function(){ + if (!create) { + $timeout(function () { vm.editor.navigateFileEnd(); vm.editor.focus(); persistCurrentLocation(); @@ -335,9 +335,9 @@ vm.editor.on("blur", persistCurrentLocation); vm.editor.on("focus", persistCurrentLocation); vm.editor.on("change", changeAceEditor); - } + } } - + }; vm.openPageFieldOverlay = openPageFieldOverlay; @@ -363,15 +363,15 @@ partial: true, umbracoField: true }, - submit: function(model) { - switch(model.insert.type) { + submit: function (model) { + switch (model.insert.type) { case "macro": var macroObject = macroService.collectValueData(model.insert.selectedMacro, model.insert.macroParams, "Mvc"); insert(macroObject.syntax); break; case "dictionary": - var code = templateHelper.getInsertDictionarySnippet(model.insert.node.name); - insert(code); + var code = templateHelper.getInsertDictionarySnippet(model.insert.node.name); + insert(code); break; case "partial": var code = templateHelper.getInsertPartialSnippet(model.insert.node.parentId, model.insert.node.name); @@ -383,7 +383,7 @@ } editorService.close(); }, - close: function(oldModel) { + close: function (oldModel) { // close the dialog editorService.close(); // focus editor @@ -401,7 +401,7 @@ insert(macroObject.syntax); editorService.close(); }, - close: function() { + close: function () { editorService.close(); vm.editor.focus(); } @@ -431,7 +431,7 @@ "emptyStates_emptyDictionaryTree" ]; - localizationService.localizeMany(labelKeys).then(function(values){ + localizationService.localizeMany(labelKeys).then(function (values) { var title = values[0]; var emptyStateMessage = values[1]; @@ -442,7 +442,7 @@ multiPicker: false, title: title, emptyStateMessage: emptyStateMessage, - select: function(node){ + select: function (node) { var code = templateHelper.getInsertDictionarySnippet(node.name); insert(code); editorService.close(); @@ -463,22 +463,22 @@ function openPartialOverlay() { - localizationService.localize("template_insertPartialView").then(function(value){ + localizationService.localize("template_insertPartialView").then(function (value) { var title = value; var partialItem = { - section: "settings", + section: "settings", treeAlias: "partialViews", entityType: "partialView", multiPicker: false, title: title, - filter: function(i) { - if(i.name.indexOf(".cshtml") === -1 && i.name.indexOf(".vbhtml") === -1) { + filter: function (i) { + if (i.name.indexOf(".cshtml") === -1 && i.name.indexOf(".vbhtml") === -1) { return true; } }, filterCssClass: "not-allowed", - select: function(node){ + select: function (node) { var code = templateHelper.getInsertPartialSnippet(node.parentId, node.name); insert(code); editorService.close(); @@ -505,7 +505,7 @@ close: function () { editorService.close(); // focus editor - vm.editor.focus(); + vm.editor.focus(); } }; editorService.queryBuilder(queryBuilder); @@ -515,7 +515,7 @@ function openSectionsOverlay() { var templateSections = { isMaster: vm.template.isMasterTemplate, - submit: function(model) { + submit: function (model) { if (model.insertType === 'renderBody') { var code = templateHelper.getRenderBodySnippet(); @@ -535,7 +535,7 @@ editorService.close(); }, - close: function(model) { + close: function (model) { editorService.close(); vm.editor.focus(); } @@ -559,12 +559,12 @@ } }); - localizationService.localize("template_mastertemplate").then(function(value){ + localizationService.localize("template_mastertemplate").then(function (value) { var title = value; var masterTemplate = { title: title, availableItems: availableMasterTemplates, - submit: function(model) { + submit: function (model) { var template = model.selectedItem; if (template && template.alias) { vm.template.masterTemplateAlias = template.alias; @@ -575,7 +575,7 @@ } editorService.close(); }, - close: function(oldModel) { + close: function (oldModel) { // close dialog editorService.close(); // focus editor @@ -596,14 +596,14 @@ vm.template.masterTemplateAlias = null; setLayout(null); } - + } function getMasterTemplateName(masterTemplateAlias, templates) { - if(masterTemplateAlias) { + if (masterTemplateAlias) { var templateName = ""; - angular.forEach(templates, function(template){ - if(template.alias === masterTemplateAlias) { + angular.forEach(templates, function (template) { + if (template.alias === masterTemplateAlias) { templateName = template.name; } }); @@ -620,8 +620,8 @@ } - function setLayout(templatePath){ - + function setLayout(templatePath) { + var templateCode = vm.editor.getValue(); var newValue = templatePath; var layoutDefRegex = new RegExp("(@{[\\s\\S]*?Layout\\s*?=\\s*?)(\"[^\"]*?\"|null)(;[\\s\\S]*?})", "gi"); @@ -645,7 +645,7 @@ vm.editor.setValue(templateCode); vm.editor.clearSelection(); vm.editor.navigateFileStart(); - + vm.editor.focus(); // set form state to $dirty setFormState("dirty"); @@ -668,7 +668,7 @@ str = str.replace("{0}", selectedContent); vm.editor.insert(str); vm.editor.focus(); - + // set form state to $dirty setFormState("dirty"); } @@ -682,14 +682,14 @@ } function setFormState(state) { - + // get the current form var currentForm = angularHelper.getCurrentForm($scope); // set state - if(state === "dirty") { + if (state === "dirty") { currentForm.$setDirty(); - } else if(state === "pristine") { + } else if (state === "pristine") { currentForm.$setPristine(); } } @@ -699,18 +699,18 @@ } function submit() { - if($scope.model.submit) { + if ($scope.model.submit) { $scope.model.template = vm.template; $scope.model.submit($scope.model); } } function close() { - if($scope.model.close) { + if ($scope.model.close) { $scope.model.close(); } } - + vm.init(); } diff --git a/src/Umbraco.Web.UI.Client/src/views/users/group.controller.js b/src/Umbraco.Web.UI.Client/src/views/users/group.controller.js index 43339adf04..f996e944db 100644 --- a/src/Umbraco.Web.UI.Client/src/views/users/group.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/users/group.controller.js @@ -6,7 +6,7 @@ var vm = this; var contentPickerOpen = false; - vm.page = {}; + vm.page = {}; vm.page.rootIcon = "icon-folder"; vm.userGroup = {}; vm.labels = {}; @@ -63,9 +63,9 @@ }); } else { // get user group - userGroupsResource.getUserGroup($routeParams.id).then(function (userGroup) { - vm.userGroup = userGroup; - formatGranularPermissionSelection(); + userGroupsResource.getUserGroup($routeParams.id).then(function (userGroup) { + vm.userGroup = userGroup; + formatGranularPermissionSelection(); setSectionIcon(vm.userGroup.sections); makeBreadcrumbs(); vm.loading = false; @@ -101,7 +101,7 @@ function openSectionPicker() { var currentSelection = []; - angular.copy(vm.userGroup.sections, currentSelection); + Utilities.copy(vm.userGroup.sections, currentSelection); var sectionPicker = { selection: currentSelection, submit: function (model) { @@ -166,7 +166,7 @@ function openUserPicker() { var currentSelection = []; - angular.copy(vm.userGroup.users, currentSelection); + Utilities.copy(vm.userGroup.users, currentSelection); var userPicker = { selection: currentSelection, submit: function (model) { @@ -212,8 +212,8 @@ if (model.selection) { var node = model.selection[0]; //check if this is already in our selection - var found = _.find(vm.userGroup.assignedPermissions, function(i) { - return i.id === node.id; + var found = _.find(vm.userGroup.assignedPermissions, function (i) { + return i.id === node.id; }); node = found ? found : node; setPermissionsForNode(node); @@ -231,7 +231,7 @@ //clone the current defaults to pass to the model if (!node.permissions) { - node.permissions = angular.copy(vm.userGroup.defaultPermissions); + node.permissions = Utilities.copy(vm.userGroup.defaultPermissions); } vm.nodePermissions = { @@ -257,7 +257,7 @@ editorService.close(); - if(contentPickerOpen) { + if (contentPickerOpen) { editorService.close(); contentPickerOpen = false; } diff --git a/src/Umbraco.Web.UI.Client/src/views/users/user.controller.js b/src/Umbraco.Web.UI.Client/src/views/users/user.controller.js index 56d01a8604..ecea3b1dba 100644 --- a/src/Umbraco.Web.UI.Client/src/views/users/user.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/users/user.controller.js @@ -8,7 +8,7 @@ vm.page = {}; vm.page.rootIcon = "icon-folder"; vm.user = { - changePassword: null + changePassword: null }; vm.breadcrumbs = []; vm.showBackButton = true; @@ -17,12 +17,12 @@ vm.maxFileSize = Umbraco.Sys.ServerVariables.umbracoSettings.maxFileSize + "KB"; vm.acceptedFileTypes = mediaHelper.formatFileTypes(Umbraco.Sys.ServerVariables.umbracoSettings.imageFileTypes); vm.usernameIsEmail = Umbraco.Sys.ServerVariables.umbracoSettings.usernameIsEmail; - + //create the initial model for change password vm.changePasswordModel = { - config: {}, - isChanging: false, - value: {} + config: {}, + isChanging: false, + value: {} }; vm.goToPage = goToPage; @@ -38,7 +38,7 @@ vm.changeAvatar = changeAvatar; vm.clearAvatar = clearAvatar; vm.save = save; - + vm.changePassword = changePassword; vm.toggleChangePassword = toggleChangePassword; @@ -83,40 +83,39 @@ //go get the config for the membership provider and add it to the model authResource.getMembershipProviderConfig().then(function (data) { - vm.changePasswordModel.config = data; + vm.changePasswordModel.config = data; - //the user has a password if they are not states: Invited, NoCredentials - vm.changePasswordModel.config.hasPassword = vm.user.userState !== 3 && vm.user.userState !== 4; + //the user has a password if they are not states: Invited, NoCredentials + vm.changePasswordModel.config.hasPassword = vm.user.userState !== 3 && vm.user.userState !== 4; - vm.changePasswordModel.config.disableToggle = true; + vm.changePasswordModel.config.disableToggle = true; - //this is only relavent for membership providers now (it's basically obsolete) - vm.changePasswordModel.config.enableReset = false; + //this is only relavent for membership providers now (it's basically obsolete) + vm.changePasswordModel.config.enableReset = false; - //in the ASP.NET Identity world, this config option will allow an admin user to change another user's password - //if the user has access to the user section. So if this editor is being access, the user of course has access to this section. - //the authorization check is also done on the server side when submitted. - - // only update the setting if not the current logged in user, otherwise leave the value as it is - // currently set in the web.config - if (!vm.user.isCurrentUser) - { - vm.changePasswordModel.config.allowManuallyChangingPassword = true; - } - - vm.loading = false; + //in the ASP.NET Identity world, this config option will allow an admin user to change another user's password + //if the user has access to the user section. So if this editor is being access, the user of course has access to this section. + //the authorization check is also done on the server side when submitted. + + // only update the setting if not the current logged in user, otherwise leave the value as it is + // currently set in the web.config + if (!vm.user.isCurrentUser) { + vm.changePasswordModel.config.allowManuallyChangingPassword = true; + } + + vm.loading = false; }); }); } - + function getLocalDate(date, culture, format) { - if(date) { + if (date) { var dateVal; var serverOffset = Umbraco.Sys.ServerVariables.application.serverTimeOffset; var localOffset = new Date().getTimezoneOffset(); var serverTimeNeedsOffsetting = (-serverOffset !== localOffset); - if(serverTimeNeedsOffsetting) { + if (serverTimeNeedsOffsetting) { dateVal = dateHelper.convertToLocalMomentTime(date, serverOffset); } else { dateVal = moment(date, "YYYY-MM-DD HH:mm:ss"); @@ -144,11 +143,11 @@ submit: model => { overlayService.close(); vm.changePasswordModel.value = model.changePassword; - changePassword(); + changePassword(); } }; overlayService.open(overlay); - }); + }); } function save() { @@ -165,16 +164,16 @@ .then(function (saved) { //if the user saved, then try to execute all extended save options - extendedSave(saved).then(function(result) { + extendedSave(saved).then(function (result) { //if all is good, then reset the form formHelper.resetForm({ scope: $scope }); }, Utilities.noop); - + vm.user = _.omit(saved, "navigation"); //restore vm.user.navigation = currentNav; setUserDisplayState(); - formatDatesToLocal(vm.user); + formatDatesToLocal(vm.user); vm.page.saveButtonState = "success"; @@ -184,7 +183,7 @@ err: err, showNotifications: true }); - + vm.page.saveButtonState = "error"; }); } @@ -201,15 +200,15 @@ //if allowManuallyChangingPassword=false, then we are using default settings and the user will need to enter their old password to change their own password. vm.changePasswordModel.value.reset = (!vm.changePasswordModel.value.oldPassword && !vm.user.isCurrentUser) || vm.changePasswordModel.config.allowManuallyChangingPassword; } - + // since we don't send the entire user model, the id is required vm.changePasswordModel.value.id = vm.user.id; - + usersResource.changePassword(vm.changePasswordModel.value) .then(() => { vm.changePasswordModel.isChanging = false; vm.changePasswordModel.value = {}; - + //the user has a password if they are not states: Invited, NoCredentials vm.changePasswordModel.config.hasPassword = vm.user.userState !== 3 && vm.user.userState !== 4; }, err => { @@ -219,7 +218,7 @@ }); }); } - + /** * Used to emit the save event and await any async operations being performed by editor extensions * @param {any} savedUser @@ -228,7 +227,7 @@ //used to track any promises added by the event handlers to be awaited var promises = []; - + var args = { //getPromise: getPromise, user: savedUser, @@ -240,10 +239,10 @@ //emit the event eventsService.emit("editors.user.editController.save", args); - + //await all promises to complete var resultPromise = $q.all(promises); - + return resultPromise; } @@ -253,7 +252,7 @@ function openUserGroupPicker() { var currentSelection = []; - angular.copy(vm.user.userGroups, currentSelection); + Utilities.copy(vm.user.userGroups, currentSelection); var userGroupPicker = { selection: currentSelection, submit: function (model) { @@ -263,7 +262,7 @@ } editorService.close(); }, - close: function () { + close: function () { editorService.close(); } }; @@ -355,10 +354,10 @@ vm.user.userState = 1; setUserDisplayState(); vm.disableUserButtonState = "success"; - + }, function (error) { vm.disableUserButtonState = "error"; - + }); } @@ -380,7 +379,7 @@ vm.user.failedPasswordAttempts = 0; setUserDisplayState(); vm.unlockUserButtonState = "success"; - + }, function (error) { vm.unlockUserButtonState = "error"; }); @@ -448,7 +447,7 @@ function clearAvatar() { // get user usersResource.clearAvatar(vm.user.id).then(function (data) { - vm.user.avatars = data; + vm.user.avatars = data; }); } @@ -469,15 +468,15 @@ }).progress(function (evt) { if (vm.avatarFile.uploadStatus !== "done" && vm.avatarFile.uploadStatus !== "error") { - // set uploading status on file - vm.avatarFile.uploadStatus = "uploading"; + // set uploading status on file + vm.avatarFile.uploadStatus = "uploading"; - // calculate progress in percentage - var progressPercentage = parseInt(100.0 * evt.loaded / evt.total, 10); + // calculate progress in percentage + var progressPercentage = parseInt(100.0 * evt.loaded / evt.total, 10); - // set percentage property on file - vm.avatarFile.uploadProgress = progressPercentage; - } + // set percentage property on file + vm.avatarFile.uploadProgress = progressPercentage; + } }).success(function (data, status, headers, config) { diff --git a/src/Umbraco.Web.UI.Client/src/views/users/views/users/users.controller.js b/src/Umbraco.Web.UI.Client/src/views/users/views/users/users.controller.js index 4ac385921e..102efae702 100644 --- a/src/Umbraco.Web.UI.Client/src/views/users/views/users/users.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/users/views/users/users.controller.js @@ -67,7 +67,7 @@ ]; // Get last selected layout for "users" (defaults to first layout = card layout) - vm.activeLayout = listViewHelper.getLayout("users", vm.layouts); + vm.activeLayout = listViewHelper.getLayout("users", vm.layouts); // Don't show the invite button if no email is configured if (Umbraco.Sys.ServerVariables.umbracoSettings.showUserInvite) { @@ -247,19 +247,19 @@ function selectLayout(selectedLayout) { // save the selected layout for "users" so it's applied next time the user visits this section - vm.activeLayout = listViewHelper.setLayout("users", selectedLayout, vm.layouts); + vm.activeLayout = listViewHelper.setLayout("users", selectedLayout, vm.layouts); } - + function isSelectable(user) { return !user.isCurrentUser; } - + function selectUser(user) { - + if (!isSelectable(user)) { return; } - + if (user.selected) { var index = vm.selection.indexOf(user.id); vm.selection.splice(index, 1); @@ -268,9 +268,9 @@ user.selected = true; vm.selection.push(user.id); } - + setBulkActions(vm.users); - + } function clearSelection() { @@ -279,14 +279,14 @@ }); vm.selection = []; } - + function clickUser(user, $event) { - + $event.stopPropagation(); - + if ($event) { // targeting a new tab/window? - if ($event.ctrlKey || + if ($event.ctrlKey || $event.shiftKey || $event.metaKey || // apple ($event.button && $event.button === 1) // middle click, >IE9 + everyone else @@ -295,7 +295,7 @@ return; } } - + goToUser(user); $event.preventDefault(); @@ -398,7 +398,7 @@ function openUserGroupPicker() { var currentSelection = []; - angular.copy(vm.newUser.userGroups, currentSelection); + Utilities.copy(vm.newUser.userGroups, currentSelection); var userGroupPicker = { selection: currentSelection, submit: function (model) { @@ -611,7 +611,7 @@ // copy to clip board success function copySuccess() { if (vm.page.copyPasswordButtonState !== "success") { - $timeout(function(){ + $timeout(function () { vm.page.copyPasswordButtonState = "success"; }); $timeout(function () { @@ -623,7 +623,7 @@ // copy to clip board error function copyError() { if (vm.page.copyPasswordButtonState !== "error") { - $timeout(function() { + $timeout(function () { vm.page.copyPasswordButtonState = "error"; }); $timeout(function () { @@ -654,7 +654,7 @@ return null; } - + function getEditPath(user) { return pathToUser(user) + usersOptionsAsQueryString(); } @@ -699,7 +699,7 @@ vm.usersOptions.pageSize = data.pageSize; vm.usersOptions.totalItems = data.totalItems; vm.usersOptions.totalPages = data.totalPages; - + formatDates(vm.users); setUserDisplayState(vm.users); vm.userStatesFilter = usersHelper.getUserStatesFilter(data.userStates); @@ -753,19 +753,19 @@ var firstSelectedUserGroups; angular.forEach(users, function (user) { - + if (!user.selected) { return; } - - + + // if the current user is selected prevent any bulk actions with the user included if (user.isCurrentUser) { vm.allowDisableUser = false; vm.allowEnableUser = false; vm.allowUnlockUser = false; vm.allowSetUserGroup = false; - + return false; } diff --git a/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js b/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js index 965fcdce71..2888351783 100644 --- a/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js +++ b/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js @@ -51,12 +51,12 @@ angular.mock.$Browser = function () { self.onUrlChange = function (listener) { self.pollFns.push( - function () { - if (self.$$lastUrl != self.$$url) { - self.$$lastUrl = self.$$url; - listener(self.$$url); - } - } + function () { + if (self.$$lastUrl != self.$$url) { + self.$$lastUrl = self.$$url; + listener(self.$$url); + } + } ); return listener; @@ -172,8 +172,8 @@ angular.mock.$Browser.prototype = { } } else { if (!angular.equals(this.cookieHash, this.lastCookieHash)) { - this.lastCookieHash = angular.copy(this.cookieHash); - this.cookieHash = angular.copy(this.cookieHash); + this.lastCookieHash = Utilities.copy(this.cookieHash); + this.cookieHash = Utilities.copy(this.cookieHash); } return this.cookieHash; } @@ -397,7 +397,7 @@ angular.mock.$LogProvider = function () { }); if (errors.length) { errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or an expected " + - "log message was not checked and removed:"); + "log message was not checked and removed:"); errors.push(''); throw new Error(errors.join('\n---------\n')); } @@ -581,12 +581,12 @@ angular.mock.$LogProvider = function () { if (self.toISOString) { self.toISOString = function () { return padNumber(self.origDate.getUTCFullYear(), 4) + '-' + - padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' + - padNumber(self.origDate.getUTCDate(), 2) + 'T' + - padNumber(self.origDate.getUTCHours(), 2) + ':' + - padNumber(self.origDate.getUTCMinutes(), 2) + ':' + - padNumber(self.origDate.getUTCSeconds(), 2) + '.' + - padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z' + padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' + + padNumber(self.origDate.getUTCDate(), 2) + 'T' + + padNumber(self.origDate.getUTCHours(), 2) + ':' + + padNumber(self.origDate.getUTCMinutes(), 2) + ':' + + padNumber(self.origDate.getUTCSeconds(), 2) + '.' + + padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z' } } @@ -1004,7 +1004,7 @@ function createHttpBackendMock($rootScope, $delegate, $browser) { throw wasExpected ? Error('No response defined !') : Error('Unexpected request: ' + method + ' ' + url + '\n' + - (expectation ? 'Expected ' + expectation : 'No more request expected')); + (expectation ? 'Expected ' + expectation : 'No more request expected')); } /** From 90890cea333dd0733ba1c14fbde7105959f72ce3 Mon Sep 17 00:00:00 2001 From: Jan Skovgaard Date: Tue, 14 Apr 2020 10:28:16 +0200 Subject: [PATCH 28/46] Replace instances of angular.element() (#7951) --- .../application/umbbackdrop.directive.js | 20 +- .../application/umbsearch.directive.js | 28 +- .../application/umbtour.directive.js | 100 ++++---- .../forms/hexbackgroundcolor.directive.js | 7 +- .../components/umbdatetimepicker.directive.js | 242 +++++++++--------- .../components/umbimagelazyload.directive.js | 4 +- .../components/umbrangeslider.directive.js | 104 ++++---- .../directives/util/autoscale.directive.js | 4 +- .../util/disabletabindex.directive.js | 62 ++--- .../src/preview/preview.controller.js | 38 +-- .../mediapicker/mediapicker.controller.js | 10 +- .../nodename/nodename.controller.js | 8 +- .../doctypename/doctypename.controller.js | 8 +- .../propertyname/propertyname.controller.js | 6 +- .../tabname/tabname.controller.js | 6 +- .../foldername/foldername.controller.js | 8 +- .../uploadimages/uploadimages.controller.js | 7 +- .../templatetree/templatetree.controller.js | 9 +- .../src/views/templates/edit.controller.js | 2 +- .../test/lib/angular/angular-mocks.js | 10 +- 20 files changed, 340 insertions(+), 343 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbbackdrop.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbbackdrop.directive.js index 39e4f10666..4b24075748 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbbackdrop.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbbackdrop.directive.js @@ -7,8 +7,8 @@ var events = []; - scope.clickBackdrop = function(event) { - if(scope.disableEventsOnClick === true) { + scope.clickBackdrop = function (event) { + if (scope.disableEventsOnClick === true) { event.preventDefault(); event.stopPropagation(); } @@ -22,16 +22,16 @@ } - function setHighlight () { + function setHighlight() { scope.loading = true; $timeout(function () { // The element to highlight - var highlightElement = angular.element(scope.highlightElement); + var highlightElement = $(scope.highlightElement); - if(highlightElement && highlightElement.length > 0) { + if (highlightElement && highlightElement.length > 0) { var offset = highlightElement.offset(); var width = highlightElement.outerWidth(); @@ -48,7 +48,7 @@ var rectRight = el.find(".umb-backdrop__rect--right"); var rectBottom = el.find(".umb-backdrop__rect--bottom"); var rectLeft = el.find(".umb-backdrop__rect--left"); - + // Add the css scope.rectTopCss = { "height": topDistance, "left": leftDistance + "px", opacity: scope.backdropOpacity }; scope.rectRightCss = { "left": leftAndWidth + "px", "top": topDistance + "px", "height": height, opacity: scope.backdropOpacity }; @@ -56,14 +56,14 @@ scope.rectLeftCss = { "width": leftDistance, opacity: scope.backdropOpacity }; // Prevent interaction in the highlighted area - if(scope.highlightPreventClick) { + if (scope.highlightPreventClick) { var preventClickElement = el.find(".umb-backdrop__highlight-prevent-click"); preventClickElement.css({ "width": width, "height": height, "left": offset.left, "top": offset.top }); } } - scope.loading = false; + scope.loading = false; }); @@ -74,8 +74,8 @@ } events.push(scope.$watch("highlightElement", function (newValue, oldValue) { - if(!newValue) {return;} - if(newValue === oldValue) {return;} + if (!newValue) { return; } + if (newValue === oldValue) { return; } setHighlight(); })); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbsearch.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbsearch.directive.js index 8434a96ba5..e03e63b68f 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbsearch.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbsearch.directive.js @@ -12,7 +12,7 @@ onClose: "&" } }; - + function umbSearchController($timeout, backdropService, searchService, focusService) { var vm = this; @@ -25,7 +25,7 @@ vm.handleKeyDown = handleKeyDown; vm.closeSearch = closeSearch; vm.focusSearch = focusSearch; - + //we need to capture the focus before this element is initialized. vm.focusBeforeOpening = focusService.getLastKnownFocus(); @@ -66,8 +66,8 @@ */ function focusSearch() { vm.searchHasFocus = false; - $timeout(function(){ - vm.searchHasFocus = true; + $timeout(function () { + vm.searchHasFocus = true; }); } @@ -76,14 +76,14 @@ * @param {object} event */ function handleKeyDown(event) { - + // esc - if(event.keyCode === 27) { + if (event.keyCode === 27) { event.stopPropagation(); event.preventDefault(); - + closeSearch(); - return; + return; } // up/down (navigate search results) @@ -132,7 +132,7 @@ } $timeout(function () { - var resultElementLink = angular.element(".umb-search-item[active-result='true'] .umb-search-result__link"); + var resultElementLink = $(".umb-search-item[active-result='true'] .umb-search-result__link"); resultElementLink[0].focus(); }); } @@ -142,10 +142,10 @@ * Used to proxy a callback */ function closeSearch() { - if(vm.focusBeforeOpening) { + if (vm.focusBeforeOpening) { vm.focusBeforeOpening.focus(); } - if(vm.onClose) { + if (vm.onClose) { vm.onClose(); } } @@ -155,9 +155,9 @@ * @param {string} searchQuery */ function search(searchQuery) { - if(searchQuery.length > 0) { - var search = {"term": searchQuery}; - searchService.searchAll(search).then(function(result){ + if (searchQuery.length > 0) { + var search = { "term": searchQuery }; + searchService.searchAll(search).then(function (result) { //result is a dictionary of group Title and it's results var filtered = {}; _.each(result, function (value, key) { diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbtour.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbtour.directive.js index 287962b6d3..6f98dbca6e 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbtour.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbtour.directive.js @@ -198,27 +198,27 @@ In the following example you see how to run some custom logic before a step goes scope.loadingStep = false; scope.elementNotFound = false; - scope.model.nextStep = function() { + scope.model.nextStep = function () { nextStep(); }; - scope.model.endTour = function() { + scope.model.endTour = function () { unbindEvent(); tourService.endTour(scope.model); backdropService.close(); }; - scope.model.completeTour = function() { + scope.model.completeTour = function () { unbindEvent(); - tourService.completeTour(scope.model).then(function() { - backdropService.close(); + tourService.completeTour(scope.model).then(function () { + backdropService.close(); }); }; - scope.model.disableTour = function() { + scope.model.disableTour = function () { unbindEvent(); - tourService.disableTour(scope.model).then(function() { - backdropService.close(); + tourService.disableTour(scope.model).then(function () { + backdropService.close(); }); } @@ -227,7 +227,7 @@ In the following example you see how to run some custom logic before a step goes pulseElement = el.find(".umb-tour__pulse"); popover.hide(); scope.model.currentStepIndex = 0; - backdropService.open({disableEventsOnClick: true}); + backdropService.open({ disableEventsOnClick: true }); startStep(); } @@ -249,20 +249,20 @@ In the following example you see how to run some custom logic before a step goes } function nextStep() { - + popover.hide(); pulseElement.hide(); $timeout.cancel(pulseTimer); scope.model.currentStepIndex++; // make sure we don't go too far - if(scope.model.currentStepIndex !== scope.model.steps.length) { + if (scope.model.currentStepIndex !== scope.model.steps.length) { startStep(); - // tour completed - final step + // tour completed - final step } else { scope.loadingStep = true; - waitForPendingRerequests().then(function(){ + waitForPendingRerequests().then(function () { scope.loadingStep = false; // clear current step scope.model.currentStep = {}; @@ -280,17 +280,17 @@ In the following example you see how to run some custom logic before a step goes backdropService.setOpacity(scope.model.steps[scope.model.currentStepIndex].backdropOpacity); backdropService.setHighlight(null); - waitForPendingRerequests().then(function() { + waitForPendingRerequests().then(function () { scope.model.currentStep = scope.model.steps[scope.model.currentStepIndex]; setView(); - + // if highlight element is set - find it findHighlightElement(); // if a custom event needs to be bound we do it now - if(scope.model.currentStep.event) { + if (scope.model.currentStep.event) { bindEvent(); } @@ -301,7 +301,7 @@ In the following example you see how to run some custom logic before a step goes function findHighlightElement() { - scope.elementNotFound = false; + scope.elementNotFound = false; $timeout(function () { // clear element when step as marked as intro, so it always displays in the center @@ -312,15 +312,15 @@ In the following example you see how to run some custom logic before a step goes } // if an element isn't set - show the popover in the center - if(scope.model.currentStep && !scope.model.currentStep.element) { + if (scope.model.currentStep && !scope.model.currentStep.element) { setPopoverPosition(null); return; } - var element = angular.element(scope.model.currentStep.element); + var element = $(scope.model.currentStep.element); // we couldn't find the element in the dom - abort and show error - if(element.length === 0) { + if (element.length === 0) { scope.elementNotFound = true; setPopoverPosition(null); return; @@ -337,7 +337,7 @@ In the following example you see how to run some custom logic before a step goes el = el.offsetParent(); } } - + var scrollToCenterOfContainer = offsetTop - (scrollParent[0].clientHeight / 2); if (element[0].clientHeight < scrollParent[0].clientHeight) { scrollToCenterOfContainer += (element[0].clientHeight / 2); @@ -366,7 +366,7 @@ In the following example you see how to run some custom logic before a step goes function setPopoverPosition(element) { $timeout(function () { - + var position = "center"; var margin = 20; var css = {}; @@ -374,10 +374,10 @@ In the following example you see how to run some custom logic before a step goes var popoverWidth = popover.outerWidth(); var popoverHeight = popover.outerHeight(); var popoverOffset = popover.offset(); - var documentWidth = angular.element(document).width(); - var documentHeight = angular.element(document).height(); + var documentWidth = $(document).width(); + var documentHeight = $(document).height(); - if(element) { + if (element) { var offset = element.offset(); var width = element.outerWidth(); @@ -436,29 +436,29 @@ In the following example you see how to run some custom logic before a step goes } else { // if there is no dom element center the popover - css.top = "calc(50% - " + popoverHeight/2 + "px)"; - css.left = "calc(50% - " + popoverWidth/2 + "px)"; + css.top = "calc(50% - " + popoverHeight / 2 + "px)"; + css.left = "calc(50% - " + popoverWidth / 2 + "px)"; } popover.css(css).fadeIn("fast"); - + }); } function setPulsePosition() { - if(scope.model.currentStep.event) { + if (scope.model.currentStep.event) { + + pulseTimer = $timeout(function () { - pulseTimer = $timeout(function(){ - var clickElementSelector = scope.model.currentStep.eventElement ? scope.model.currentStep.eventElement : scope.model.currentStep.element; var clickElement = $(clickElementSelector); - + var offset = clickElement.offset(); var width = clickElement.outerWidth(); var height = clickElement.outerHeight(); - + pulseElement.css({ "width": width, "height": height, "left": offset.left, "top": offset.top }); pulseElement.fadeIn(); @@ -468,24 +468,24 @@ In the following example you see how to run some custom logic before a step goes function waitForPendingRerequests() { var deferred = $q.defer(); - var timer = window.setInterval(function(){ - + var timer = window.setInterval(function () { + var requestsReady = false; var animationsDone = false; // check for pending requests both in angular and on the document - if($http.pendingRequests.length === 0 && document.readyState === "complete") { + if ($http.pendingRequests.length === 0 && document.readyState === "complete") { requestsReady = true; } // check for animations. ng-enter and ng-leave are default angular animations. // Also check for infinite editors animating - if(document.querySelectorAll(".ng-enter, .ng-leave, .umb-editor--animating").length === 0) { + if (document.querySelectorAll(".ng-enter, .ng-leave, .umb-editor--animating").length === 0) { animationsDone = true; } - if(requestsReady && animationsDone) { - $timeout(function(){ + if (requestsReady && animationsDone) { + $timeout(function () { deferred.resolve(); clearInterval(timer); }); @@ -512,14 +512,14 @@ In the following example you see how to run some custom logic before a step goes var bindToElement = scope.model.currentStep.element; var eventName = scope.model.currentStep.event + ".step-" + scope.model.currentStepIndex; var removeEventName = "remove.step-" + scope.model.currentStepIndex; - var handled = false; + var handled = false; - if(scope.model.currentStep.eventElement) { + if (scope.model.currentStep.eventElement) { bindToElement = scope.model.currentStep.eventElement; } - $(bindToElement).on(eventName, function(){ - if(!handled) { + $(bindToElement).on(eventName, function () { + if (!handled) { unbindEvent(); nextStep(); handled = true; @@ -530,7 +530,7 @@ In the following example you see how to run some custom logic before a step goes // for some reason it seems the elements gets removed before the event is raised. This is a temp solution which assumes: // "if you ask me to click on an element, and it suddenly gets removed from the dom, let's go on to the next step". $(bindToElement).on(removeEventName, function () { - if(!handled) { + if (!handled) { unbindEvent(); nextStep(); handled = true; @@ -542,13 +542,13 @@ In the following example you see how to run some custom logic before a step goes function unbindEvent() { var eventName = scope.model.currentStep.event + ".step-" + scope.model.currentStepIndex; var removeEventName = "remove.step-" + scope.model.currentStepIndex; - - if(scope.model.currentStep.eventElement) { - angular.element(scope.model.currentStep.eventElement).off(eventName); - angular.element(scope.model.currentStep.eventElement).off(removeEventName); + + if (scope.model.currentStep.eventElement) { + $(scope.model.currentStep.eventElement).off(eventName); + $(scope.model.currentStep.eventElement).off(removeEventName); } else { - angular.element(scope.model.currentStep.element).off(eventName); - angular.element(scope.model.currentStep.element).off(removeEventName); + $(scope.model.currentStep.element).off(eventName); + $(scope.model.currentStep.element).off(removeEventName); } } diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/hexbackgroundcolor.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/hexbackgroundcolor.directive.js index 6780ad8e58..eff05c94ff 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/hexbackgroundcolor.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/hexbackgroundcolor.directive.js @@ -7,13 +7,12 @@ * a color will not be set. **/ function hexBgColor() { - return { + return { restrict: "A", link: function (scope, element, attr, formCtrl) { function setBackgroundColor(color) { - // note: can't use element.css(), it doesn't support hexa background colors - angular.element(element)[0].style.backgroundColor = "#" + color; + element[0].style.backgroundColor = "#" + color; } // Only add inline hex background color if defined and not "true". @@ -24,7 +23,7 @@ function hexBgColor() { // Set the orig based on the attribute if there is one. origColor = attr.hexBgOrig; } - + attr.$observe("hexBgColor", function (newVal) { if (newVal) { if (!origColor) { diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbdatetimepicker.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbdatetimepicker.directive.js index 5433f73fa6..0498b81963 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbdatetimepicker.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbdatetimepicker.directive.js @@ -67,37 +67,37 @@ Use this directive to render a date time picker @param {callback} onDayCreate (callback): Take full control of every date cell with theonDayCreate()hook. **/ -(function() { - 'use strict'; +(function () { + 'use strict'; - var umbDateTimePicker = { - template: '' + - '' + - '
    ' + - '
    ', - controller: umbDateTimePickerCtrl, - transclude: true, - bindings: { - ngModel: '<', - options: '<', - onSetup: '&?', - onChange: '&?', - onOpen: '&?', - onClose: '&?', - onMonthChange: '&?', - onYearChange: '&?', - onReady: '&?', - onValueUpdate: '&?', - onDayCreate: '&?' - } + var umbDateTimePicker = { + template: '' + + '' + + '
    ' + + '
    ', + controller: umbDateTimePickerCtrl, + transclude: true, + bindings: { + ngModel: '<', + options: '<', + onSetup: '&?', + onChange: '&?', + onOpen: '&?', + onClose: '&?', + onMonthChange: '&?', + onYearChange: '&?', + onReady: '&?', + onValueUpdate: '&?', + onDayCreate: '&?' + } }; - + function umbDateTimePickerCtrl($element, $timeout, $scope, assetsService, userService) { var ctrl = this; var userLocale = null; - ctrl.$onInit = function() { + ctrl.$onInit = function () { // load css file for the date picker assetsService.loadCss('lib/flatpickr/flatpickr.css', $scope).then(function () { @@ -113,27 +113,27 @@ Use this directive to render a date time picker }); }); - }; + }; - function grabElementAndRunFlatpickr() { - $timeout(function() { - var transcludeEl = $element.find('ng-transclude')[0]; - var element = transcludeEl.children[0]; + function grabElementAndRunFlatpickr() { + $timeout(function () { + var transcludeEl = $element.find('ng-transclude')[0]; + var element = transcludeEl.children[0]; - setDatepicker(element); - }, 0, true); - } + setDatepicker(element); + }, 0, true); + } - function setDatepicker(element) { - var fpLib = flatpickr ? flatpickr : FlatpickrInstance; + function setDatepicker(element) { + var fpLib = flatpickr ? flatpickr : FlatpickrInstance; - if (!fpLib) { - return console.warn('Unable to find any flatpickr installation'); - } + if (!fpLib) { + return console.warn('Unable to find any flatpickr installation'); + } var fpInstance; - setUpCallbacks(); + setUpCallbacks(); if (!ctrl.options.locale) { ctrl.options.locale = userLocale; @@ -149,101 +149,101 @@ Use this directive to render a date time picker }; fpInstance = new fpLib(element, ctrl.options); - - if (ctrl.onSetup) { - ctrl.onSetup({ - fpItem: fpInstance - }); - } - // If has ngModel set the date - if (ctrl.ngModel) { - fpInstance.setDate(ctrl.ngModel); - } + if (ctrl.onSetup) { + ctrl.onSetup({ + fpItem: fpInstance + }); + } - // destroy the flatpickr instance when the dom element is removed - angular.element(element).on('$destroy', function() { - fpInstance.destroy(); - }); + // If has ngModel set the date + if (ctrl.ngModel) { + fpInstance.setDate(ctrl.ngModel); + } - // Refresh the scope - $scope.$applyAsync(); - } + // destroy the flatpickr instance when the dom element is removed + $(element).on('$destroy', function () { + fpInstance.destroy(); + }); - function setUpCallbacks() { - // bind hook for onChange - if(ctrl.options && ctrl.onChange) { - ctrl.options.onChange = function(selectedDates, dateStr, instance) { - $timeout(function() { - ctrl.onChange({selectedDates: selectedDates, dateStr: dateStr, instance: instance}); - }); - }; - } + // Refresh the scope + $scope.$applyAsync(); + } - // bind hook for onOpen - if(ctrl.options && ctrl.onOpen) { - ctrl.options.onOpen = function(selectedDates, dateStr, instance) { - $timeout(function() { - ctrl.onOpen({selectedDates: selectedDates, dateStr: dateStr, instance: instance}); - }); - }; - } + function setUpCallbacks() { + // bind hook for onChange + if (ctrl.options && ctrl.onChange) { + ctrl.options.onChange = function (selectedDates, dateStr, instance) { + $timeout(function () { + ctrl.onChange({ selectedDates: selectedDates, dateStr: dateStr, instance: instance }); + }); + }; + } - // bind hook for onOpen - if(ctrl.options && ctrl.onClose) { - ctrl.options.onClose = function(selectedDates, dateStr, instance) { - $timeout(function() { - ctrl.onClose({selectedDates: selectedDates, dateStr: dateStr, instance: instance}); - }); - }; - } + // bind hook for onOpen + if (ctrl.options && ctrl.onOpen) { + ctrl.options.onOpen = function (selectedDates, dateStr, instance) { + $timeout(function () { + ctrl.onOpen({ selectedDates: selectedDates, dateStr: dateStr, instance: instance }); + }); + }; + } - // bind hook for onMonthChange - if(ctrl.options && ctrl.onMonthChange) { - ctrl.options.onMonthChange = function(selectedDates, dateStr, instance) { - $timeout(function() { - ctrl.onMonthChange({selectedDates: selectedDates, dateStr: dateStr, instance: instance}); - }); - }; - } + // bind hook for onOpen + if (ctrl.options && ctrl.onClose) { + ctrl.options.onClose = function (selectedDates, dateStr, instance) { + $timeout(function () { + ctrl.onClose({ selectedDates: selectedDates, dateStr: dateStr, instance: instance }); + }); + }; + } - // bind hook for onYearChange - if(ctrl.options && ctrl.onYearChange) { - ctrl.options.onYearChange = function(selectedDates, dateStr, instance) { - $timeout(function() { - ctrl.onYearChange({selectedDates: selectedDates, dateStr: dateStr, instance: instance}); - }); - }; - } + // bind hook for onMonthChange + if (ctrl.options && ctrl.onMonthChange) { + ctrl.options.onMonthChange = function (selectedDates, dateStr, instance) { + $timeout(function () { + ctrl.onMonthChange({ selectedDates: selectedDates, dateStr: dateStr, instance: instance }); + }); + }; + } - // bind hook for onReady - if(ctrl.options && ctrl.onReady) { - ctrl.options.onReady = function(selectedDates, dateStr, instance) { - $timeout(function() { - ctrl.onReady({selectedDates: selectedDates, dateStr: dateStr, instance: instance}); - }); - }; - } + // bind hook for onYearChange + if (ctrl.options && ctrl.onYearChange) { + ctrl.options.onYearChange = function (selectedDates, dateStr, instance) { + $timeout(function () { + ctrl.onYearChange({ selectedDates: selectedDates, dateStr: dateStr, instance: instance }); + }); + }; + } - // bind hook for onValueUpdate - if(ctrl.onValueUpdate) { - ctrl.options.onValueUpdate = function(selectedDates, dateStr, instance) { - $timeout(function() { - ctrl.onValueUpdate({selectedDates: selectedDates, dateStr: dateStr, instance: instance}); - }); - }; - } + // bind hook for onReady + if (ctrl.options && ctrl.onReady) { + ctrl.options.onReady = function (selectedDates, dateStr, instance) { + $timeout(function () { + ctrl.onReady({ selectedDates: selectedDates, dateStr: dateStr, instance: instance }); + }); + }; + } - // bind hook for onDayCreate - if(ctrl.onDayCreate) { - ctrl.options.onDayCreate = function(selectedDates, dateStr, instance) { - $timeout(function() { - ctrl.onDayCreate({selectedDates: selectedDates, dateStr: dateStr, instance: instance}); - }); - }; - } + // bind hook for onValueUpdate + if (ctrl.onValueUpdate) { + ctrl.options.onValueUpdate = function (selectedDates, dateStr, instance) { + $timeout(function () { + ctrl.onValueUpdate({ selectedDates: selectedDates, dateStr: dateStr, instance: instance }); + }); + }; + } - } + // bind hook for onDayCreate + if (ctrl.onDayCreate) { + ctrl.options.onDayCreate = function (selectedDates, dateStr, instance) { + $timeout(function () { + ctrl.onDayCreate({ selectedDates: selectedDates, dateStr: dateStr, instance: instance }); + }); + }; + } + + } } // umbFlatpickr (umb-flatpickr) is deprecated, but we keep it for backwards compatibility diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbimagelazyload.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbimagelazyload.directive.js index 9d76993fd3..988f8fab24 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbimagelazyload.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbimagelazyload.directive.js @@ -31,7 +31,7 @@ Use this directive to lazy-load an image only when it is scrolled into view. **/ -(function() { +(function () { 'use strict'; function ImageLazyLoadDirective() { @@ -41,7 +41,7 @@ Use this directive to lazy-load an image only when it is scrolled into view. function link(scope, element, attrs) { const observer = new IntersectionObserver(loadImg); - const img = angular.element(element)[0]; + const img = element[0]; img.src = placeholder; observer.observe(img); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbrangeslider.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbrangeslider.directive.js index 0003658600..21a1f181a6 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/umbrangeslider.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbrangeslider.directive.js @@ -57,13 +57,13 @@ For extra details about options and events take a look here: https://refreshless **/ -(function() { - 'use strict'; +(function () { + 'use strict'; - var umbRangeSlider = { + var umbRangeSlider = { template: '
    ', - controller: UmbRangeSliderController, - bindings: { + controller: UmbRangeSliderController, + bindings: { ngModel: '<', options: '<', onSetup: '&?', @@ -73,15 +73,15 @@ For extra details about options and events take a look here: https://refreshless onChange: '&?', onStart: '&?', onEnd: '&?' - } + } }; - - function UmbRangeSliderController($element, $timeout, $scope, assetsService) { - + + function UmbRangeSliderController($element, $timeout, $scope, assetsService) { + const ctrl = this; let sliderInstance = null; - ctrl.$onInit = function() { + ctrl.$onInit = function () { // load css file for the date picker assetsService.loadCss('lib/nouislider/nouislider.min.css', $scope); @@ -94,13 +94,13 @@ For extra details about options and events take a look here: https://refreshless }; - function grabElementAndRun() { - $timeout(function() { + function grabElementAndRun() { + $timeout(function () { const element = $element.find('.umb-range-slider')[0]; - setSlider(element); - }, 0, true); + setSlider(element); + }, 0, true); } - + function setSlider(element) { sliderInstance = element; @@ -117,82 +117,82 @@ For extra details about options and events take a look here: https://refreshless // create new slider noUiSlider.create(sliderInstance, options); - - if (ctrl.onSetup) { - ctrl.onSetup({ - slider: sliderInstance - }); + + if (ctrl.onSetup) { + ctrl.onSetup({ + slider: sliderInstance + }); } // If has ngModel set the date - if (ctrl.ngModel) { + if (ctrl.ngModel) { sliderInstance.noUiSlider.set(ctrl.ngModel); } // destroy the slider instance when the dom element is removed - angular.element(element).on('$destroy', function() { + $(element).on('$destroy', function () { sliderInstance.noUiSlider.off(); }); setUpCallbacks(); - // Refresh the scope - $scope.$applyAsync(); + // Refresh the scope + $scope.$applyAsync(); } - + function setUpCallbacks() { - if(sliderInstance) { + if (sliderInstance) { // bind hook for update - if(ctrl.onUpdate) { - sliderInstance.noUiSlider.on('update', function (values, handle, unencoded, tap, positions) { - $timeout(function() { - ctrl.onUpdate({values: values, handle: handle, unencoded: unencoded, tap: tap, positions: positions}); + if (ctrl.onUpdate) { + sliderInstance.noUiSlider.on('update', function (values, handle, unencoded, tap, positions) { + $timeout(function () { + ctrl.onUpdate({ values: values, handle: handle, unencoded: unencoded, tap: tap, positions: positions }); }); }); } // bind hook for slide - if(ctrl.onSlide) { - sliderInstance.noUiSlider.on('slide', function (values, handle, unencoded, tap, positions) { - $timeout(function() { - ctrl.onSlide({values: values, handle: handle, unencoded: unencoded, tap: tap, positions: positions}); + if (ctrl.onSlide) { + sliderInstance.noUiSlider.on('slide', function (values, handle, unencoded, tap, positions) { + $timeout(function () { + ctrl.onSlide({ values: values, handle: handle, unencoded: unencoded, tap: tap, positions: positions }); }); }); } // bind hook for set - if(ctrl.onSet) { - sliderInstance.noUiSlider.on('set', function (values, handle, unencoded, tap, positions) { - $timeout(function() { - ctrl.onSet({values: values, handle: handle, unencoded: unencoded, tap: tap, positions: positions}); + if (ctrl.onSet) { + sliderInstance.noUiSlider.on('set', function (values, handle, unencoded, tap, positions) { + $timeout(function () { + ctrl.onSet({ values: values, handle: handle, unencoded: unencoded, tap: tap, positions: positions }); }); }); } // bind hook for change - if(ctrl.onChange) { - sliderInstance.noUiSlider.on('change', function (values, handle, unencoded, tap, positions) { - $timeout(function() { - ctrl.onChange({values: values, handle: handle, unencoded: unencoded, tap: tap, positions: positions}); + if (ctrl.onChange) { + sliderInstance.noUiSlider.on('change', function (values, handle, unencoded, tap, positions) { + $timeout(function () { + ctrl.onChange({ values: values, handle: handle, unencoded: unencoded, tap: tap, positions: positions }); }); }); } // bind hook for start - if(ctrl.onStart) { - sliderInstance.noUiSlider.on('start', function (values, handle, unencoded, tap, positions) { - $timeout(function() { - ctrl.onStart({values: values, handle: handle, unencoded: unencoded, tap: tap, positions: positions}); + if (ctrl.onStart) { + sliderInstance.noUiSlider.on('start', function (values, handle, unencoded, tap, positions) { + $timeout(function () { + ctrl.onStart({ values: values, handle: handle, unencoded: unencoded, tap: tap, positions: positions }); }); }); } // bind hook for end - if(ctrl.onEnd) { - sliderInstance.noUiSlider.on('end', function (values, handle, unencoded, tap, positions) { - $timeout(function() { - ctrl.onEnd({values: values, handle: handle, unencoded: unencoded, tap: tap, positions: positions}); + if (ctrl.onEnd) { + sliderInstance.noUiSlider.on('end', function (values, handle, unencoded, tap, positions) { + $timeout(function () { + ctrl.onEnd({ values: values, handle: handle, unencoded: unencoded, tap: tap, positions: positions }); }); }); } @@ -201,7 +201,7 @@ For extra details about options and events take a look here: https://refreshless } } - + angular.module('umbraco.directives').component('umbRangeSlider', umbRangeSlider); - + })(); diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/util/autoscale.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/util/autoscale.directive.js index 029a4e420f..023692be86 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/util/autoscale.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/util/autoscale.directive.js @@ -21,7 +21,7 @@ angular.module("umbraco.directives") var totalOffset = 0; var offsety = parseInt(attrs.autoScale, 10); - var window = angular.element($window); + var window = $($window); if (offsety !== undefined) { totalOffset += offsety; } @@ -34,7 +34,7 @@ angular.module("umbraco.directives") el.height(window.height() - (el.offset().top + totalOffset)); } - var resizeCallback = function() { + var resizeCallback = function () { setElementSize(); }; diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/util/disabletabindex.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/util/disabletabindex.directive.js index 759d05df71..d43282715e 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/util/disabletabindex.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/util/disabletabindex.directive.js @@ -1,46 +1,46 @@ angular.module("umbraco.directives") .directive('disableTabindex', function (tabbableService) { - return { - restrict: 'A', //Can only be used as an attribute, - scope: { - "disableTabindex": "<" - }, - link: function (scope, element, attrs) { + return { + restrict: 'A', //Can only be used as an attribute, + scope: { + "disableTabindex": "<" + }, + link: function (scope, element, attrs) { - if(scope.disableTabindex) { - //Select the node that will be observed for mutations (native DOM element not jQLite version) - var targetNode = element[0]; + if (scope.disableTabindex) { + //Select the node that will be observed for mutations (native DOM element not jQLite version) + var targetNode = element[0]; - //Watch for DOM changes - so when the property editor subview loads in - //We can be notified its updated the child elements inside the DIV we are watching - var observer = new MutationObserver(domChange); + //Watch for DOM changes - so when the property editor subview loads in + //We can be notified its updated the child elements inside the DIV we are watching + var observer = new MutationObserver(domChange); - // Options for the observer (which mutations to observe) - var config = { attributes: true, childList: true, subtree: true }; + // Options for the observer (which mutations to observe) + var config = { attributes: true, childList: true, subtree: true }; - function domChange(mutationsList, observer) { - for(var mutation of mutationsList) { + function domChange(mutationsList, observer) { + for (var mutation of mutationsList) { - //DOM items have been added or removed - if (mutation.type == 'childList') { + //DOM items have been added or removed + if (mutation.type == 'childList') { - //Check if any child items in mutation.target contain an input - var childInputs = tabbableService.tabbable(mutation.target); + //Check if any child items in mutation.target contain an input + var childInputs = tabbableService.tabbable(mutation.target); - //For each item in childInputs - override or set HTML attribute tabindex="-1" - angular.forEach(childInputs, function(element){ - angular.element(element).attr('tabindex', '-1'); - }); + //For each item in childInputs - override or set HTML attribute tabindex="-1" + angular.forEach(childInputs, function (element) { + $(element).attr('tabindex', '-1'); + }); + } } } + + // Start observing the target node for configured mutations + //GO GO GO + observer.observe(targetNode, config); } - // Start observing the target node for configured mutations - //GO GO GO - observer.observe(targetNode, config); } - - } - }; -}); + }; + }); diff --git a/src/Umbraco.Web.UI.Client/src/preview/preview.controller.js b/src/Umbraco.Web.UI.Client/src/preview/preview.controller.js index dc40338d01..5ff8dd3633 100644 --- a/src/Umbraco.Web.UI.Client/src/preview/preview.controller.js +++ b/src/Umbraco.Web.UI.Client/src/preview/preview.controller.js @@ -6,8 +6,8 @@ var app = angular.module("umbraco.preview", ['umbraco.resources', 'umbraco.services']) .controller("previewController", function ($scope, $window, $location) { - - $scope.currentCulture = {iso:'', title:'...', icon:'icon-loading'} + + $scope.currentCulture = { iso: '', title: '...', icon: 'icon-loading' } var cultures = []; $scope.tabbingActive = false; @@ -21,7 +21,7 @@ var app = angular.module("umbraco.preview", ['umbraco.resources', 'umbraco.servi window.addEventListener('mousedown', disableTabbingActive); } } - + function disableTabbingActive(evt) { $scope.tabbingActive = false; $scope.$digest(); @@ -113,10 +113,10 @@ var app = angular.module("umbraco.preview", ['umbraco.resources', 'umbraco.servi $scope.sizeOpen = false; $scope.cultureOpen = false; - $scope.toggleSizeOpen = function() { + $scope.toggleSizeOpen = function () { $scope.sizeOpen = toggleMenu($scope.sizeOpen); } - $scope.toggleCultureOpen = function() { + $scope.toggleCultureOpen = function () { $scope.cultureOpen = toggleMenu($scope.cultureOpen); } @@ -132,8 +132,8 @@ var app = angular.module("umbraco.preview", ['umbraco.resources', 'umbraco.servi $scope.sizeOpen = false; $scope.cultureOpen = false; } - - $scope.windowClickHandler = function() { + + $scope.windowClickHandler = function () { closeOthers(); } function windowBlurHandler() { @@ -141,16 +141,16 @@ var app = angular.module("umbraco.preview", ['umbraco.resources', 'umbraco.servi $scope.$digest(); } - var win = angular.element($window); + var win = $($window); win.on("blur", windowBlurHandler); - + $scope.$on("$destroy", function () { - win.off("blur", handleBlwindowBlurHandlerur ); + win.off("blur", handleBlwindowBlurHandlerur); }); - - function setPageUrl(){ + + function setPageUrl() { $scope.pageId = $location.search().id || getParameterByName("id"); var culture = $location.search().culture || getParameterByName("culture"); @@ -204,27 +204,27 @@ var app = angular.module("umbraco.preview", ['umbraco.resources', 'umbraco.servi /* Change culture */ /*****************************************************************************/ $scope.changeCulture = function (iso) { - if($location.search().culture !== iso) { + if ($location.search().culture !== iso) { $scope.frameLoaded = false; $scope.currentCultureIso = iso; $location.search("culture", iso); setPageUrl(); } }; - $scope.registerCulture = function(iso, title, isDefault) { - var cultureObject = {iso: iso, title: title, isDefault: isDefault}; + $scope.registerCulture = function (iso, title, isDefault) { + var cultureObject = { iso: iso, title: title, isDefault: isDefault }; cultures.push(cultureObject); } - $scope.$watch("currentCultureIso", function(oldIso, newIso) { + $scope.$watch("currentCultureIso", function (oldIso, newIso) { // if no culture is selected, we will pick the default one: if ($scope.currentCultureIso === null) { - $scope.currentCulture = cultures.find(function(culture) { + $scope.currentCulture = cultures.find(function (culture) { return culture.isDefault === true; }) return; } - $scope.currentCulture = cultures.find(function(culture) { + $scope.currentCulture = cultures.find(function (culture) { return culture.iso === $scope.currentCultureIso; }) }); @@ -252,7 +252,7 @@ var app = angular.module("umbraco.preview", ['umbraco.resources', 'umbraco.servi }); } - function hideUmbracoPreviewBadge (iframe) { + function hideUmbracoPreviewBadge(iframe) { if (iframe && iframe.contentDocument && iframe.contentDocument.getElementById("umbracoPreviewBadge")) { iframe.contentDocument.getElementById("umbracoPreviewBadge").style.display = "none"; } diff --git a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js index 89e55d2f2c..7a4db7cbc5 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/mediapicker/mediapicker.controller.js @@ -156,15 +156,15 @@ angular.module("umbraco") } } - function upload(v) { - angular.element(".umb-file-dropzone .file-select").trigger("click"); + function upload() { + $(".umb-file-dropzone .file-select").trigger("click"); } - function dragLeave(el, event) { + function dragLeave() { $scope.activeDrag = false; } - function dragEnter(el, event) { + function dragEnter() { $scope.activeDrag = true; } @@ -341,7 +341,7 @@ angular.module("umbraco") return false; } - function gotoStartNode(err) { + function gotoStartNode() { gotoFolder({ id: $scope.startNodeId, name: "Media", icon: "icon-folder" }); } diff --git a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatecontent/nodename/nodename.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatecontent/nodename/nodename.controller.js index bdd7eb65d0..eca0c4582b 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatecontent/nodename/nodename.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatecontent/nodename/nodename.controller.js @@ -2,16 +2,16 @@ "use strict"; function NodeNameController($scope) { - + var vm = this; - var element = angular.element($scope.model.currentStep.element); + var element = $($scope.model.currentStep.element); vm.error = false; - + vm.initNextStep = initNextStep; function initNextStep() { - if(element.val().toLowerCase() === 'home') { + if (element.val().toLowerCase() === 'home') { $scope.model.nextStep(); } else { vm.error = true; diff --git a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatedoctype/doctypename/doctypename.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatedoctype/doctypename/doctypename.controller.js index fee52eb506..ed5a0b93e3 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatedoctype/doctypename/doctypename.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatedoctype/doctypename/doctypename.controller.js @@ -2,16 +2,16 @@ "use strict"; function DocTypeNameController($scope) { - + var vm = this; - var element = angular.element($scope.model.currentStep.element); + var element = $($scope.model.currentStep.element); vm.error = false; - + vm.initNextStep = initNextStep; function initNextStep() { - if(element.val().toLowerCase() === 'home page') { + if (element.val().toLowerCase() === 'home page') { $scope.model.nextStep(); } else { vm.error = true; diff --git a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatedoctype/propertyname/propertyname.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatedoctype/propertyname/propertyname.controller.js index 1ebe878928..5ceae2f2f8 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatedoctype/propertyname/propertyname.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatedoctype/propertyname/propertyname.controller.js @@ -2,12 +2,12 @@ "use strict"; function PropertyNameController($scope) { - + var vm = this; - var element = angular.element($scope.model.currentStep.element); + var element = $($scope.model.currentStep.element); vm.error = false; - + vm.initNextStep = initNextStep; function initNextStep() { diff --git a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatedoctype/tabname/tabname.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatedoctype/tabname/tabname.controller.js index c477204cb7..c134e50a34 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatedoctype/tabname/tabname.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrocreatedoctype/tabname/tabname.controller.js @@ -2,12 +2,12 @@ "use strict"; function TabNameController($scope) { - + var vm = this; - var element = angular.element($scope.model.currentStep.element); + var element = $($scope.model.currentStep.element); vm.error = false; - + vm.initNextStep = initNextStep; function initNextStep() { diff --git a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintromediasection/foldername/foldername.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintromediasection/foldername/foldername.controller.js index ebda50481d..bad9718251 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintromediasection/foldername/foldername.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintromediasection/foldername/foldername.controller.js @@ -2,16 +2,16 @@ "use strict"; function FolderNameController($scope) { - + var vm = this; - var element = angular.element($scope.model.currentStep.element); + var element = $($scope.model.currentStep.element); vm.error = false; - + vm.initNextStep = initNextStep; function initNextStep() { - if(element.val().toLowerCase() === "my images") { + if (element.val().toLowerCase() === "my images") { $scope.model.nextStep(); } else { vm.error = true; diff --git a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintromediasection/uploadimages/uploadimages.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintromediasection/uploadimages/uploadimages.controller.js index 0989076e95..08f0751510 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintromediasection/uploadimages/uploadimages.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintromediasection/uploadimages/uploadimages.controller.js @@ -2,12 +2,11 @@ "use strict"; function UploadImagesController($scope, editorState, mediaResource) { - + var vm = this; - var element = angular.element($scope.model.currentStep.element); vm.error = false; - + vm.initNextStep = initNextStep; function initNextStep() { @@ -23,7 +22,7 @@ var children = data; - if(children.items && children.items.length > 0) { + if (children.items && children.items.length > 0) { $scope.model.nextStep(); } else { vm.error = true; diff --git a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrorenderintemplate/templatetree/templatetree.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrorenderintemplate/templatetree/templatetree.controller.js index 3fdeb8d3c0..4edd9c9837 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrorenderintemplate/templatetree/templatetree.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/tours/umbintrorenderintemplate/templatetree/templatetree.controller.js @@ -2,13 +2,12 @@ "use strict"; function TemplatesTreeController($scope) { - - var vm = this; - var eventElement = angular.element($scope.model.currentStep.eventElement); - + + var eventElement = $($scope.model.currentStep.eventElement); + function onInit() { // check if tree is already open - if it is - go to next step - if(eventElement.hasClass("icon-navigation-down")) { + if (eventElement.hasClass("icon-navigation-down")) { $scope.model.nextStep(); } } diff --git a/src/Umbraco.Web.UI.Client/src/views/templates/edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/templates/edit.controller.js index 781ff731d2..2e3bc6eb80 100644 --- a/src/Umbraco.Web.UI.Client/src/views/templates/edit.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/templates/edit.controller.js @@ -188,7 +188,7 @@ // if this is a new template, bind to the blur event on the name if (create) { $timeout(function () { - var nameField = angular.element(document.querySelector('[data-element="editor-name-field"]')); + var nameField = $('[data-element="editor-name-field"]'); if (nameField) { nameField.on('blur', function (event) { if (event.target.value) { diff --git a/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js b/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js index 2888351783..c3bf5d0c20 100644 --- a/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js +++ b/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js @@ -686,10 +686,10 @@ angular.mock.dump = function (object) { var out; if (angular.isElement(object)) { - object = angular.element(object); - out = angular.element('
    '); + object = $(object); + out = $('
    '); angular.forEach(object, function (element) { - out.append(angular.element(element).clone()); + out.append($(element).clone()); }); out = out.html(); } else if (Utilities.isArray(object)) { @@ -1499,7 +1499,7 @@ angular.mock.$TimeoutDecorator = function ($delegate, $browser) { */ angular.mock.$RootElementProvider = function () { this.$get = function () { - return angular.element('
    '); + return $('
    '); } }; @@ -1710,7 +1710,7 @@ angular.mock.clearDataCache = function () { if (cache.hasOwnProperty(key)) { var handle = cache[key].handle; - handle && angular.element(handle.elem).unbind(); + handle && $(handle.elem).unbind(); delete cache[key]; } } From a5ff8a429b83fb6263617eb2396aa1e80d1e55a4 Mon Sep 17 00:00:00 2001 From: Jan Skovgaard Date: Tue, 14 Apr 2020 10:31:52 +0200 Subject: [PATCH 29/46] Replace angular.fromJson with JSON.parse (#7952) --- .../components/forms/umbrawmodel.directive.js | 4 +- .../common/mocks/resources/datatype.mocks.js | 194 +++++++++--------- .../src/common/services/util.service.js | 2 +- .../macropicker/macropicker.controller.js | 16 +- .../treepicker/treepicker.controller.js | 28 +-- .../test/lib/angular/angular-mocks.js | 2 +- 6 files changed, 123 insertions(+), 123 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbrawmodel.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbrawmodel.directive.js index ab92cfdb91..271a499b09 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbrawmodel.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/forms/umbrawmodel.directive.js @@ -39,7 +39,7 @@ angular.module("umbraco.directives") function stringToJson(text) { try { - return angular.fromJson(text); + return JSON.parse(text); } catch (err) { setInvalid(); return text; @@ -55,7 +55,7 @@ angular.module("umbraco.directives") function isValidJson(model) { var flag = true; try { - angular.fromJson(model); + JSON.parse(model) } catch (err) { flag = false; } diff --git a/src/Umbraco.Web.UI.Client/src/common/mocks/resources/datatype.mocks.js b/src/Umbraco.Web.UI.Client/src/common/mocks/resources/datatype.mocks.js index 054f0aa66d..e70f483bf4 100644 --- a/src/Umbraco.Web.UI.Client/src/common/mocks/resources/datatype.mocks.js +++ b/src/Umbraco.Web.UI.Client/src/common/mocks/resources/datatype.mocks.js @@ -1,113 +1,113 @@ angular.module('umbraco.mocks'). - factory('dataTypeMocks', ['$httpBackend', 'mocksUtils', function ($httpBackend, mocksUtils) { - 'use strict'; - - function returnById(status, data, headers) { + factory('dataTypeMocks', ['$httpBackend', 'mocksUtils', function ($httpBackend, mocksUtils) { + 'use strict'; - if (!mocksUtils.checkAuth()) { - return [401, null, null]; - } + function returnById(status, data, headers) { - var id = mocksUtils.getParameterByName(data, "id") || 1234; + if (!mocksUtils.checkAuth()) { + return [401, null, null]; + } - var selectedId = String.CreateGuid(); + var id = mocksUtils.getParameterByName(data, "id") || 1234; - var dataType = mocksUtils.getMockDataType(id, selectedId); - - return [200, dataType, null]; - } - - function returnEmpty(status, data, headers) { + var selectedId = String.CreateGuid(); - if (!mocksUtils.checkAuth()) { - return [401, null, null]; - } + var dataType = mocksUtils.getMockDataType(id, selectedId); - var response = returnById(200, "", null); - var node = response[1]; + return [200, dataType, null]; + } - node.name = ""; - node.selectedEditor = ""; - node.id = 0; - node.preValues = []; + function returnEmpty(status, data, headers) { - return response; - } - - function returnPreValues(status, data, headers) { + if (!mocksUtils.checkAuth()) { + return [401, null, null]; + } - if (!mocksUtils.checkAuth()) { - return [401, null, null]; - } + var response = returnById(200, "", null); + var node = response[1]; - var editorId = mocksUtils.getParameterByName(data, "editorId") || "83E9AD36-51A7-4440-8C07-8A5623AC6979"; + node.name = ""; + node.selectedEditor = ""; + node.id = 0; + node.preValues = []; - var preValues = [ - { - label: "Custom pre value 1 for editor " + editorId, - description: "Enter a value for this pre-value", - key: "myPreVal", - view: "requiredfield", - validation: [ - { - type: "Required" - } - ] - }, - { - label: "Custom pre value 2 for editor " + editorId, - description: "Enter a value for this pre-value", - key: "myPreVal", - view: "requiredfield", - validation: [ - { - type: "Required" - } - ] - } - ]; - return [200, preValues, null]; - } - - function returnSave(status, data, headers) { - if (!mocksUtils.checkAuth()) { - return [401, null, null]; - } + return response; + } - var postedData = angular.fromJson(headers); + function returnPreValues(status, data, headers) { - var dataType = mocksUtils.getMockDataType(postedData.id, postedData.selectedEditor); - dataType.notifications = [{ - header: "Saved", - message: "Data type saved", - type: 0 - }]; + if (!mocksUtils.checkAuth()) { + return [401, null, null]; + } - return [200, dataType, null]; - } + var editorId = mocksUtils.getParameterByName(data, "editorId") || "83E9AD36-51A7-4440-8C07-8A5623AC6979"; - return { - register: function() { - - $httpBackend - .whenPOST(mocksUtils.urlRegex('/umbraco/UmbracoApi/DataType/PostSave')) - .respond(returnSave); - - $httpBackend - .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/DataType/GetById')) - .respond(returnById); - - $httpBackend - .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/DataType/GetEmpty')) - .respond(returnEmpty); - - $httpBackend - .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/DataType/GetPreValues')) - .respond(returnPreValues); - }, - expectGetById: function() { - $httpBackend - .expectGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/DataType/GetById')); - } - }; - }]); + var preValues = [ + { + label: "Custom pre value 1 for editor " + editorId, + description: "Enter a value for this pre-value", + key: "myPreVal", + view: "requiredfield", + validation: [ + { + type: "Required" + } + ] + }, + { + label: "Custom pre value 2 for editor " + editorId, + description: "Enter a value for this pre-value", + key: "myPreVal", + view: "requiredfield", + validation: [ + { + type: "Required" + } + ] + } + ]; + return [200, preValues, null]; + } + + function returnSave(status, data, headers) { + if (!mocksUtils.checkAuth()) { + return [401, null, null]; + } + + var postedData = JSON.parse(headers); + + var dataType = mocksUtils.getMockDataType(postedData.id, postedData.selectedEditor); + dataType.notifications = [{ + header: "Saved", + message: "Data type saved", + type: 0 + }]; + + return [200, dataType, null]; + } + + return { + register: function () { + + $httpBackend + .whenPOST(mocksUtils.urlRegex('/umbraco/UmbracoApi/DataType/PostSave')) + .respond(returnSave); + + $httpBackend + .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/DataType/GetById')) + .respond(returnById); + + $httpBackend + .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/DataType/GetEmpty')) + .respond(returnEmpty); + + $httpBackend + .whenGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/DataType/GetPreValues')) + .respond(returnPreValues); + }, + expectGetById: function () { + $httpBackend + .expectGET(mocksUtils.urlRegex('/umbraco/UmbracoApi/DataType/GetById')); + } + }; + }]); diff --git a/src/Umbraco.Web.UI.Client/src/common/services/util.service.js b/src/Umbraco.Web.UI.Client/src/common/services/util.service.js index a7c98b9ac4..58ef342f44 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/util.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/util.service.js @@ -206,7 +206,7 @@ function umbSessionStorage($window) { return { get: function (key) { - return angular.fromJson(storage["umb_" + key]); + return JSON.parse(storage["umb_" + key]); }, set: function (key, value) { diff --git a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/macropicker/macropicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/macropicker/macropicker.controller.js index b4a8f36444..83c49d604f 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/macropicker/macropicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/macropicker/macropicker.controller.js @@ -8,9 +8,9 @@ function MacroPickerController($scope, entityResource, macroResource, umbPropEdi $scope.noMacroParams = false; function onInit() { - if(!$scope.model.title) { - localizationService.localize("defaultdialogs_selectMacro").then(function(value){ - $scope.model.title = value; + if (!$scope.model.title) { + localizationService.localize("defaultdialogs_selectMacro").then(function (value) { + $scope.model.title = value; }); } } @@ -26,8 +26,8 @@ function MacroPickerController($scope, entityResource, macroResource, umbPropEdi } }; - $scope.close = function() { - if($scope.model.close) { + $scope.close = function () { + if ($scope.model.close) { $scope.model.close(); } } @@ -51,7 +51,7 @@ function MacroPickerController($scope, entityResource, macroResource, umbPropEdi } } else { - + $scope.wizardStep = "paramSelect"; $scope.model.macroParams = data; @@ -71,7 +71,7 @@ function MacroPickerController($scope, entityResource, macroResource, umbPropEdi if (val.detectIsJson()) { try { //Parse it to json - prop.value = angular.fromJson(val); + prop.value = JSON.parse(val); } catch (e) { // not json @@ -110,7 +110,7 @@ function MacroPickerController($scope, entityResource, macroResource, umbPropEdi //if 'allowedMacros' is specified, we need to filter if (Utilities.isArray($scope.model.dialogData.allowedMacros) && $scope.model.dialogData.allowedMacros.length > 0) { - $scope.macros = _.filter(data, function(d) { + $scope.macros = _.filter(data, function (d) { return _.contains($scope.model.dialogData.allowedMacros, d.alias); }); } diff --git a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/treepicker/treepicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/treepicker/treepicker.controller.js index e2e16f111c..f6118e1523 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/treepicker/treepicker.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/treepicker/treepicker.controller.js @@ -76,7 +76,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", /** * Performs the initialization of this component */ - function onInit () { + function onInit() { if (vm.showLanguageSelector) { // load languages @@ -96,7 +96,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", if (vm.treeAlias === "content") { vm.entityType = "Document"; if (!$scope.model.title) { - localizationService.localize("defaultdialogs_selectContent").then(function(value){ + localizationService.localize("defaultdialogs_selectContent").then(function (value) { $scope.model.title = value; }); } @@ -104,7 +104,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", else if (vm.treeAlias === "documentTypes") { vm.entityType = "DocumentType"; if (!$scope.model.title) { - localizationService.localize("defaultdialogs_selectContentType").then(function(value){ + localizationService.localize("defaultdialogs_selectContentType").then(function (value) { $scope.model.title = value; }); } @@ -112,7 +112,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", else if (vm.treeAlias === "member" || vm.section === "member") { vm.entityType = "Member"; if (!$scope.model.title) { - localizationService.localize("defaultdialogs_selectMember").then(function(value) { + localizationService.localize("defaultdialogs_selectMember").then(function (value) { $scope.model.title = value; }); } @@ -120,7 +120,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", else if (vm.treeAlias === "memberTypes") { vm.entityType = "MemberType"; if (!$scope.model.title) { - localizationService.localize("defaultdialogs_selectMemberType").then(function(value){ + localizationService.localize("defaultdialogs_selectMemberType").then(function (value) { $scope.model.title = value; }); } @@ -128,7 +128,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", else if (vm.treeAlias === "media" || vm.section === "media") { vm.entityType = "Media"; if (!$scope.model.title) { - localizationService.localize("defaultdialogs_selectMedia").then(function(value){ + localizationService.localize("defaultdialogs_selectMedia").then(function (value) { $scope.model.title = value; }); } @@ -136,7 +136,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", else if (vm.treeAlias === "mediaTypes") { vm.entityType = "MediaType"; if (!$scope.model.title) { - localizationService.localize("defaultdialogs_selectMediaType").then(function(value){ + localizationService.localize("defaultdialogs_selectMediaType").then(function (value) { $scope.model.title = value; }); } @@ -189,7 +189,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", if ($scope.model.filter.startsWith("{")) { $scope.model.filterAdvanced = true; //convert to object - $scope.model.filter = angular.fromJson($scope.model.filter); + $scope.model.filter = JSON.parse($scope.model.filter); } } } @@ -218,7 +218,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", } var queryString = $.param(queryParams); //create the query string from the params object - + if (!queryString) { vm.customTreeParams = $scope.model.customTreeParams; } @@ -243,7 +243,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", $timeout(function () { //reload the tree with it's updated querystring args vm.dialogTreeApi.load(vm.section).then(function () { - + //create the list of promises var promises = []; for (var i = 0; i < expandedPaths.length; i++) { @@ -258,7 +258,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", function toggleLanguageSelector() { vm.languageSelectorIsOpen = !vm.languageSelectorIsOpen; }; - + function nodeExpandedHandler(args) { //store the reference to the expanded node path @@ -673,17 +673,17 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", } function submit(model) { - if($scope.model.submit) { + if ($scope.model.submit) { $scope.model.submit(model); } } function close() { - if($scope.model.close) { + if ($scope.model.close) { $scope.model.close(); } } - + //initialize onInit(); diff --git a/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js b/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js index c3bf5d0c20..31310e1c46 100644 --- a/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js +++ b/src/Umbraco.Web.UI.Client/test/lib/angular/angular-mocks.js @@ -1572,7 +1572,7 @@ angular.module('ngMockE2E', ['ng']).config(function ($provide) { * * // adds a new phone to the phones array * $httpBackend.whenPOST('/phones').respond(function(method, url, data) { - * phones.push(angular.fromJSON(data)); + * phones.push(JSON.parse(data)); * }); * $httpBackend.whenGET(/^\/templates\//).passThrough(); * //... From d582460f361d618e693188f7aa39ec727f7212cd Mon Sep 17 00:00:00 2001 From: Jan Skovgaard Date: Tue, 14 Apr 2020 10:45:25 +0200 Subject: [PATCH 30/46] Add backdrop to "user overlay" (#7956) --- .../components/application/umbappheader.directive.js | 4 +++- src/Umbraco.Web.UI.Client/src/less/components/overlays.less | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js index 2b9a96cf55..8efaf0c024 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/application/umbappheader.directive.js @@ -1,7 +1,7 @@ (function () { "use strict"; - function AppHeaderDirective(eventsService, appState, userService, focusService) { + function AppHeaderDirective(eventsService, appState, userService, focusService, backdropService) { function link(scope, el, attr, ctrl) { @@ -72,12 +72,14 @@ scope.avatarClick = function () { if (!scope.userDialog) { + backdropService.open(); scope.userDialog = { view: "user", show: true, close: function (oldModel) { scope.userDialog.show = false; scope.userDialog = null; + backdropService.close(); } }; } else { diff --git a/src/Umbraco.Web.UI.Client/src/less/components/overlays.less b/src/Umbraco.Web.UI.Client/src/less/components/overlays.less index eb8740b385..f4402dec7b 100644 --- a/src/Umbraco.Web.UI.Client/src/less/components/overlays.less +++ b/src/Umbraco.Web.UI.Client/src/less/components/overlays.less @@ -2,7 +2,7 @@ position: fixed; overflow: hidden; background: @white; - z-index: @zindexUmbOverlay; + z-index: 7501; animation: fadeIn 0.2s; box-shadow: 0 10px 50px rgba(0,0,0,0.1), 0 6px 20px rgba(0,0,0,0.16); text-align: left; From b5e866aeba49053db0bb0b5566bdbb71e65e4483 Mon Sep 17 00:00:00 2001 From: Joe Glombek Date: Tue, 14 Apr 2020 10:33:30 +0100 Subject: [PATCH 31/46] Append "active" to currently selected section for screen readers (#7946) --- .../src/views/components/application/umb-sections.html | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/views/components/application/umb-sections.html b/src/Umbraco.Web.UI.Client/src/views/components/application/umb-sections.html index d435c6ead7..f43353ede9 100644 --- a/src/Umbraco.Web.UI.Client/src/views/components/application/umb-sections.html +++ b/src/Umbraco.Web.UI.Client/src/views/components/application/umb-sections.html @@ -6,13 +6,15 @@ + prevent-default + ng-attr-aria-current="{{section.alias == currentSection ? 'page' : undefined}}" + aria-label="{{section.name + (section.alias == currentSection ? ' (active)' : '')}}"> {{section.name}}
  • - + ••• @@ -21,7 +23,9 @@ + prevent-default + ng-attr-aria-current="{{section.alias == currentSection ? 'page' : undefined}}" + aria-label="{{section.name + (section.alias == currentSection ? ' (active)' : '')}}"> {{section.name}}
  • From 627243c84cc3381b3062f56e367926400da137d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niels=20Lyngs=C3=B8?= Date: Wed, 15 Apr 2020 16:43:59 +0200 Subject: [PATCH 32/46] show message when user has no start nodes --- .../src/common/services/events.service.js | 2 -- src/Umbraco.Web.UI.Client/src/init.js | 1 + src/Umbraco.Web.UI.Client/src/main.controller.js | 11 ++++++----- .../src/views/common/login.controller.js | 7 ------- .../src/views/components/application/umb-login.html | 3 ++- 5 files changed, 9 insertions(+), 15 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/services/events.service.js b/src/Umbraco.Web.UI.Client/src/common/services/events.service.js index f90936f371..965ac3d635 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/events.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/events.service.js @@ -18,8 +18,6 @@ function eventsService($q, $rootScope) { /** raise an event with a given name */ emit: function (name, args) { - console.log(`Emitting event: ${name}`, args); - //there are no listeners if (!$rootScope.$$listeners[name]) { return; diff --git a/src/Umbraco.Web.UI.Client/src/init.js b/src/Umbraco.Web.UI.Client/src/init.js index f46b24a546..c5a20cd890 100644 --- a/src/Umbraco.Web.UI.Client/src/init.js +++ b/src/Umbraco.Web.UI.Client/src/init.js @@ -23,6 +23,7 @@ app.run(['$rootScope', '$route', '$location', 'urlHelper', 'navigationService', if(user.startContentIds.length === 0 && user.startMediaIds.length === 0){ const args = { isTimedOut: true, noAccess: true }; eventsService.emit("app.notAuthenticated", args); + return; } assetsService._loadInitAssets().then(function () { diff --git a/src/Umbraco.Web.UI.Client/src/main.controller.js b/src/Umbraco.Web.UI.Client/src/main.controller.js index 4fac328f70..54d897ca74 100644 --- a/src/Umbraco.Web.UI.Client/src/main.controller.js +++ b/src/Umbraco.Web.UI.Client/src/main.controller.js @@ -56,9 +56,11 @@ function MainController($scope, $location, appState, treeService, notificationsS appState.setSearchState("show", false); }; - $scope.showLoginScreen = function(isTimedOut) { - console.log('SHOW ME THE LOGIN SCREEN'); + $scope.showLoginScreen = function(isTimedOut, noAccess) { + console.log('SHOW ME THE LOGIN SCREEN', isTimedOut, noAccess); + $scope.login.isTimedOut = isTimedOut; + $scope.login.noAccess = noAccess; $scope.login.show = true; }; @@ -73,10 +75,9 @@ function MainController($scope, $location, appState, treeService, notificationsS $scope.authenticated = null; $scope.user = null; const isTimedOut = data && data.isTimedOut ? true : false; + const noAccess = data && data.noAccess ? true : false; - console.log('Log me out & show login screen?', isTimedOut); - - $scope.showLoginScreen(isTimedOut); + $scope.showLoginScreen(isTimedOut, noAccess); // Remove the localstorage items for tours shown // Means that when next logged in they can be re-shown if not already dismissed etc diff --git a/src/Umbraco.Web.UI.Client/src/views/common/login.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/login.controller.js index 713af9661b..86132fe8f3 100644 --- a/src/Umbraco.Web.UI.Client/src/views/common/login.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/common/login.controller.js @@ -17,13 +17,6 @@ angular.module('umbraco').controller("Umbraco.LoginController", function (events $location.url(path); }); - eventsService.on("app.notAuthenticated", function(evt, data){ - console.log('not authenticated event back', data); - if(data.noAccess){ - alert('NO NO NO YOU HAVE NO START NODES'); - } - }); - $scope.$on('$destroy', function () { eventsService.unsubscribe(evtOn); }); diff --git a/src/Umbraco.Web.UI.Client/src/views/components/application/umb-login.html b/src/Umbraco.Web.UI.Client/src/views/components/application/umb-login.html index 2e81395643..c26e3daa8a 100644 --- a/src/Umbraco.Web.UI.Client/src/views/components/application/umb-login.html +++ b/src/Umbraco.Web.UI.Client/src/views/components/application/umb-login.html @@ -120,7 +120,8 @@

    - Log in below. + Session timed out. + User has no start-nodes.

    From b870ca7fcf0d8b10c35e9b3e8f7115136c762acf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niels=20Lyngs=C3=B8?= Date: Wed, 15 Apr 2020 17:46:12 +0200 Subject: [PATCH 33/46] revert --- src/Umbraco.Web.UI.Client/src/init.js | 8 -------- .../src/views/components/application/umb-login.html | 3 +-- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/init.js b/src/Umbraco.Web.UI.Client/src/init.js index c5a20cd890..d5c5166d21 100644 --- a/src/Umbraco.Web.UI.Client/src/init.js +++ b/src/Umbraco.Web.UI.Client/src/init.js @@ -18,14 +18,6 @@ app.run(['$rootScope', '$route', '$location', 'urlHelper', 'navigationService', /** Listens for authentication and checks if our required assets are loaded, if/once they are we'll broadcast a ready event */ eventsService.on("app.authenticated", function (evt, data) { - // Lets check if the auth'd user has a start node set (befor trying to make the app ready) - const user = data.user; - if(user.startContentIds.length === 0 && user.startMediaIds.length === 0){ - const args = { isTimedOut: true, noAccess: true }; - eventsService.emit("app.notAuthenticated", args); - return; - } - assetsService._loadInitAssets().then(function () { appReady(data); diff --git a/src/Umbraco.Web.UI.Client/src/views/components/application/umb-login.html b/src/Umbraco.Web.UI.Client/src/views/components/application/umb-login.html index c26e3daa8a..2e81395643 100644 --- a/src/Umbraco.Web.UI.Client/src/views/components/application/umb-login.html +++ b/src/Umbraco.Web.UI.Client/src/views/components/application/umb-login.html @@ -120,8 +120,7 @@

    - Session timed out. - User has no start-nodes. + Log in below.

    From 61cb9208085e00b4360e0590f8239c6abd54ef42 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niels=20Lyngs=C3=B8?= Date: Wed, 15 Apr 2020 17:46:28 +0200 Subject: [PATCH 34/46] show message if user has no start-nodes --- .../src/common/services/user.service.js | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/services/user.service.js b/src/Umbraco.Web.UI.Client/src/common/services/user.service.js index afd7b606e7..45a819317c 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/user.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/user.service.js @@ -185,7 +185,19 @@ angular.module('umbraco.services') authenticate: function (login, password) { return authResource.performLogin(login, password) - .then(this.setAuthenticationSuccessful); + .then(function(data) { + + // Check if user has a start node set. + if(data.startContentIds.length === 0 && data.startMediaIds.length === 0){ + var errorMsg = "User has no start-nodes"; + var result = { errorMsg: errorMsg, user: data, authenticated: false, lastUserId: lastUserId, loginType: "credentials" };; + eventsService.emit("app.notAuthenticated", result); + throw result; + } + + return this.setAuthenticationSuccessful(data); + + }); }, setAuthenticationSuccessful: function (data) { From 0b4b28851e6ab3b82285c04ef07701f55dbfd9c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niels=20Lyngs=C3=B8?= Date: Wed, 15 Apr 2020 17:47:32 +0200 Subject: [PATCH 35/46] revert --- src/Umbraco.Web.UI.Client/src/main.controller.js | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/main.controller.js b/src/Umbraco.Web.UI.Client/src/main.controller.js index 54d897ca74..81eadf150f 100644 --- a/src/Umbraco.Web.UI.Client/src/main.controller.js +++ b/src/Umbraco.Web.UI.Client/src/main.controller.js @@ -56,11 +56,8 @@ function MainController($scope, $location, appState, treeService, notificationsS appState.setSearchState("show", false); }; - $scope.showLoginScreen = function(isTimedOut, noAccess) { - console.log('SHOW ME THE LOGIN SCREEN', isTimedOut, noAccess); - + $scope.showLoginScreen = function(isTimedOut) { $scope.login.isTimedOut = isTimedOut; - $scope.login.noAccess = noAccess; $scope.login.show = true; }; @@ -75,9 +72,8 @@ function MainController($scope, $location, appState, treeService, notificationsS $scope.authenticated = null; $scope.user = null; const isTimedOut = data && data.isTimedOut ? true : false; - const noAccess = data && data.noAccess ? true : false; - $scope.showLoginScreen(isTimedOut, noAccess); + $scope.showLoginScreen(isTimedOut); // Remove the localstorage items for tours shown // Means that when next logged in they can be re-shown if not already dismissed etc From 3f22d1c452db197250336be47f1a32eee850ec9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Niels=20Lyngs=C3=B8?= Date: Wed, 15 Apr 2020 17:57:38 +0200 Subject: [PATCH 36/46] correcting promise --- .../src/common/services/user.service.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Umbraco.Web.UI.Client/src/common/services/user.service.js b/src/Umbraco.Web.UI.Client/src/common/services/user.service.js index 45a819317c..5b4e516289 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/user.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/user.service.js @@ -190,14 +190,14 @@ angular.module('umbraco.services') // Check if user has a start node set. if(data.startContentIds.length === 0 && data.startMediaIds.length === 0){ var errorMsg = "User has no start-nodes"; - var result = { errorMsg: errorMsg, user: data, authenticated: false, lastUserId: lastUserId, loginType: "credentials" };; + var result = { errorMsg: errorMsg, user: data, authenticated: false, lastUserId: lastUserId, loginType: "credentials" }; eventsService.emit("app.notAuthenticated", result); throw result; } - return this.setAuthenticationSuccessful(data); + return data; - }); + }).then(this.setAuthenticationSuccessful); }, setAuthenticationSuccessful: function (data) { From b30db05cc7a1b69c7e9d9990ea2677f18473bae3 Mon Sep 17 00:00:00 2001 From: Shannon Deminick Date: Thu, 16 Apr 2020 04:51:13 +1000 Subject: [PATCH 37/46] Nucache NullReferenceException when copying (#7961) --- .../PublishedContent/NuCacheChildrenTests.cs | 106 +++++++++++++----- .../PublishedCache/NuCache/ContentStore.cs | 6 +- 2 files changed, 82 insertions(+), 30 deletions(-) diff --git a/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs b/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs index 4221968429..c124582730 100644 --- a/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs +++ b/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs @@ -44,7 +44,7 @@ namespace Umbraco.Tests.PublishedContent _snapshotService?.Dispose(); } - private void Init(IEnumerable kits) + private void Init(Func> kits) { Current.Reset(); @@ -133,7 +133,7 @@ namespace Umbraco.Tests.PublishedContent _snapshotAccessor = new TestPublishedSnapshotAccessor(); // create a data source for NuCache - _source = new TestDataSource(kits); + _source = new TestDataSource(kits()); // at last, create the complete NuCache snapshot service! var options = new PublishedSnapshotServiceOptions { IgnoreLocalDb = true }; @@ -371,7 +371,7 @@ namespace Umbraco.Tests.PublishedContent [Test] public void EmptyTest() { - Init(Enumerable.Empty()); + Init(() => Enumerable.Empty()); var snapshot = _snapshotService.CreatePublishedSnapshot(previewToken: null); _snapshotAccessor.PublishedSnapshot = snapshot; @@ -383,7 +383,7 @@ namespace Umbraco.Tests.PublishedContent [Test] public void ChildrenTest() { - Init(GetInvariantKits()); + Init(GetInvariantKits); var snapshot = _snapshotService.CreatePublishedSnapshot(previewToken: null); _snapshotAccessor.PublishedSnapshot = snapshot; @@ -410,7 +410,7 @@ namespace Umbraco.Tests.PublishedContent [Test] public void ParentTest() { - Init(GetInvariantKits()); + Init(GetInvariantKits); var snapshot = _snapshotService.CreatePublishedSnapshot(previewToken: null); _snapshotAccessor.PublishedSnapshot = snapshot; @@ -436,7 +436,7 @@ namespace Umbraco.Tests.PublishedContent [Test] public void MoveToRootTest() { - Init(GetInvariantKits()); + Init(GetInvariantKits); // get snapshot var snapshot = _snapshotService.CreatePublishedSnapshot(previewToken: null); @@ -478,7 +478,7 @@ namespace Umbraco.Tests.PublishedContent [Test] public void MoveFromRootTest() { - Init(GetInvariantKits()); + Init(GetInvariantKits); // get snapshot var snapshot = _snapshotService.CreatePublishedSnapshot(previewToken: null); @@ -520,7 +520,7 @@ namespace Umbraco.Tests.PublishedContent [Test] public void ReOrderTest() { - Init(GetInvariantKits()); + Init(GetInvariantKits); // get snapshot var snapshot = _snapshotService.CreatePublishedSnapshot(previewToken: null); @@ -595,7 +595,7 @@ namespace Umbraco.Tests.PublishedContent [Test] public void MoveTest() { - Init(GetInvariantKits()); + Init(GetInvariantKits); // get snapshot var snapshot = _snapshotService.CreatePublishedSnapshot(previewToken: null); @@ -696,11 +696,61 @@ namespace Umbraco.Tests.PublishedContent Assert.AreEqual(1, snapshot.Content.GetById(7).Parent?.Id); } + [Test] + public void Clear_Branch_Locked() + { + // This test replicates an issue we saw here https://github.com/umbraco/Umbraco-CMS/pull/7907#issuecomment-610259393 + // The data was sent to me and this replicates it's structure + + var paths = new Dictionary { { -1, "-1" } }; + + Init(() => new List + { + CreateInvariantKit(1, -1, 1, paths), // first level + CreateInvariantKit(2, 1, 1, paths), // second level + CreateInvariantKit(3, 2, 1, paths), // third level + + CreateInvariantKit(4, 3, 1, paths), // fourth level (we'll copy this one to the same level) + + CreateInvariantKit(5, 4, 1, paths), // 6th level + + CreateInvariantKit(6, 5, 2, paths), // 7th level + CreateInvariantKit(7, 5, 3, paths), + CreateInvariantKit(8, 5, 4, paths), + CreateInvariantKit(9, 5, 5, paths), + CreateInvariantKit(10, 5, 6, paths) + }); + + // get snapshot + var snapshot = _snapshotService.CreatePublishedSnapshot(previewToken: null); + _snapshotAccessor.PublishedSnapshot = snapshot; + + var snapshotService = (PublishedSnapshotService)_snapshotService; + var contentStore = snapshotService.GetContentStore(); + //This will set a flag to force creating a new Gen next time the store is locked (i.e. In Notify) + contentStore.CreateSnapshot(); + + // notify - which ensures there are 2 generations in the cache meaning each LinkedNode has a Next value. + _snapshotService.Notify(new[] + { + new ContentCacheRefresher.JsonPayload(4, Guid.Empty, TreeChangeTypes.RefreshBranch) + }, out _, out _); + + // refresh the branch again, this used to show the issue where a null ref exception would occur + // because in the ClearBranchLocked logic, when SetValueLocked was called within a recursive call + // to a child, we null out the .Value of the LinkedNode within the while loop because we didn't capture + // this value before recursing. + Assert.DoesNotThrow(() => + _snapshotService.Notify(new[] + { + new ContentCacheRefresher.JsonPayload(4, Guid.Empty, TreeChangeTypes.RefreshBranch) + }, out _, out _)); + } + [Test] public void NestedVariationChildrenTest() { - var mixedKits = GetNestedVariantKits(); - Init(mixedKits); + Init(GetNestedVariantKits); var snapshot = _snapshotService.CreatePublishedSnapshot(previewToken: null); _snapshotAccessor.PublishedSnapshot = snapshot; @@ -789,7 +839,7 @@ namespace Umbraco.Tests.PublishedContent [Test] public void VariantChildrenTest() { - Init(GetVariantKits()); + Init(GetVariantKits); var snapshot = _snapshotService.CreatePublishedSnapshot(previewToken: null); _snapshotAccessor.PublishedSnapshot = snapshot; @@ -861,7 +911,7 @@ namespace Umbraco.Tests.PublishedContent [Test] public void RemoveTest() { - Init(GetInvariantKits()); + Init(GetInvariantKits); var snapshot = _snapshotService.CreatePublishedSnapshot(previewToken: null); _snapshotAccessor.PublishedSnapshot = snapshot; @@ -910,7 +960,7 @@ namespace Umbraco.Tests.PublishedContent [Test] public void UpdateTest() { - Init(GetInvariantKits()); + Init(GetInvariantKits); var snapshot = _snapshotService.CreatePublishedSnapshot(previewToken: null); _snapshotAccessor.PublishedSnapshot = snapshot; @@ -957,13 +1007,13 @@ namespace Umbraco.Tests.PublishedContent documents = snapshot.Content.GetById(2).Children().ToArray(); AssertDocuments(documents, "N9", "N8", "N7"); - + } [Test] public void AtRootTest() { - Init(GetVariantWithDraftKits()); + Init(GetVariantWithDraftKits); var snapshot = _snapshotService.CreatePublishedSnapshot(previewToken: null); _snapshotAccessor.PublishedSnapshot = snapshot; @@ -992,7 +1042,7 @@ namespace Umbraco.Tests.PublishedContent yield return CreateInvariantKit(2, 1, 1, paths); } - Init(GetKits()); + Init(GetKits); var snapshotService = (PublishedSnapshotService)_snapshotService; var contentStore = snapshotService.GetContentStore(); @@ -1031,7 +1081,7 @@ namespace Umbraco.Tests.PublishedContent yield return CreateInvariantKit(4, 1, 3, paths); } - Init(GetKits()); + Init(GetKits); var snapshotService = (PublishedSnapshotService)_snapshotService; var contentStore = snapshotService.GetContentStore(); @@ -1111,7 +1161,7 @@ namespace Umbraco.Tests.PublishedContent yield return CreateInvariantKit(40, 1, 3, paths); } - Init(GetKits()); + Init(GetKits); var snapshotService = (PublishedSnapshotService)_snapshotService; var contentStore = snapshotService.GetContentStore(); @@ -1130,7 +1180,7 @@ namespace Umbraco.Tests.PublishedContent _snapshotService.Notify(new[] { - new ContentCacheRefresher.JsonPayload(1, Guid.Empty, TreeChangeTypes.RefreshNode) + new ContentCacheRefresher.JsonPayload(1, Guid.Empty, TreeChangeTypes.RefreshNode) }, out _, out _); Assert.AreEqual(2, contentStore.Test.LiveGen); @@ -1178,12 +1228,12 @@ namespace Umbraco.Tests.PublishedContent //children of 1 yield return CreateInvariantKit(20, 1, 1, paths); - yield return CreateInvariantKit(30, 1, 2, paths); + yield return CreateInvariantKit(30, 1, 2, paths); yield return CreateInvariantKit(40, 1, 3, paths); } //init with all published - Init(GetKits()); + Init(GetKits); var snapshotService = (PublishedSnapshotService)_snapshotService; var contentStore = snapshotService.GetContentStore(); @@ -1200,7 +1250,7 @@ namespace Umbraco.Tests.PublishedContent //Change the root publish flag var kit = rootKit.Clone(); kit.DraftData = published ? null : kit.PublishedData; - kit.PublishedData = published? kit.PublishedData : null; + kit.PublishedData = published ? kit.PublishedData : null; _source.Kits[1] = kit; _snapshotService.Notify(new[] @@ -1215,12 +1265,12 @@ namespace Umbraco.Tests.PublishedContent var (gen, contentNode) = contentStore.Test.GetValues(1)[0]; Assert.AreEqual(assertGen, gen); //even when unpublishing/re-publishing/etc... the linked list is always maintained - AssertLinkedNode(contentNode, 100, 2, 3, 20, 40); + AssertLinkedNode(contentNode, 100, 2, 3, 20, 40); } //unpublish the root ChangePublishFlagOfRoot(false, 2, TreeChangeTypes.RefreshBranch); - + //publish the root (since it's not published, it will cause a RefreshBranch) ChangePublishFlagOfRoot(true, 3, TreeChangeTypes.RefreshBranch); @@ -1253,7 +1303,7 @@ namespace Umbraco.Tests.PublishedContent yield return CreateInvariantKit(4, 1, 3, paths); } - Init(GetKits()); + Init(GetKits); var snapshotService = (PublishedSnapshotService)_snapshotService; var contentStore = snapshotService.GetContentStore(); @@ -1313,9 +1363,9 @@ namespace Umbraco.Tests.PublishedContent public void MultipleCacheIteration() { //see https://github.com/umbraco/Umbraco-CMS/issues/7798 - this.Init(this.GetInvariantKits()); + Init(GetInvariantKits); var snapshot = this._snapshotService.CreatePublishedSnapshot(previewToken: null); - this._snapshotAccessor.PublishedSnapshot = snapshot; + _snapshotAccessor.PublishedSnapshot = snapshot; var items = snapshot.Content.GetByXPath("/root/itype"); Assert.AreEqual(items.Count(), items.Count()); diff --git a/src/Umbraco.Web/PublishedCache/NuCache/ContentStore.cs b/src/Umbraco.Web/PublishedCache/NuCache/ContentStore.cs index f92d8adebb..34d21497a2 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/ContentStore.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/ContentStore.cs @@ -873,9 +873,11 @@ namespace Umbraco.Web.PublishedCache.NuCache var id = content.FirstChildContentId; while (id > 0) { + // get the required link node, this ensures that both `link` and `link.Value` are not null var link = GetRequiredLinkedNode(id, "child", null); - ClearBranchLocked(link.Value); - id = link.Value.NextSiblingContentId; + var linkValue = link.Value; // capture local since clearing in recurse can clear it + ClearBranchLocked(linkValue); // recurse + id = linkValue.NextSiblingContentId; } } From 5d8bfcea979d1582af1dc3f7ed973107b16368e5 Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 17 Apr 2020 00:47:26 +1000 Subject: [PATCH 38/46] Ensure when we are loading in ALL data that we page over the data as to not cause an SQL timeout --- .../Persistence/NPocoDatabaseExtensions.cs | 42 +++++++++++++ .../NuCache/DataSource/DatabaseDataSource.cs | 63 ++++++++++++------- 2 files changed, 82 insertions(+), 23 deletions(-) diff --git a/src/Umbraco.Core/Persistence/NPocoDatabaseExtensions.cs b/src/Umbraco.Core/Persistence/NPocoDatabaseExtensions.cs index acfa51f895..152dcbe6d3 100644 --- a/src/Umbraco.Core/Persistence/NPocoDatabaseExtensions.cs +++ b/src/Umbraco.Core/Persistence/NPocoDatabaseExtensions.cs @@ -18,6 +18,48 @@ namespace Umbraco.Core.Persistence ///
public static partial class NPocoDatabaseExtensions { + /// + /// Iterates over the result of a paged data set with a db reader + /// + /// + /// + /// + /// The number of rows to load per page + /// + /// + /// + /// + /// NPoco's normal Page returns a List{T} but sometimes we don't want all that in memory and instead want to + /// iterate over each row with a reader using Query vs Fetch. + /// + internal static IEnumerable QueryPaged(this IDatabase database, long pageSize, Sql sql) + { + var sqlString = sql.SQL; + var sqlArgs = sql.Arguments; + + int? itemCount = null; + long pageIndex = 0; + do + { + // Get the paged queries + database.BuildPageQueries(pageIndex * pageSize, pageSize, sqlString, ref sqlArgs, out var sqlCount, out var sqlPage); + + // get the item count once + if (itemCount == null) + { + itemCount = database.ExecuteScalar(sqlCount, sqlArgs); + } + pageIndex++; + + // iterate over rows without allocating all items to memory (Query vs Fetch) + foreach (var row in database.Query(sqlPage, sqlArgs)) + { + yield return row; + } + + } while ((pageIndex * pageSize) < itemCount); + } + // NOTE // // proper way to do it with TSQL and SQLCE diff --git a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/DatabaseDataSource.cs b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/DatabaseDataSource.cs index 19aab7ea65..694dac04df 100644 --- a/src/Umbraco.Web/PublishedCache/NuCache/DataSource/DatabaseDataSource.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/DataSource/DatabaseDataSource.cs @@ -20,6 +20,8 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource // provides efficient database access for NuCache internal class DatabaseDataSource : IDataSource { + private const int PageSize = 500; + // we want arrays, we want them all loaded, not an enumerable private Sql ContentSourcesSelect(IScope scope, Func, Sql> joins = null) @@ -79,33 +81,43 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource .Where(x => x.NodeObjectType == Constants.ObjectTypes.Document && !x.Trashed) .OrderBy(x => x.Level, x => x.ParentId, x => x.SortOrder); - return scope.Database.Query(sql).Select(CreateContentNodeKit); + // We need to page here. We don't want to iterate over every single row in one connection cuz this can cause an SQL Timeout. + // We also want to read with a db reader and not load everything into memory, QueryPaged lets us do that. + + foreach (var row in scope.Database.QueryPaged(PageSize, sql)) + yield return CreateContentNodeKit(row); } public IEnumerable GetBranchContentSources(IScope scope, int id) { var syntax = scope.SqlContext.SqlSyntax; - var sql = ContentSourcesSelect(scope, s => s + var sql = ContentSourcesSelect(scope, + s => s.InnerJoin("x").On((left, right) => left.NodeId == right.NodeId || SqlText(left.Path, right.Path, (lp, rp) => $"({lp} LIKE {syntax.GetConcat(rp, "',%'")})"), aliasRight: "x")) + .Where(x => x.NodeObjectType == Constants.ObjectTypes.Document && !x.Trashed) + .Where(x => x.NodeId == id, "x") + .OrderBy(x => x.Level, x => x.ParentId, x => x.SortOrder); - .InnerJoin("x").On((left, right) => left.NodeId == right.NodeId || SqlText(left.Path, right.Path, (lp, rp) => $"({lp} LIKE {syntax.GetConcat(rp, "',%'")})"), aliasRight: "x")) + // We need to page here. We don't want to iterate over every single row in one connection cuz this can cause an SQL Timeout. + // We also want to read with a db reader and not load everything into memory, QueryPaged lets us do that. - .Where(x => x.NodeObjectType == Constants.ObjectTypes.Document && !x.Trashed) - .Where(x => x.NodeId == id, "x") - .OrderBy(x => x.Level, x => x.ParentId, x => x.SortOrder); - - return scope.Database.Query(sql).Select(CreateContentNodeKit); + foreach (var row in scope.Database.QueryPaged(PageSize, sql)) + yield return CreateContentNodeKit(row); } public IEnumerable GetTypeContentSources(IScope scope, IEnumerable ids) { - if (!ids.Any()) return Enumerable.Empty(); + if (!ids.Any()) yield break; var sql = ContentSourcesSelect(scope) .Where(x => x.NodeObjectType == Constants.ObjectTypes.Document && !x.Trashed) .WhereIn(x => x.ContentTypeId, ids) .OrderBy(x => x.Level, x => x.ParentId, x => x.SortOrder); - return scope.Database.Query(sql).Select(CreateContentNodeKit); + // We need to page here. We don't want to iterate over every single row in one connection cuz this can cause an SQL Timeout. + // We also want to read with a db reader and not load everything into memory, QueryPaged lets us do that. + + foreach (var row in scope.Database.QueryPaged(PageSize, sql)) + yield return CreateContentNodeKit(row); } private Sql MediaSourcesSelect(IScope scope, Func, Sql> joins = null) @@ -116,11 +128,8 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource x => Alias(x.Level, "Level"), x => Alias(x.Path, "Path"), x => Alias(x.SortOrder, "SortOrder"), x => Alias(x.ParentId, "ParentId"), x => Alias(x.CreateDate, "CreateDate"), x => Alias(x.UserId, "CreatorId")) .AndSelect(x => Alias(x.ContentTypeId, "ContentTypeId")) - .AndSelect(x => Alias(x.Id, "VersionId"), x => Alias(x.Text, "EditName"), x => Alias(x.VersionDate, "EditVersionDate"), x => Alias(x.UserId, "EditWriterId")) - .AndSelect("nuEdit", x => Alias(x.Data, "EditData")) - .From(); if (joins != null) @@ -128,9 +137,7 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource sql = sql .InnerJoin().On((left, right) => left.NodeId == right.NodeId) - .InnerJoin().On((left, right) => left.NodeId == right.NodeId && right.Current) - .LeftJoin("nuEdit").On((left, right) => left.NodeId == right.NodeId && !right.Published, aliasRight: "nuEdit"); return sql; @@ -152,33 +159,43 @@ namespace Umbraco.Web.PublishedCache.NuCache.DataSource .Where(x => x.NodeObjectType == Constants.ObjectTypes.Media && !x.Trashed) .OrderBy(x => x.Level, x => x.ParentId, x => x.SortOrder); - return scope.Database.Query(sql).Select(CreateMediaNodeKit); + // We need to page here. We don't want to iterate over every single row in one connection cuz this can cause an SQL Timeout. + // We also want to read with a db reader and not load everything into memory, QueryPaged lets us do that. + + foreach (var row in scope.Database.QueryPaged(PageSize, sql)) + yield return CreateMediaNodeKit(row); } public IEnumerable GetBranchMediaSources(IScope scope, int id) { var syntax = scope.SqlContext.SqlSyntax; - var sql = MediaSourcesSelect(scope, s => s - - .InnerJoin("x").On((left, right) => left.NodeId == right.NodeId || SqlText(left.Path, right.Path, (lp, rp) => $"({lp} LIKE {syntax.GetConcat(rp, "',%'")})"), aliasRight: "x")) - + var sql = MediaSourcesSelect(scope, + s => s.InnerJoin("x").On((left, right) => left.NodeId == right.NodeId || SqlText(left.Path, right.Path, (lp, rp) => $"({lp} LIKE {syntax.GetConcat(rp, "',%'")})"), aliasRight: "x")) .Where(x => x.NodeObjectType == Constants.ObjectTypes.Media && !x.Trashed) .Where(x => x.NodeId == id, "x") .OrderBy(x => x.Level, x => x.ParentId, x => x.SortOrder); - return scope.Database.Query(sql).Select(CreateMediaNodeKit); + // We need to page here. We don't want to iterate over every single row in one connection cuz this can cause an SQL Timeout. + // We also want to read with a db reader and not load everything into memory, QueryPaged lets us do that. + + foreach (var row in scope.Database.QueryPaged(PageSize, sql)) + yield return CreateMediaNodeKit(row); } public IEnumerable GetTypeMediaSources(IScope scope, IEnumerable ids) { - if (!ids.Any()) return Enumerable.Empty(); + if (!ids.Any()) yield break; var sql = MediaSourcesSelect(scope) .Where(x => x.NodeObjectType == Constants.ObjectTypes.Media && !x.Trashed) .WhereIn(x => x.ContentTypeId, ids) .OrderBy(x => x.Level, x => x.ParentId, x => x.SortOrder); - return scope.Database.Query(sql).Select(CreateMediaNodeKit); + // We need to page here. We don't want to iterate over every single row in one connection cuz this can cause an SQL Timeout. + // We also want to read with a db reader and not load everything into memory, QueryPaged lets us do that. + + foreach (var row in scope.Database.QueryPaged(PageSize, sql)) + yield return CreateMediaNodeKit(row); } private static ContentNodeKit CreateContentNodeKit(ContentSourceDto dto) From 2509dc3749dac1ce44071f59a0ea2a8a21f27024 Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 17 Apr 2020 14:46:45 +1000 Subject: [PATCH 39/46] runs in parallel the call to rebuild the in-memory cache from the db sources when in pure live mode and content types change --- .../NuCache/PublishedSnapshotService.cs | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs index a33d9ee427..4e630cad3d 100755 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs @@ -5,6 +5,7 @@ using System.Globalization; using System.IO; using System.Linq; using System.Threading; +using System.Threading.Tasks; using CSharpTest.Net.Collections; using Newtonsoft.Json; using Umbraco.Core; @@ -866,12 +867,24 @@ namespace Umbraco.Web.PublishedCache.NuCache //into a new DLL for the application which includes both content types and media types. //Since the models in the cache are based on these actual classes, all of the objects in the cache need to be updated //to use the newest version of the class. - using (_contentStore.GetScopedWriteLock(_scopeProvider)) - using (_mediaStore.GetScopedWriteLock(_scopeProvider)) - { - NotifyLocked(new[] { new ContentCacheRefresher.JsonPayload(0, null, TreeChangeTypes.RefreshAll) }, out var draftChanged, out var publishedChanged); - NotifyLocked(new[] { new MediaCacheRefresher.JsonPayload(0, null, TreeChangeTypes.RefreshAll) }, out var anythingChanged); - } + + // These can be run side by side in parallel + + Parallel.Invoke( + () => + { + using (_contentStore.GetScopedWriteLock(_scopeProvider)) + { + NotifyLocked(new[] { new ContentCacheRefresher.JsonPayload(0, null, TreeChangeTypes.RefreshAll) }, out _, out _); + } + }, + () => + { + using (_mediaStore.GetScopedWriteLock(_scopeProvider)) + { + NotifyLocked(new[] { new MediaCacheRefresher.JsonPayload(0, null, TreeChangeTypes.RefreshAll) }, out _); + } + }); } ((PublishedSnapshot)CurrentPublishedSnapshot)?.Resync(); From 49da58b23c064b6cdeb31e4d5c858e09da351095 Mon Sep 17 00:00:00 2001 From: Shannon Date: Fri, 17 Apr 2020 14:56:49 +1000 Subject: [PATCH 40/46] adds notes --- .../NuCache/PublishedSnapshotService.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs index 4e630cad3d..6866878484 100755 --- a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs +++ b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs @@ -868,7 +868,20 @@ namespace Umbraco.Web.PublishedCache.NuCache //Since the models in the cache are based on these actual classes, all of the objects in the cache need to be updated //to use the newest version of the class. - // These can be run side by side in parallel + // NOTE: Ideally this can be run on background threads here which would prevent blocking the UI + // as is the case when saving a content type. Intially one would think that it won't be any different + // between running this here or in another background thread immediately after with regards to how the + // UI will respond because we already know between calling `WithSafeLiveFactoryReset` to reset the PureLive models + // and this code here, that many front-end requests could be attempted to be processed. If that is the case, those pages are going to get a + // model binding error and our ModelBindingExceptionFilter is going to to its magic to reload those pages so the end user is none the wiser. + // So whether or not this executes 'here' or on a background thread immediately wouldn't seem to make any difference except that we can return + // execution to the UI sooner. + // BUT!... there is a difference IIRC. There is still execution logic that continues after this call on this thread with the cache refreshers + // and those cache refreshers need to have the up-to-date data since other user cache refreshers will be expecting the data to be 'live'. If + // we ran this on a background thread then those cache refreshers are going to not get 'live' data when they query the content cache which + // they require. + + // These can be run side by side in parallel. Parallel.Invoke( () => From 008df6018c5483886e6707a97ab0204c84f19f76 Mon Sep 17 00:00:00 2001 From: Shannon Date: Tue, 21 Apr 2020 00:02:59 +1000 Subject: [PATCH 41/46] Fixes: SqlMainDomLock when configured via appSettings cannot be used unless umbraco is installed #7967 --- src/Umbraco.Core/Runtime/SqlMainDomLock.cs | 76 +++++++++++++--------- 1 file changed, 46 insertions(+), 30 deletions(-) diff --git a/src/Umbraco.Core/Runtime/SqlMainDomLock.cs b/src/Umbraco.Core/Runtime/SqlMainDomLock.cs index 4433a8e307..f3bfe4eefc 100644 --- a/src/Umbraco.Core/Runtime/SqlMainDomLock.cs +++ b/src/Umbraco.Core/Runtime/SqlMainDomLock.cs @@ -32,6 +32,7 @@ namespace Umbraco.Core.Runtime // unique id for our appdomain, this is more unique than the appdomain id which is just an INT counter to its safer _lockId = Guid.NewGuid().ToString(); _logger = logger; + _dbFactory = new UmbracoDatabaseFactory( Constants.System.UmbracoConnectionName, _logger, @@ -40,6 +41,12 @@ namespace Umbraco.Core.Runtime public async Task AcquireLockAsync(int millisecondsTimeout) { + if (!_dbFactory.Configured) + { + // if we aren't configured, then we're in an install state, in which case we have no choice but to assume we can acquire + return true; + } + if (!(_dbFactory.SqlContext.SqlSyntax is SqlServerSyntaxProvider sqlServerSyntaxProvider)) throw new NotSupportedException("SqlMainDomLock is only supported for Sql Server"); @@ -126,6 +133,12 @@ namespace Umbraco.Core.Runtime // poll every 1 second Thread.Sleep(1000); + if (!_dbFactory.Configured) + { + // if we aren't configured, we just keep looping since we can't query the db + continue; + } + lock (_locker) { // If cancellation has been requested we will just exit. Depending on timing of the shutdown, @@ -358,41 +371,44 @@ namespace Umbraco.Core.Runtime _cancellationTokenSource.Cancel(); _cancellationTokenSource.Dispose(); - var db = GetDatabase(); - try + if (_dbFactory.Configured) { - db.BeginTransaction(IsolationLevel.ReadCommitted); - - // get a write lock - _sqlServerSyntax.WriteLock(db, Constants.Locks.MainDom); - - // When we are disposed, it means we have released the MainDom lock - // and called all MainDom release callbacks, in this case - // if another maindom is actually coming online we need - // to signal to the MainDom coming online that we have shutdown. - // To do that, we update the existing main dom DB record with a suffixed "_updated" string. - // Otherwise, if we are just shutting down, we want to just delete the row. - if (_mainDomChanging) + var db = GetDatabase(); + try { - _logger.Debug("Releasing MainDom, updating row, new application is booting."); - db.Execute($"UPDATE umbracoKeyValue SET [value] = [value] + '{UpdatedSuffix}' WHERE [key] = @key", new { key = MainDomKey }); + db.BeginTransaction(IsolationLevel.ReadCommitted); + + // get a write lock + _sqlServerSyntax.WriteLock(db, Constants.Locks.MainDom); + + // When we are disposed, it means we have released the MainDom lock + // and called all MainDom release callbacks, in this case + // if another maindom is actually coming online we need + // to signal to the MainDom coming online that we have shutdown. + // To do that, we update the existing main dom DB record with a suffixed "_updated" string. + // Otherwise, if we are just shutting down, we want to just delete the row. + if (_mainDomChanging) + { + _logger.Debug("Releasing MainDom, updating row, new application is booting."); + db.Execute($"UPDATE umbracoKeyValue SET [value] = [value] + '{UpdatedSuffix}' WHERE [key] = @key", new { key = MainDomKey }); + } + else + { + _logger.Debug("Releasing MainDom, deleting row, application is shutting down."); + db.Execute("DELETE FROM umbracoKeyValue WHERE [key] = @key", new { key = MainDomKey }); + } } - else + catch (Exception ex) { - _logger.Debug("Releasing MainDom, deleting row, application is shutting down."); - db.Execute("DELETE FROM umbracoKeyValue WHERE [key] = @key", new { key = MainDomKey }); + ResetDatabase(); + _logger.Error(ex, "Unexpected error during dipsose."); + _hasError = true; + } + finally + { + db?.CompleteTransaction(); + ResetDatabase(); } - } - catch (Exception ex) - { - ResetDatabase(); - _logger.Error(ex, "Unexpected error during dipsose."); - _hasError = true; - } - finally - { - db?.CompleteTransaction(); - ResetDatabase(); } } } From 2a89b36871cbf36d6e30895d7310cd8ff5a412df Mon Sep 17 00:00:00 2001 From: Shannon Date: Wed, 22 Apr 2020 10:37:23 +1000 Subject: [PATCH 42/46] Fixing Nasty Exception with Scope/Provider #5151 --- src/Umbraco.Examine/ContentValueSetBuilder.cs | 34 +++++++++++++++++-- .../UmbracoExamine/IndexInitializer.cs | 16 ++++++--- src/Umbraco.Tests/UmbracoExamine/IndexTest.cs | 10 +++--- .../UmbracoExamine/SearchTests.cs | 2 +- src/Umbraco.Web/Search/ExamineComposer.cs | 3 ++ 5 files changed, 52 insertions(+), 13 deletions(-) diff --git a/src/Umbraco.Examine/ContentValueSetBuilder.cs b/src/Umbraco.Examine/ContentValueSetBuilder.cs index 9cbc311639..788ddfac4a 100644 --- a/src/Umbraco.Examine/ContentValueSetBuilder.cs +++ b/src/Umbraco.Examine/ContentValueSetBuilder.cs @@ -1,9 +1,13 @@ using Examine; +using System; using System.Collections.Generic; using System.Linq; using Umbraco.Core; +using Umbraco.Core.Composing; using Umbraco.Core.Models; +using Umbraco.Core.Models.Membership; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Core.Strings; @@ -16,20 +20,46 @@ namespace Umbraco.Examine { private readonly UrlSegmentProviderCollection _urlSegmentProviders; private readonly IUserService _userService; + private readonly IScopeProvider _scopeProvider; + + [Obsolete("Use the other ctor instead")] + public ContentValueSetBuilder(PropertyEditorCollection propertyEditors, + UrlSegmentProviderCollection urlSegmentProviders, + IUserService userService, + bool publishedValuesOnly) + : this(propertyEditors, urlSegmentProviders, userService, Current.ScopeProvider, publishedValuesOnly) + { + } public ContentValueSetBuilder(PropertyEditorCollection propertyEditors, UrlSegmentProviderCollection urlSegmentProviders, IUserService userService, + IScopeProvider scopeProvider, bool publishedValuesOnly) : base(propertyEditors, publishedValuesOnly) { _urlSegmentProviders = urlSegmentProviders; _userService = userService; + _scopeProvider = scopeProvider; } /// public override IEnumerable GetValueSets(params IContent[] content) { + Dictionary creatorIds; + Dictionary writerIds; + + // We can lookup all of the creator/writer names at once which can save some + // processing below instead of one by one. + using (var scope = _scopeProvider.CreateScope()) + { + creatorIds = content.Select(x => x.CreatorId).Distinct().Select(x => _userService.GetProfileById(x)) + .ToDictionary(x => x.Id, x => x); + writerIds = content.Select(x => x.WriterId).Distinct().Select(x => _userService.GetProfileById(x)) + .ToDictionary(x => x.Id, x => x); + scope.Complete(); + } + // TODO: There is a lot of boxing going on here and ultimately all values will be boxed by Lucene anyways // but I wonder if there's a way to reduce the boxing that we have to do or if it will matter in the end since // Lucene will do it no matter what? One idea was to create a `FieldValue` struct which would contain `object`, `object[]`, `ValueType` and `ValueType[]` @@ -58,8 +88,8 @@ namespace Umbraco.Examine {"urlName", urlValue?.Yield() ?? Enumerable.Empty()}, //Always add invariant urlName {"path", c.Path?.Yield() ?? Enumerable.Empty()}, {"nodeType", c.ContentType.Id.ToString().Yield() ?? Enumerable.Empty()}, - {"creatorName", (c.GetCreatorProfile(_userService)?.Name ?? "??").Yield() }, - {"writerName",(c.GetWriterProfile(_userService)?.Name ?? "??").Yield() }, + {"creatorName", (creatorIds.TryGetValue(c.CreatorId, out var creatorProfile) ? creatorProfile.Name : "??").Yield() }, + {"writerName", (writerIds.TryGetValue(c.CreatorId, out var writerProfile) ? writerProfile.Name : "??").Yield() }, {"writerID", new object[] {c.WriterId}}, {"templateID", new object[] {c.TemplateId ?? 0}}, {UmbracoContentIndex.VariesByCultureFieldName, new object[] {"n"}}, diff --git a/src/Umbraco.Tests/UmbracoExamine/IndexInitializer.cs b/src/Umbraco.Tests/UmbracoExamine/IndexInitializer.cs index 1653de827d..e9f18d8947 100644 --- a/src/Umbraco.Tests/UmbracoExamine/IndexInitializer.cs +++ b/src/Umbraco.Tests/UmbracoExamine/IndexInitializer.cs @@ -30,16 +30,22 @@ namespace Umbraco.Tests.UmbracoExamine /// internal static class IndexInitializer { - public static ContentValueSetBuilder GetContentValueSetBuilder(PropertyEditorCollection propertyEditors, bool publishedValuesOnly) + public static ContentValueSetBuilder GetContentValueSetBuilder(PropertyEditorCollection propertyEditors, IScopeProvider scopeProvider, bool publishedValuesOnly) { - var contentValueSetBuilder = new ContentValueSetBuilder(propertyEditors, new UrlSegmentProviderCollection(new[] { new DefaultUrlSegmentProvider() }), GetMockUserService(), publishedValuesOnly); + var contentValueSetBuilder = new ContentValueSetBuilder( + propertyEditors, + new UrlSegmentProviderCollection(new[] { new DefaultUrlSegmentProvider() }), + GetMockUserService(), + scopeProvider, + publishedValuesOnly); + return contentValueSetBuilder; } - public static ContentIndexPopulator GetContentIndexRebuilder(PropertyEditorCollection propertyEditors, IContentService contentService, ISqlContext sqlContext, bool publishedValuesOnly) + public static ContentIndexPopulator GetContentIndexRebuilder(PropertyEditorCollection propertyEditors, IContentService contentService, IScopeProvider scopeProvider, bool publishedValuesOnly) { - var contentValueSetBuilder = GetContentValueSetBuilder(propertyEditors, publishedValuesOnly); - var contentIndexDataSource = new ContentIndexPopulator(true, null, contentService, sqlContext, contentValueSetBuilder); + var contentValueSetBuilder = GetContentValueSetBuilder(propertyEditors, scopeProvider, publishedValuesOnly); + var contentIndexDataSource = new ContentIndexPopulator(true, null, contentService, scopeProvider.SqlContext, contentValueSetBuilder); return contentIndexDataSource; } diff --git a/src/Umbraco.Tests/UmbracoExamine/IndexTest.cs b/src/Umbraco.Tests/UmbracoExamine/IndexTest.cs index 9e59422310..acb26fb8f6 100644 --- a/src/Umbraco.Tests/UmbracoExamine/IndexTest.cs +++ b/src/Umbraco.Tests/UmbracoExamine/IndexTest.cs @@ -29,7 +29,7 @@ namespace Umbraco.Tests.UmbracoExamine [Test] public void Index_Property_Data_With_Value_Indexer() { - var contentValueSetBuilder = IndexInitializer.GetContentValueSetBuilder(Factory.GetInstance(), false); + var contentValueSetBuilder = IndexInitializer.GetContentValueSetBuilder(Factory.GetInstance(), ScopeProvider, false); using (var luceneDir = new RandomIdRamDirectory()) using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, @@ -121,7 +121,7 @@ namespace Umbraco.Tests.UmbracoExamine [Test] public void Rebuild_Index() { - var contentRebuilder = IndexInitializer.GetContentIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockContentService(), ScopeProvider.SqlContext, false); + var contentRebuilder = IndexInitializer.GetContentIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockContentService(), ScopeProvider, false); var mediaRebuilder = IndexInitializer.GetMediaIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockMediaService()); using (var luceneDir = new RandomIdRamDirectory()) @@ -149,7 +149,7 @@ namespace Umbraco.Tests.UmbracoExamine [Test] public void Index_Protected_Content_Not_Indexed() { - var rebuilder = IndexInitializer.GetContentIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockContentService(), ScopeProvider.SqlContext, false); + var rebuilder = IndexInitializer.GetContentIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockContentService(), ScopeProvider, false); using (var luceneDir = new RandomIdRamDirectory()) @@ -274,7 +274,7 @@ namespace Umbraco.Tests.UmbracoExamine [Test] public void Index_Reindex_Content() { - var rebuilder = IndexInitializer.GetContentIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockContentService(), ScopeProvider.SqlContext, false); + var rebuilder = IndexInitializer.GetContentIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockContentService(), ScopeProvider, false); using (var luceneDir = new RandomIdRamDirectory()) using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir, validator: new ContentValueSetValidator(false))) @@ -315,7 +315,7 @@ namespace Umbraco.Tests.UmbracoExamine public void Index_Delete_Index_Item_Ensure_Heirarchy_Removed() { - var rebuilder = IndexInitializer.GetContentIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockContentService(), ScopeProvider.SqlContext, false); + var rebuilder = IndexInitializer.GetContentIndexRebuilder(Factory.GetInstance(), IndexInitializer.GetMockContentService(), ScopeProvider, false); using (var luceneDir = new RandomIdRamDirectory()) using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir)) diff --git a/src/Umbraco.Tests/UmbracoExamine/SearchTests.cs b/src/Umbraco.Tests/UmbracoExamine/SearchTests.cs index a45a33ec00..96e8892cd1 100644 --- a/src/Umbraco.Tests/UmbracoExamine/SearchTests.cs +++ b/src/Umbraco.Tests/UmbracoExamine/SearchTests.cs @@ -55,7 +55,7 @@ namespace Umbraco.Tests.UmbracoExamine allRecs); var propertyEditors = Factory.GetInstance(); - var rebuilder = IndexInitializer.GetContentIndexRebuilder(propertyEditors, contentService, ScopeProvider.SqlContext, true); + var rebuilder = IndexInitializer.GetContentIndexRebuilder(propertyEditors, contentService, ScopeProvider, true); using (var luceneDir = new RandomIdRamDirectory()) using (var indexer = IndexInitializer.GetUmbracoIndexer(ProfilingLogger, luceneDir)) diff --git a/src/Umbraco.Web/Search/ExamineComposer.cs b/src/Umbraco.Web/Search/ExamineComposer.cs index b30f0cbe03..64eeb6978a 100644 --- a/src/Umbraco.Web/Search/ExamineComposer.cs +++ b/src/Umbraco.Web/Search/ExamineComposer.cs @@ -4,6 +4,7 @@ using Umbraco.Core; using Umbraco.Core.Composing; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Scoping; using Umbraco.Core.Services; using Umbraco.Core.Strings; using Umbraco.Examine; @@ -36,12 +37,14 @@ namespace Umbraco.Web.Search factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), + factory.GetInstance(), true)); composition.RegisterUnique(factory => new ContentValueSetBuilder( factory.GetInstance(), factory.GetInstance(), factory.GetInstance(), + factory.GetInstance(), false)); composition.RegisterUnique, MediaValueSetBuilder>(); composition.RegisterUnique, MemberValueSetBuilder>(); From d4f84998513889351c18d988579a55397ff928fc Mon Sep 17 00:00:00 2001 From: Callum Whyte Date: Sun, 19 Apr 2020 15:13:58 +0100 Subject: [PATCH 43/46] Update Models Builder model namespace in Views/web.config --- build/NuSpecs/tools/Views.Web.config.install.xdt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/NuSpecs/tools/Views.Web.config.install.xdt b/build/NuSpecs/tools/Views.Web.config.install.xdt index 828bb8612f..7dd2640d09 100644 --- a/build/NuSpecs/tools/Views.Web.config.install.xdt +++ b/build/NuSpecs/tools/Views.Web.config.install.xdt @@ -11,7 +11,7 @@ - + From c58831925e516c247d6c74642e56ad26cb3cabff Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Wed, 22 Apr 2020 16:20:49 +0200 Subject: [PATCH 44/46] 5151 - Fix using writerId instead of creatorId --- src/Umbraco.Examine/ContentValueSetBuilder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Umbraco.Examine/ContentValueSetBuilder.cs b/src/Umbraco.Examine/ContentValueSetBuilder.cs index 788ddfac4a..8ff556a470 100644 --- a/src/Umbraco.Examine/ContentValueSetBuilder.cs +++ b/src/Umbraco.Examine/ContentValueSetBuilder.cs @@ -89,7 +89,7 @@ namespace Umbraco.Examine {"path", c.Path?.Yield() ?? Enumerable.Empty()}, {"nodeType", c.ContentType.Id.ToString().Yield() ?? Enumerable.Empty()}, {"creatorName", (creatorIds.TryGetValue(c.CreatorId, out var creatorProfile) ? creatorProfile.Name : "??").Yield() }, - {"writerName", (writerIds.TryGetValue(c.CreatorId, out var writerProfile) ? writerProfile.Name : "??").Yield() }, + {"writerName", (writerIds.TryGetValue(c.WriterId, out var writerProfile) ? writerProfile.Name : "??").Yield() }, {"writerID", new object[] {c.WriterId}}, {"templateID", new object[] {c.TemplateId ?? 0}}, {UmbracoContentIndex.VariesByCultureFieldName, new object[] {"n"}}, From 27f7d5efae744e9e4d227e3d526ec83113ded80f Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Thu, 23 Apr 2020 08:38:29 +0200 Subject: [PATCH 45/46] 5151 - Added GetProfilesById extension --- .../Services/UserServiceExtensions.cs | 13 +++++++++++++ src/Umbraco.Examine/ContentValueSetBuilder.cs | 4 ++-- src/Umbraco.Tests/Services/UserServiceTests.cs | 18 ++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/Umbraco.Core/Services/UserServiceExtensions.cs b/src/Umbraco.Core/Services/UserServiceExtensions.cs index 82cab07b25..c365f1ccc2 100644 --- a/src/Umbraco.Core/Services/UserServiceExtensions.cs +++ b/src/Umbraco.Core/Services/UserServiceExtensions.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Web.Security; using Umbraco.Core.Models.Membership; @@ -116,5 +117,17 @@ namespace Umbraco.Core.Services var permissionCollection = userService.GetPermissions(user, nodeId); return permissionCollection.SelectMany(c => c.AssignedPermissions).Distinct().ToArray(); } + + internal static IEnumerable GetProfilesById(this IUserService userService, params int[] ids) + { + var fullUsers = userService.GetUsersById(ids); + + return fullUsers.Select(user => + { + var asProfile = user as IProfile; + return asProfile ?? new UserProfile(user.Id, user.Name); + }); + + } } } diff --git a/src/Umbraco.Examine/ContentValueSetBuilder.cs b/src/Umbraco.Examine/ContentValueSetBuilder.cs index 8ff556a470..b8477a9047 100644 --- a/src/Umbraco.Examine/ContentValueSetBuilder.cs +++ b/src/Umbraco.Examine/ContentValueSetBuilder.cs @@ -53,9 +53,9 @@ namespace Umbraco.Examine // processing below instead of one by one. using (var scope = _scopeProvider.CreateScope()) { - creatorIds = content.Select(x => x.CreatorId).Distinct().Select(x => _userService.GetProfileById(x)) + creatorIds = _userService.GetProfilesById(content.Select(x => x.CreatorId).ToArray()) .ToDictionary(x => x.Id, x => x); - writerIds = content.Select(x => x.WriterId).Distinct().Select(x => _userService.GetProfileById(x)) + writerIds = _userService.GetProfilesById(content.Select(x => x.WriterId).ToArray()) .ToDictionary(x => x.Id, x => x); scope.Complete(); } diff --git a/src/Umbraco.Tests/Services/UserServiceTests.cs b/src/Umbraco.Tests/Services/UserServiceTests.cs index a96385a923..016085c352 100644 --- a/src/Umbraco.Tests/Services/UserServiceTests.cs +++ b/src/Umbraco.Tests/Services/UserServiceTests.cs @@ -924,6 +924,24 @@ namespace Umbraco.Tests.Services Assert.AreEqual(user.Id, profile.Id); } + [Test] + public void Get_By_Profile_Id_Must_return_null_if_user_not_exists() + { + var profile = ServiceContext.UserService.GetProfileById(42); + + // Assert + Assert.IsNull(profile); + } + + [Test] + public void GetProfilesById_Must_empty_if_users_not_exists() + { + var profiles = ServiceContext.UserService.GetProfilesById(42); + + // Assert + CollectionAssert.IsEmpty(profiles); + } + [Test] public void Get_User_By_Username() { From c7908a9ba1da8c1518e3a9c41bd9a66bac9ef0fc Mon Sep 17 00:00:00 2001 From: Kenn Jacobsen Date: Sun, 26 Apr 2020 13:50:15 +0200 Subject: [PATCH 46/46] V8: Make the sticky header span the full width of its container (#7184) * Make the sticky header span the full width of its container * Fix bad merge --- .../components/editor/subheader/umb-editor-sub-header.less | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Umbraco.Web.UI.Client/src/less/components/editor/subheader/umb-editor-sub-header.less b/src/Umbraco.Web.UI.Client/src/less/components/editor/subheader/umb-editor-sub-header.less index 4ebfa94b6f..3c4a037b0b 100644 --- a/src/Umbraco.Web.UI.Client/src/less/components/editor/subheader/umb-editor-sub-header.less +++ b/src/Umbraco.Web.UI.Client/src/less/components/editor/subheader/umb-editor-sub-header.less @@ -5,7 +5,7 @@ border-right: 5px solid @brownGrayLight; display: flex; justify-content: space-between; - margin: -10px -5px 10px; + margin: -10px -1px 10px; position: relative; top: 0; box-sizing: border-box; @@ -34,6 +34,7 @@ transition: box-shadow 240ms; position:sticky; z-index: 30; + width: calc(100% + 2px); &.umb-sticky-bar--active { box-shadow: 0 6px 3px -3px rgba(0,0,0,.16);