diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 0101ac9d16..5537a46ef8 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) @@ -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. @@ -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. @@ -122,9 +123,10 @@ You can get in touch with [the PR team](#the-pr-team) in multiple ways; we love 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+ + * [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. @@ -193,4 +195,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. 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 @@ - + 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 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.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(); } } } 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 9cbc311639..b8477a9047 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 = _userService.GetProfilesById(content.Select(x => x.CreatorId).ToArray()) + .ToDictionary(x => x.Id, x => x); + writerIds = _userService.GetProfilesById(content.Select(x => x.WriterId).ToArray()) + .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.WriterId, 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/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() { 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.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" }, 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..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) { @@ -18,20 +18,20 @@ ]; // 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; 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] }); } @@ -40,13 +40,13 @@ })); - 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 (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] }); } @@ -54,10 +54,10 @@ } }); })); - + scope.rememberFocus = focusService.rememberFocus; - - scope.searchClick = function() { + + scope.searchClick = function () { var showSearch = appState.getSearchState("show"); appState.setSearchState("show", !showSearch); }; @@ -71,13 +71,15 @@ }; scope.avatarClick = function () { - if(!scope.userDialog) { + 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/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/content/edit.controller.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/content/edit.controller.js index ebd44e6bf5..4bc34ec392 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 @@ -180,32 +180,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 @@ -321,7 +321,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 @@ -782,7 +782,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) { @@ -816,7 +816,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 5db31a3430..d277350d90 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 @@ -42,7 +42,7 @@ /** Called when the component initializes */ function onInit() { - prevContentDateUpdated = angular.copy(vm.content.updateDate); + prevContentDateUpdated = Utilities.copy(vm.content.updateDate); setActiveVariant(); } @@ -69,7 +69,7 @@ function doCheck() { if (!angular.equals(vm.content.updateDate, prevContentDateUpdated)) { setActiveVariant(); - prevContentDateUpdated = angular.copy(vm.content.updateDate); + prevContentDateUpdated = Utilities.copy(vm.content.updateDate); } } 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/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/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/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(); + }); + } + }; + }); 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..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 @@ -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 JSON.parse(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 angular.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 { + JSON.parse(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/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/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/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/tags/umbtagseditor.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/tags/umbtagseditor.directive.js index 7ff7f7fa66..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 @@ -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); @@ -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 3d743c7e9a..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 }); @@ -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 cd1b1d8181..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 @@ -24,40 +24,40 @@ // sets the ace worker path, if running from concatenated // or minified source - if (angular.isDefined(opts.workerPath)) { + if (Utilities.isDefined(opts.workerPath)) { var config = window.ace.require('ace/config'); config.set('workerPath', opts.workerPath); } // ace requires loading - if (angular.isDefined(opts.require)) { + if (Utilities.isDefined(opts.require)) { opts.require.forEach(function(n) { window.ace.require(n); }); } // Boolean options - if (angular.isDefined(opts.showGutter)) { + if (Utilities.isDefined(opts.showGutter)) { acee.renderer.setShowGutter(opts.showGutter); } - if (angular.isDefined(opts.useWrapMode)) { + if (Utilities.isDefined(opts.useWrapMode)) { session.setUseWrapMode(opts.useWrapMode); } - if (angular.isDefined(opts.showInvisibles)) { + if (Utilities.isDefined(opts.showInvisibles)) { acee.renderer.setShowInvisibles(opts.showInvisibles); } - if (angular.isDefined(opts.showIndentGuides)) { + if (Utilities.isDefined(opts.showIndentGuides)) { acee.renderer.setDisplayIndentGuides(opts.showIndentGuides); } - if (angular.isDefined(opts.useSoftTabs)) { + if (Utilities.isDefined(opts.useSoftTabs)) { session.setUseSoftTabs(opts.useSoftTabs); } - if (angular.isDefined(opts.showPrintMargin)) { + if (Utilities.isDefined(opts.showPrintMargin)) { acee.setShowPrintMargin(opts.showPrintMargin); } // commands - if (angular.isDefined(opts.disableSearch) && opts.disableSearch) { + if (Utilities.isDefined(opts.disableSearch) && opts.disableSearch) { acee.commands.addCommands([{ name: 'unfind', bindKey: { @@ -72,15 +72,15 @@ } // 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 - if (angular.isDefined(opts.firstLineNumber)) { - if (angular.isNumber(opts.firstLineNumber)) { + if (Utilities.isDefined(opts.firstLineNumber)) { + if (Utilities.isNumber(opts.firstLineNumber)) { session.setOption('firstLineNumber', opts.firstLineNumber); } else if (angular.isFunction(opts.firstLineNumber)) { session.setOption('firstLineNumber', opts.firstLineNumber()); @@ -89,7 +89,7 @@ // advanced options var key, obj; - if (angular.isDefined(opts.advanced)) { + if (Utilities.isDefined(opts.advanced)) { for (key in opts.advanced) { // create a javascript object with the key and value obj = { @@ -102,7 +102,7 @@ } // advanced options for the renderer - if (angular.isDefined(opts.rendererOptions)) { + if (Utilities.isDefined(opts.rendererOptions)) { for (key in opts.rendererOptions) { // create a javascript object with the key and value obj = { @@ -206,7 +206,7 @@ */ var args = Array.prototype.slice.call(arguments, 1); - if (angular.isDefined(callback)) { + if (Utilities.isDefined(callback)) { scope.$evalAsync(function() { if (angular.isFunction(callback)) { callback(args); 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/umbgroupsbuilder.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/umbgroupsbuilder.directive.js index 6f76828f5a..3f53a1e18c 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,741 +1,740 @@ -(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, + contentTypeAllowSegmentVariant: scope.model.allowSegmentVariant, + 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; + property.allowSegmentVariant = propertyModel.allowSegmentVariant; + + // 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 = ""; - } - // SEGMENTS_TODO: test if we need to do the same for the segments ^^ - var propertyModel = angular.copy(property); - - var propertySettings = { - title: "Property settings", - property: propertyModel, - contentType: scope.contentType, - contentTypeName: scope.model.name, - contentTypeAllowCultureVariant: scope.model.allowCultureVariant, - contentTypeAllowSegmentVariant: scope.model.allowSegmentVariant, - 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; - property.allowSegmentVariant = propertyModel.allowSegmentVariant; - - // 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/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/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/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/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/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); - -})(); 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/components/users/changepassword.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/components/users/changepassword.directive.js index 97eb2bf708..8cbdabbf75 100644 --- a/src/Umbraco.Web.UI.Client/src/common/directives/components/users/changepassword.directive.js +++ b/src/Umbraco.Web.UI.Client/src/common/directives/components/users/changepassword.directive.js @@ -56,7 +56,7 @@ } //set the model defaults - if (!angular.isObject(vm.passwordValues)) { + if (!Utilities.isObject(vm.passwordValues)) { //if it's not an object then just create a new one vm.passwordValues = { newPassword: null, 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/common/directives/validation/valpropertymsg.directive.js b/src/Umbraco.Web.UI.Client/src/common/directives/validation/valpropertymsg.directive.js index c7275c6ec3..623225dc64 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 @@ -102,7 +102,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++; } } @@ -112,8 +112,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/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/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/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/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/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/content.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/content.resource.js index d714ea4938..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 @@ -610,10 +610,10 @@ 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)) { + if (Utilities.isString(v)) { return v === "true"; } if (typeof v === "boolean") { @@ -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/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/resources/media.resource.js b/src/Umbraco.Web.UI.Client/src/common/resources/media.resource.js index e4e3cc6f3f..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 @@ -348,10 +348,10 @@ 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)) { + 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 d21edbbab8..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 @@ -53,10 +53,10 @@ 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)) { + if (Utilities.isString(v)) { return v === "true"; } if (typeof v === "boolean") { 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/contenteditinghelper.service.js b/src/Umbraco.Web.UI.Client/src/common/services/contenteditinghelper.service.js index c15d25b7bd..8f2aa1d22b 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; } @@ -39,7 +39,7 @@ function contentEditingHelper(fileManager, $q, $location, $routeParams, editorSt /** Used by the content editor and mini content editor to perform saving operations */ contentEditorPerformSave: function (args) { - if (!angular.isObject(args)) { + if (!Utilities.isObject(args)) { throw "args must be an object"; } if (!args.scope) { @@ -152,7 +152,7 @@ function contentEditingHelper(fileManager, $q, $location, $routeParams, editorSt here we'll build the buttons according to the chars of the user. */ configureContentEditorButtons: function (args) { - if (!angular.isObject(args)) { + if (!Utilities.isObject(args)) { throw "args must be an object"; } if (!args.content) { 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 305e4a694d..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(angular.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/events.service.js b/src/Umbraco.Web.UI.Client/src/common/services/events.service.js index 51f63e6787..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 @@ -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,9 +12,9 @@ */ function eventsService($q, $rootScope) { - + return { - + /** raise an event with a given name */ emit: function (name, args) { 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 41614a3bee..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 @@ -27,10 +27,10 @@ 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 (!angular.isObject(args.files)) { + if (!Utilities.isObject(args.files)) { throw "args.files must be an object"; } @@ -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 46ae0ecb8e..5411602e34 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/macro.service.js b/src/Umbraco.Web.UI.Client/src/common/services/macro.service.js index a91f9d51e4..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,12 +62,12 @@ 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 { //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/mediahelper.service.js b/src/Umbraco.Web.UI.Client/src/common/services/mediahelper.service.js index 2271f891ce..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; } @@ -143,7 +143,7 @@ function mediaHelper(umbRequestHelper, $log) { */ resolveFileFromEntity: function (mediaEntity, thumbnail) { - var mediaPath = angular.isObject(mediaEntity.metaData) ? mediaEntity.metaData.MediaPath : null; + var mediaPath = Utilities.isObject(mediaEntity.metaData) ? mediaEntity.metaData.MediaPath : null; if (!mediaPath) { //don't throw since this image legitimately might not contain a media path, but output a warning 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 97b3de8feb..da784a1f9e 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", "csegment", "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; } } @@ -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]; @@ -114,7 +114,7 @@ function navigationService($routeParams, $location, $q, $injector, eventsService } var service = { - + /** * @ngdoc method * @name umbraco.services.navigationService#isRouteChangingNavigation @@ -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); } @@ -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", []); @@ -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('.'); @@ -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/common/services/notifications.service.js b/src/Umbraco.Web.UI.Client/src/common/services/notifications.service.js index e5701b9de0..196e0e3baa 100644 --- a/src/Umbraco.Web.UI.Client/src/common/services/notifications.service.js +++ b/src/Umbraco.Web.UI.Client/src/common/services/notifications.service.js @@ -245,7 +245,7 @@ angular.module('umbraco.services') * @param {Int} index index where the notication should be removed from */ remove: function (index) { - if(angular.isObject(index)){ + if (Utilities.isObject(index)){ var i = nArray.indexOf(index); angularHelper.safeApply($rootScope, function() { nArray.splice(i, 1); 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 7c36b5e4eb..be730a6f60 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 @@ -26,7 +26,7 @@ function serverValidationManager($timeout) { } function getFieldErrors(self, fieldName) { - if (!angular.isString(fieldName)) { + if (!Utilities.isString(fieldName)) { throw "fieldName must be a string"; } @@ -36,11 +36,12 @@ function serverValidationManager($timeout) { }); } + function getPropertyErrors(self, propertyAlias, culture, segment, 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/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/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/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/umbdataformatter.service.js b/src/Umbraco.Web.UI.Client/src/common/services/umbdataformatter.service.js index 02305b77c5..30a80bc338 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 { @@ -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/umbrequesthelper.service.js b/src/Umbraco.Web.UI.Client/src/common/services/umbrequesthelper.service.js index 0d766dc7d8..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; @@ -59,7 +59,7 @@ function umbRequestHelper($http, $q, notificationsService, eventsService, formHe return encodeURIComponent(key) + "=" + encodeURIComponent(val); }).join("&"); } - else if (angular.isObject(queryStrings)) { + else if (Utilities.isObject(queryStrings)) { //this allows for a normal object to be passed in (ie. a dictionary) return decodeURIComponent($.param(queryStrings)); @@ -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 }; @@ -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,13 +340,13 @@ 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, !angular.isString(item.value) ? angular.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) ? angular.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/common/services/user.service.js b/src/Umbraco.Web.UI.Client/src/common/services/user.service.js index afd7b606e7..de6fbaf782 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(); } @@ -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 data; + + }).then(this.setAuthenticationSuccessful); }, setAuthenticationSuccessful: function (data) { 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..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,11 +206,11 @@ function umbSessionStorage($window) { return { get: function (key) { - return angular.fromJson(storage["umb_" + key]); + return JSON.parse(storage["umb_" + key]); }, 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/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/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/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); 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.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; 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/main.controller.js b/src/Umbraco.Web.UI.Client/src/main.controller.js index 198ac132c1..81eadf150f 100644 --- a/src/Umbraco.Web.UI.Client/src/main.controller.js +++ b/src/Umbraco.Web.UI.Client/src/main.controller.js @@ -72,6 +72,7 @@ function MainController($scope, $location, appState, treeService, notificationsS $scope.authenticated = null; $scope.user = null; const isTimedOut = data && data.isTimedOut ? true : false; + $scope.showLoginScreen(isTimedOut); // Remove the localstorage items for tours shown diff --git a/src/Umbraco.Web.UI.Client/src/navigation.controller.js b/src/Umbraco.Web.UI.Client/src/navigation.controller.js index 281be2d331..ee8d13e320 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; @@ -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/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/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/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/common/infiniteeditors/macropicker/macropicker.controller.js b/src/Umbraco.Web.UI.Client/src/views/common/infiniteeditors/macropicker/macropicker.controller.js index dfc77f786c..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(); } } @@ -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); @@ -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 @@ -104,13 +104,13 @@ 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) { - $scope.macros = _.filter(data, function(d) { + 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..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 @@ -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 @@ -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; } @@ -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 { @@ -341,7 +341,7 @@ angular.module("umbraco") return false; } - function gotoStartNode(err) { + function gotoStartNode() { gotoFolder({ id: $scope.startNodeId, name: "Media", icon: "icon-folder" }); } @@ -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 : []; @@ -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 11d80d562d..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; }); } @@ -176,7 +176,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", if (angular.isFunction($scope.model.filter)) { $scope.model.filterAdvanced = true; } - else if (angular.isObject($scope.model.filter)) { + else if (Utilities.isObject($scope.model.filter)) { $scope.model.filterAdvanced = true; } else { @@ -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 @@ -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, @@ -446,7 +446,7 @@ angular.module("umbraco").controller("Umbraco.Editors.TreePickerController", // be allowed to be clicked on nodes = _.filter(nodes, function (n) { - return !angular.isObject(n.metaData.listViewNode); + return !Utilities.isObject(n.metaData.listViewNode); }); if ($scope.model.filterAdvanced) { @@ -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/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 @@
-
+ -
  • - +
  • + - - {{ tab.label }} + +
  • 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}} -
    +
    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) { 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/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/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/changepassword/changepassword.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/changepassword/changepassword.controller.js index 49058dfe29..ab7f5c66e0 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/changepassword/changepassword.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/changepassword/changepassword.controller.js @@ -38,7 +38,7 @@ angular.module("umbraco").controller("Umbraco.PropertyEditors.ChangePasswordCont } //set the model defaults - if (!angular.isObject($scope.model.value)) { + if (!Utilities.isObject($scope.model.value)) { //if it's not an object then just create a new one $scope.model.value = { newPassword: null, diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/checkboxlist/checkboxlist.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/checkboxlist/checkboxlist.controller.js index 297bf23cef..10668808a5 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/checkboxlist/checkboxlist.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/checkboxlist/checkboxlist.controller.js @@ -10,7 +10,7 @@ angular.module("umbraco").controller("Umbraco.PropertyEditors.CheckboxListContro function init() { // currently the property editor will onyl work if our input is an object. - if (angular.isObject($scope.model.config.items)) { + if (Utilities.isObject($scope.model.config.items)) { // formatting the items in the dictionary into an array var sortedItems = []; 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 a6d615cdd1..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,14 +45,14 @@ 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(!angular.isObject($scope.model.config.items[0])){ + if (!Utilities.isObject($scope.model.config.items[0])){ $scope.model.config.items = convertArrayToDictionaryArray($scope.model.config.items); } } - else if (angular.isObject($scope.model.config.items)) { + else if (Utilities.isObject($scope.model.config.items)) { $scope.model.config.items = convertObjectToDictionaryArray($scope.model.config.items); } else { diff --git a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/embed.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/embed.controller.js index 0f8a8df895..1370550631 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/embed.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/editors/embed.controller.js @@ -4,7 +4,7 @@ angular.module("umbraco") function onInit() { - var embedPreview = angular.isObject($scope.control.value) && $scope.control.value.preview ? $scope.control.value.preview : $scope.control.value; + var embedPreview = Utilities.isObject($scope.control.value) && $scope.control.value.preview ? $scope.control.value.preview : $scope.control.value; $scope.trustedValue = embedPreview ? $sce.trustAsHtml(embedPreview) : null; @@ -19,7 +19,7 @@ angular.module("umbraco") $scope.setEmbed = function () { - var original = angular.isObject($scope.control.value) ? $scope.control.value : null; + var original = Utilities.isObject($scope.control.value) ? $scope.control.value : null; var embed = { original: original, 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 67ec951512..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,13 +467,13 @@ 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 (angular.isObject(gridItem.config)) { + if (Utilities.isObject(gridItem.config)) { _.each(config, function (cfg) { var val = gridItem.config[cfg.key]; if (val) { @@ -482,7 +482,7 @@ angular.module("umbraco") }); } - if (angular.isObject(gridItem.styles)) { + if (Utilities.isObject(gridItem.styles)) { _.each(styles, function (style) { var val = gridItem.styles[style.key]; if (val) { @@ -739,13 +739,13 @@ 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); } 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,14 +756,14 @@ 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 // 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.html b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.html index 7fdefb4d78..5048c479bb 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.html +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/grid/grid.html @@ -256,7 +256,7 @@ - Add new role + Add new row 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 e3576426a3..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 (angular.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) { @@ -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/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; }); 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..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)); }); } @@ -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/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/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/propertyeditors/radiobuttons/radiobuttons.controller.js b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/radiobuttons/radiobuttons.controller.js index 2db7eaf562..6bfde10e9c 100644 --- a/src/Umbraco.Web.UI.Client/src/views/propertyeditors/radiobuttons/radiobuttons.controller.js +++ b/src/Umbraco.Web.UI.Client/src/views/propertyeditors/radiobuttons/radiobuttons.controller.js @@ -8,7 +8,7 @@ angular.module("umbraco").controller("Umbraco.PropertyEditors.RadioButtonsContro function init() { //we can't really do anything if the config isn't an object - if (angular.isObject($scope.model.config.items)) { + if (Utilities.isObject($scope.model.config.items)) { // formatting the items in the dictionary into an array var sortedItems = []; 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/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/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/src/views/templates/edit.controller.js b/src/Umbraco.Web.UI.Client/src/views/templates/edit.controller.js index 30aa677b8b..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 @@ -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 = $('[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 b4a3fb9ed6..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 @@ -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; @@ -104,7 +104,7 @@ angular.mock.$Browser = function () { * @param {number=} number of milliseconds to flush. See {@link #defer.now} */ self.defer.flush = function (delay) { - if (angular.isDefined(delay)) { + if (Utilities.isDefined(delay)) { self.defer.now += delay; } else { if (self.deferredFns.length) { @@ -165,15 +165,15 @@ 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; } } } 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')); } @@ -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); @@ -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' } } @@ -686,19 +686,19 @@ 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 (angular.isArray(object)) { + } else if (Utilities.isArray(object)) { out = []; angular.forEach(object, function (o) { out.push(serialize(o)); }); out = '[ ' + out.join(', ') + ' ]'; - } else if (angular.isObject(object)) { + } else if (Utilities.isObject(object)) { if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) { out = serializeScope(object); } else if (object instanceof Error) { @@ -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); } @@ -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')); } /** @@ -1267,7 +1267,7 @@ function createHttpBackendMock($rootScope, $delegate, $browser) { $rootScope.$digest(); if (!responses.length) throw Error('No pending request to flush !'); - if (angular.isDefined(count)) { + if (Utilities.isDefined(count)) { while (count--) { if (!responses.length) throw Error('No more pending request to flush !'); responses.shift()(); @@ -1365,8 +1365,8 @@ function MockHttpExpectation(method, url, data, headers) { this.match = function (m, u, d, h) { if (method != m) return false; if (!this.matchUrl(u)) return false; - if (angular.isDefined(d) && !this.matchData(d)) return false; - if (angular.isDefined(h) && !this.matchHeaders(h)) return false; + if (Utilities.isDefined(d) && !this.matchData(d)) return false; + if (Utilities.isDefined(h) && !this.matchHeaders(h)) return false; return true; }; @@ -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; }; @@ -1499,7 +1499,7 @@ angular.mock.$TimeoutDecorator = function ($delegate, $browser) { */ angular.mock.$RootElementProvider = function () { this.$get = function () { - return angular.element('
    '); + return $('
    '); } }; @@ -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(); * //... @@ -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]; } } 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); + }); + }); + }); +})(); 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 @@ - + + diff --git a/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml b/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml index 7445ef0f3d..d7ccb13193 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/en.xml @@ -2241,6 +2241,8 @@ To manage your website, simply open the Umbraco back office and start adding con Create Edit Name + 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 54a34b570d..b8d700ceb0 100644 --- a/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml +++ b/src/Umbraco.Web.UI/Umbraco/config/lang/en_us.xml @@ -2253,6 +2253,8 @@ To manage your website, simply open the Umbraco back office and start adding con Create Edit Name + Add new row + View more options References 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; 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) diff --git a/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs b/src/Umbraco.Web/PublishedCache/NuCache/PublishedSnapshotService.cs index a33d9ee427..6866878484 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,37 @@ 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); - } + + // 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( + () => + { + 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(); 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>(); 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; } }