diff --git a/.gitignore b/.gitignore index 5759fcc33..f01b25411 100644 --- a/.gitignore +++ b/.gitignore @@ -59,7 +59,7 @@ _ReSharper* *.ncrunch* .*crunch*.local.xml -# Installshield output folder +# Installshield output folder [Ee]xpress # DocProject is a documentation generator add-in @@ -117,18 +117,25 @@ UpgradeLog*.XML #NPM directory node_modules -Feather.jmconfig +#Bower directory +bower_components -ReferenceAssemblies +Feather.jmconfig -Telerik.Sitefinity.Frontend.Test/lib +Tests/Telerik.Sitefinity.Frontend.ClientTest/lib .nuget/NuGet.exe -Telerik.Sitefinity.Frontend.Test/test-results.xml +Tests/Telerik.Sitefinity.Frontend.ClientTest/test-results.xml UpgradeLog*.htm .grunt _SpecRunner.html #Angular directive templates converted in javascript. Used in client tests. -Tests/Telerik.Sitefinity.Frontend.ClientTest/templates.js \ No newline at end of file +Tests/Telerik.Sitefinity.Frontend.ClientTest/templates.js +/.JustCode + +Tests/Telerik.Sitefinity.Frontend.ClientTest/obj/Debug/DesignTimeResolveAssemblyReferencesInput.cache +Feather.sln.GhostDoc.xml +/.vs/config/applicationhost.config +*.aiis diff --git a/.nuget/NuGet.Config b/.nuget/NuGet.Config deleted file mode 100644 index 67f8ea046..000000000 --- a/.nuget/NuGet.Config +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/.nuget/NuGet.targets b/.nuget/NuGet.targets deleted file mode 100644 index ab5b65d02..000000000 --- a/.nuget/NuGet.targets +++ /dev/null @@ -1,144 +0,0 @@ - - - - $(MSBuildProjectDirectory)\..\ - - - false - - - false - - - true - - - true - - - - - - - - - - - - - - $([System.IO.Path]::Combine($(SolutionDir), ".nuget")) - - - - - $(SolutionDir).nuget - - - - $(MSBuildProjectDirectory)\packages.$(MSBuildProjectName.Replace(' ', '_')).config - $(MSBuildProjectDirectory)\packages.$(MSBuildProjectName).config - - - - $(MSBuildProjectDirectory)\packages.config - $(PackagesProjectConfig) - - - - - $(NuGetToolsPath)\NuGet.exe - @(PackageSource) - - "$(NuGetExePath)" - mono --runtime=v4.0.30319 $(NuGetExePath) - - $(TargetDir.Trim('\\')) - - -RequireConsent - -NonInteractive - - "$(SolutionDir) " - "$(SolutionDir)" - - - $(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir) -NoCache - $(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols - - - - RestorePackages; - $(BuildDependsOn); - - - - - $(BuildDependsOn); - BuildPackage; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Build/FeatherPrecompilation.targets b/Build/FeatherPrecompilation.targets new file mode 100644 index 000000000..79e1bc33d --- /dev/null +++ b/Build/FeatherPrecompilation.targets @@ -0,0 +1,157 @@ + + + + PrecompileFeatherRazorFiles; + $(CompileDependsOn); + CompileRazorGeneratedCsFiles; + + + + CleanRazorCsFiles; + $(CleanDependsOn); + + + + _ResolveFeatherRazorFiles; + GroupRazorSrcFilesByPackage; + + + + GenerateAssemblyInfoFilesForResourcePackageDlls; + + + ResourcePackages + $(AssemblyName).$(FeatherResourcePackagesFolderName). + $(MSBuildThisFileDirectory)$(FeatherResourcePackagesFolderName) + Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes.ResourcePackage + true + $(MsBuildProjectDirectory)\obj\FeatherCodeGen\ + + + + + + + + + + + + + + + + + + + + + + + + + + <_RazorSourceFileName>%(FeatherRazorSrcFiles.Identity) + <_PackageFolderLength>$([MSBuild]::Add($(FeatherResourcePackagesFolderName.Length), 1)) + <_LengthLeft>$([MSBuild]::Subtract($(_RazorSourceFileName.Length), $(_PackageFolderLength))) + <_FeatherPackageFilePath>$(_RazorSourceFileName.Substring($(_PackageFolderLength), $(_LengthLeft))) + <_FeatherPackageName>$(_FeatherPackageFilePath.Substring(0, $(_FeatherPackageFilePath.IndexOf('\')))) + + + + + $(_FeatherPackageName) + + + + + + + + + + + + + %(FeatherRazorSrcFiles.PackageName) + + + + + + + $(FeatherCodeGenDirectory)%(RazorGeneratedCsFiles.PackageName)AssemblyInfo.cs + + + + <_Parameter1>%(RazorGeneratedCsFiles.PackageName) + + + + + + + + + + %(RazorGeneratedCsFiles.PackageName) + + + + + + + <_PackageName>%(RazorGeneratedCsFiles.PackageName) + + + + + <_PackageResources Condition="$(_PackageResources)!=''" Remove="@(_PackageResources)" /> + <_PackageResources Include="@(FeatherRazorSrcFiles->WithMetadataValue('PackageName', '$(_PackageName)'))"> + Non-Resx + + <_PackageRefences Condition="$(_PackageRefences)!=''" Remove="@(_PackageRefences)" /> + <_PackageRefences Include="@(ReferencePath)" /> + <_PackageRefences Include="$(IntermediateOutputPath)$(AssemblyName).dll" /> + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Build/RazorGenerator.MsBuild/RazorGenerator.MsBuild.2.4.1.nupkg b/Build/RazorGenerator.MsBuild/RazorGenerator.MsBuild.2.4.1.nupkg new file mode 100644 index 000000000..7b34806ea Binary files /dev/null and b/Build/RazorGenerator.MsBuild/RazorGenerator.MsBuild.2.4.1.nupkg differ diff --git a/Build/RazorGenerator.MsBuild/build/RazorGenerator.MsBuild.targets b/Build/RazorGenerator.MsBuild/build/RazorGenerator.MsBuild.targets new file mode 100644 index 000000000..b60d874c4 --- /dev/null +++ b/Build/RazorGenerator.MsBuild/build/RazorGenerator.MsBuild.targets @@ -0,0 +1,40 @@ + + + true + $(MSBuildThisFileDirectory)\..\tools\RazorGenerator.MsBuild.dll + $(MsBuildProjectDirectory)\obj\CodeGen\ + + + PrecompileRazorFiles; + $(CompileDependsOn); + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Build/RazorGenerator.MsBuild/tools/RazorGenerator.Core.dll b/Build/RazorGenerator.MsBuild/tools/RazorGenerator.Core.dll new file mode 100644 index 000000000..128aede61 Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/RazorGenerator.Core.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/RazorGenerator.MsBuild.dll b/Build/RazorGenerator.MsBuild/tools/RazorGenerator.MsBuild.dll new file mode 100644 index 000000000..4291b6040 Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/RazorGenerator.MsBuild.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v1/RazorGenerator.Core.v1.dll b/Build/RazorGenerator.MsBuild/tools/v1/RazorGenerator.Core.v1.dll new file mode 100644 index 000000000..feb03b691 Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v1/RazorGenerator.Core.v1.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v1/System.Web.Mvc.dll b/Build/RazorGenerator.MsBuild/tools/v1/System.Web.Mvc.dll new file mode 100644 index 000000000..eed0d994a Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v1/System.Web.Mvc.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v1/System.Web.Razor.dll b/Build/RazorGenerator.MsBuild/tools/v1/System.Web.Razor.dll new file mode 100644 index 000000000..cd950e6d1 Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v1/System.Web.Razor.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v1/System.Web.WebPages.Razor.dll b/Build/RazorGenerator.MsBuild/tools/v1/System.Web.WebPages.Razor.dll new file mode 100644 index 000000000..9846dd3fc Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v1/System.Web.WebPages.Razor.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v1/System.Web.WebPages.dll b/Build/RazorGenerator.MsBuild/tools/v1/System.Web.WebPages.dll new file mode 100644 index 000000000..9fea01285 Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v1/System.Web.WebPages.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v2/RazorGenerator.Core.V2.dll b/Build/RazorGenerator.MsBuild/tools/v2/RazorGenerator.Core.V2.dll new file mode 100644 index 000000000..0add35c69 Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v2/RazorGenerator.Core.V2.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v2/System.Web.Mvc.dll b/Build/RazorGenerator.MsBuild/tools/v2/System.Web.Mvc.dll new file mode 100644 index 000000000..835f1b55d Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v2/System.Web.Mvc.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v2/System.Web.Razor.dll b/Build/RazorGenerator.MsBuild/tools/v2/System.Web.Razor.dll new file mode 100644 index 000000000..6a78bc6b7 Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v2/System.Web.Razor.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v2/System.Web.WebPages.Razor.dll b/Build/RazorGenerator.MsBuild/tools/v2/System.Web.WebPages.Razor.dll new file mode 100644 index 000000000..547c6e04e Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v2/System.Web.WebPages.Razor.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v2/System.Web.WebPages.dll b/Build/RazorGenerator.MsBuild/tools/v2/System.Web.WebPages.dll new file mode 100644 index 000000000..60e9abab5 Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v2/System.Web.WebPages.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v3/RazorGenerator.Core.V3.dll b/Build/RazorGenerator.MsBuild/tools/v3/RazorGenerator.Core.V3.dll new file mode 100644 index 000000000..45ef01d87 Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v3/RazorGenerator.Core.V3.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v3/System.Web.Mvc.dll b/Build/RazorGenerator.MsBuild/tools/v3/System.Web.Mvc.dll new file mode 100644 index 000000000..91257fc45 Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v3/System.Web.Mvc.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v3/System.Web.Razor.dll b/Build/RazorGenerator.MsBuild/tools/v3/System.Web.Razor.dll new file mode 100644 index 000000000..8a6fca74d Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v3/System.Web.Razor.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v3/System.Web.WebPages.Deployment.dll b/Build/RazorGenerator.MsBuild/tools/v3/System.Web.WebPages.Deployment.dll new file mode 100644 index 000000000..bb68d3c79 Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v3/System.Web.WebPages.Deployment.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v3/System.Web.WebPages.Razor.dll b/Build/RazorGenerator.MsBuild/tools/v3/System.Web.WebPages.Razor.dll new file mode 100644 index 000000000..adb7784fd Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v3/System.Web.WebPages.Razor.dll differ diff --git a/Build/RazorGenerator.MsBuild/tools/v3/System.Web.WebPages.dll b/Build/RazorGenerator.MsBuild/tools/v3/System.Web.WebPages.dll new file mode 100644 index 000000000..e894c065b Binary files /dev/null and b/Build/RazorGenerator.MsBuild/tools/v3/System.Web.WebPages.dll differ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..2a1a690e2 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1 @@ +To contribute to this project please submit your request in our feedback portal ([https://feedback.telerik.com/Project/153](https://feedback.telerik.com/Project/153)) with detailed description. This repo is a mirror of our codebase and represents the latest state of it without having control on it. For more details, read the following blog post ([http://www.sitefinity.com/blogs/peter-filipov/posts/peter-filipov-blog/2017/04/28/sitefinity-mvc-(feather)-source-code-repo-update](http://www.sitefinity.com/blogs/peter-filipov/posts/peter-filipov-blog/2017/04/28/sitefinity-mvc-(feather)-source-code-repo-update)). diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 000000000..3f1823f03 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,13 @@ + + + net48 + false + 0 + + + + + true + 3 + + \ No newline at end of file diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 000000000..e25482532 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,17 @@ + + + true + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Documentation/Files/DynamicModulesRegenerator.zip b/Documentation/Files/DynamicModulesRegenerator.zip new file mode 100644 index 000000000..6941a1e75 Binary files /dev/null and b/Documentation/Files/DynamicModulesRegenerator.zip differ diff --git a/Documentation/Images/AddressFieldCustomizedView.JPG b/Documentation/Images/AddressFieldCustomizedView.JPG new file mode 100644 index 000000000..f480fef35 Binary files /dev/null and b/Documentation/Images/AddressFieldCustomizedView.JPG differ diff --git a/Documentation/Images/CitiesDesigner.JPG b/Documentation/Images/CitiesDesigner.JPG new file mode 100644 index 000000000..4a7d05090 Binary files /dev/null and b/Documentation/Images/CitiesDesigner.JPG differ diff --git a/Documentation/Images/CitiesMVC.JPG b/Documentation/Images/CitiesMVC.JPG new file mode 100644 index 000000000..a0d26defb Binary files /dev/null and b/Documentation/Images/CitiesMVC.JPG differ diff --git a/Documentation/Images/CityDetailView.JPG b/Documentation/Images/CityDetailView.JPG new file mode 100644 index 000000000..87a97229f Binary files /dev/null and b/Documentation/Images/CityDetailView.JPG differ diff --git a/Documentation/Images/CityGuideRelatedData.JPG b/Documentation/Images/CityGuideRelatedData.JPG new file mode 100644 index 000000000..5b167ba7f Binary files /dev/null and b/Documentation/Images/CityGuideRelatedData.JPG differ diff --git a/Documentation/Images/HighlightedCountries.JPG b/Documentation/Images/HighlightedCountries.JPG new file mode 100644 index 000000000..136caeea1 Binary files /dev/null and b/Documentation/Images/HighlightedCountries.JPG differ diff --git a/Documentation/Images/MapppingTemplatesInDesigner.JPG b/Documentation/Images/MapppingTemplatesInDesigner.JPG new file mode 100644 index 000000000..b3da4446a Binary files /dev/null and b/Documentation/Images/MapppingTemplatesInDesigner.JPG differ diff --git a/Documentation/Images/SharedContent.JPG b/Documentation/Images/SharedContent.JPG new file mode 100644 index 000000000..8ea03ddf3 Binary files /dev/null and b/Documentation/Images/SharedContent.JPG differ diff --git a/Documentation/Images/SiteSelector.png b/Documentation/Images/SiteSelector.png new file mode 100644 index 000000000..93a92cfcd Binary files /dev/null and b/Documentation/Images/SiteSelector.png differ diff --git a/Documentation/Images/TimeToNow.JPG b/Documentation/Images/TimeToNow.JPG new file mode 100644 index 000000000..1f39530c3 Binary files /dev/null and b/Documentation/Images/TimeToNow.JPG differ diff --git a/Documentation/Images/UpdateCTWidgets.png b/Documentation/Images/UpdateCTWidgets.png new file mode 100644 index 000000000..e89deabe6 Binary files /dev/null and b/Documentation/Images/UpdateCTWidgets.png differ diff --git a/Documentation/Images/UseSharedOption.JPG b/Documentation/Images/UseSharedOption.JPG new file mode 100644 index 000000000..e3103148a Binary files /dev/null and b/Documentation/Images/UseSharedOption.JPG differ diff --git a/Documentation/Images/categoriesSelector.JPG b/Documentation/Images/categoriesSelector.JPG new file mode 100644 index 000000000..11a9748d3 Binary files /dev/null and b/Documentation/Images/categoriesSelector.JPG differ diff --git a/Documentation/Images/changeDynamicTemplate.JPG b/Documentation/Images/changeDynamicTemplate.JPG new file mode 100644 index 000000000..8e27061a0 Binary files /dev/null and b/Documentation/Images/changeDynamicTemplate.JPG differ diff --git a/Documentation/Images/contentBlockInsertImage.JPG b/Documentation/Images/contentBlockInsertImage.JPG new file mode 100644 index 000000000..cf8bd05eb Binary files /dev/null and b/Documentation/Images/contentBlockInsertImage.JPG differ diff --git a/Documentation/Images/customDynamicDesignerView2.JPG b/Documentation/Images/customDynamicDesignerView2.JPG new file mode 100644 index 000000000..d56bba2a9 Binary files /dev/null and b/Documentation/Images/customDynamicDesignerView2.JPG differ diff --git a/Documentation/Images/customRange.JPG b/Documentation/Images/customRange.JPG new file mode 100644 index 000000000..eecbb9960 Binary files /dev/null and b/Documentation/Images/customRange.JPG differ diff --git a/Documentation/Images/dateTimeSelector (1).JPG b/Documentation/Images/dateTimeSelector (1).JPG new file mode 100644 index 000000000..2c6356d7e Binary files /dev/null and b/Documentation/Images/dateTimeSelector (1).JPG differ diff --git a/Documentation/Images/dateTimeSelector.JPG b/Documentation/Images/dateTimeSelector.JPG new file mode 100644 index 000000000..2c6356d7e Binary files /dev/null and b/Documentation/Images/dateTimeSelector.JPG differ diff --git a/Documentation/Images/dateTimeSelectorDisplayText.JPG b/Documentation/Images/dateTimeSelectorDisplayText.JPG new file mode 100644 index 000000000..ce15c87f8 Binary files /dev/null and b/Documentation/Images/dateTimeSelectorDisplayText.JPG differ diff --git a/Documentation/Images/datetimePicker.JPG b/Documentation/Images/datetimePicker.JPG new file mode 100644 index 000000000..dd72ad77f Binary files /dev/null and b/Documentation/Images/datetimePicker.JPG differ diff --git a/Documentation/Images/dynamicItemsSelector.JPG b/Documentation/Images/dynamicItemsSelector.JPG new file mode 100644 index 000000000..895e2fc4a Binary files /dev/null and b/Documentation/Images/dynamicItemsSelector.JPG differ diff --git a/Documentation/Images/multipleSelection.JPG b/Documentation/Images/multipleSelection.JPG new file mode 100644 index 000000000..c85e9c3df Binary files /dev/null and b/Documentation/Images/multipleSelection.JPG differ diff --git a/Documentation/Images/multipleSelection2.JPG b/Documentation/Images/multipleSelection2.JPG new file mode 100644 index 000000000..767177e7b Binary files /dev/null and b/Documentation/Images/multipleSelection2.JPG differ diff --git a/Documentation/Images/newsSelector.JPG b/Documentation/Images/newsSelector.JPG new file mode 100644 index 000000000..99a8ed3ed Binary files /dev/null and b/Documentation/Images/newsSelector.JPG differ diff --git a/Documentation/Images/pageSelector.JPG b/Documentation/Images/pageSelector.JPG new file mode 100644 index 000000000..10674bb1d Binary files /dev/null and b/Documentation/Images/pageSelector.JPG differ diff --git a/Documentation/Images/relatedNews.JPG b/Documentation/Images/relatedNews.JPG new file mode 100644 index 000000000..889eda26c Binary files /dev/null and b/Documentation/Images/relatedNews.JPG differ diff --git a/Documentation/Images/reorderItems.JPG b/Documentation/Images/reorderItems.JPG new file mode 100644 index 000000000..3c8c4fb86 Binary files /dev/null and b/Documentation/Images/reorderItems.JPG differ diff --git a/Documentation/Images/tagsSelector.JPG b/Documentation/Images/tagsSelector.JPG new file mode 100644 index 000000000..e1a1fd30c Binary files /dev/null and b/Documentation/Images/tagsSelector.JPG differ diff --git a/Feather.sln b/Feather.sln index 60f437cae..5bde174c4 100644 --- a/Feather.sln +++ b/Feather.sln @@ -1,52 +1,11 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.30501.0 +# Visual Studio Version 17 +VisualStudioVersion = 17.4.33205.214 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telerik.Sitefinity.Frontend", "Telerik.Sitefinity.Frontend\Telerik.Sitefinity.Frontend.csproj", "{17ED04C3-0AB9-4055-9908-6C70720DAF77}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Telerik.Sitefinity.Frontend", "Telerik.Sitefinity.Frontend\Telerik.Sitefinity.Frontend.csproj", "{17ED04C3-0AB9-4055-9908-6C70720DAF77}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E3E1F3A5-2C9C-4223-ADBC-86904842C274}" - ProjectSection(SolutionItems) = preProject - Feather.ruleset = Feather.ruleset - Feather.vsmdi = Feather.vsmdi - Tests\TestSettings.testsettings = Tests\TestSettings.testsettings - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{F9885515-25E7-4C15-AE1B-032098DE1A90}" - ProjectSection(SolutionItems) = preProject - .nuget\NuGet.Config = .nuget\NuGet.Config - .nuget\NuGet.exe = .nuget\NuGet.exe - .nuget\NuGet.targets = .nuget\NuGet.targets - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "UITests", "UITests", "{EFF407A4-62ED-4B78-9573-7F65D70482C6}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SetupScripts", "SetupScripts", "{C9DF549F-1595-4163-B5CE-AFAB8F4048BB}" - ProjectSection(SolutionItems) = preProject - SetupScripts\Cleanup.bat = SetupScripts\Cleanup.bat - SetupScripts\Cleanup.ps1 = SetupScripts\Cleanup.ps1 - SetupScripts\FeatherSetup.ps1 = SetupScripts\FeatherSetup.ps1 - SetupScripts\Functions.ps1 = SetupScripts\Functions.ps1 - SetupScripts\IIS.ps1 = SetupScripts\IIS.ps1 - SetupScripts\Setup.bat = SetupScripts\Setup.bat - SetupScripts\Setup.ps1 = SetupScripts\Setup.ps1 - SetupScripts\SitefinitySetup.ps1 = SetupScripts\SitefinitySetup.ps1 - SetupScripts\SQL.ps1 = SetupScripts\SQL.ps1 - SetupScripts\Variables.ps1 = SetupScripts\Variables.ps1 - SetupScripts\Variables.xml = SetupScripts\Variables.xml - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{D7E812B2-E16E-4B90-9EF8-1C5F9F907E96}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telerik.Sitefinity.Frontend.ClientTest", "Tests\Telerik.Sitefinity.Frontend.ClientTest\Telerik.Sitefinity.Frontend.ClientTest.csproj", "{889A8B70-2B62-472A-AB7C-33CA9A7F48A0}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telerik.Sitefinity.Frontend.TestIntegration", "Tests\Telerik.Sitefinity.Frontend.TestIntegration\Telerik.Sitefinity.Frontend.TestIntegration.csproj", "{49B06F58-0510-4279-B6F1-90F23AB3768D}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telerik.Sitefinity.Frontend.TestUtilities", "Tests\Telerik.Sitefinity.Frontend.TestUtilities\Telerik.Sitefinity.Frontend.TestUtilities.csproj", "{1C663AB5-AEBC-41B5-A861-F635C37DAB47}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telerik.Sitefinity.Frontend.TestUI.Arrangements", "Tests\Telerik.Sitefinity.Frontend.TestUI.Arrangements\Telerik.Sitefinity.Frontend.TestUI.Arrangements.csproj", "{637A9A4D-A6D1-4C84-9A00-58AA440C2D58}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telerik.Sitefinity.Frontend.TestUnit", "Tests\Telerik.Sitefinity.Frontend.TestUnit\Telerik.Sitefinity.Frontend.TestUnit.csproj", "{D607959E-5DE3-43B9-8731-C22E495FCEF7}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Telerik.Sitefinity.Frontend.Data", "Telerik.Sitefinity.Frontend.Data\Telerik.Sitefinity.Frontend.Data.csproj", "{A9C3B088-8C44-4F0A-93E8-82FDB99A4205}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -58,38 +17,15 @@ Global {17ED04C3-0AB9-4055-9908-6C70720DAF77}.Debug|Any CPU.Build.0 = Debug|Any CPU {17ED04C3-0AB9-4055-9908-6C70720DAF77}.Release|Any CPU.ActiveCfg = Release|Any CPU {17ED04C3-0AB9-4055-9908-6C70720DAF77}.Release|Any CPU.Build.0 = Release|Any CPU - {889A8B70-2B62-472A-AB7C-33CA9A7F48A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {889A8B70-2B62-472A-AB7C-33CA9A7F48A0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {889A8B70-2B62-472A-AB7C-33CA9A7F48A0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {889A8B70-2B62-472A-AB7C-33CA9A7F48A0}.Release|Any CPU.Build.0 = Release|Any CPU - {49B06F58-0510-4279-B6F1-90F23AB3768D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {49B06F58-0510-4279-B6F1-90F23AB3768D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {49B06F58-0510-4279-B6F1-90F23AB3768D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {49B06F58-0510-4279-B6F1-90F23AB3768D}.Release|Any CPU.Build.0 = Release|Any CPU - {1C663AB5-AEBC-41B5-A861-F635C37DAB47}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {1C663AB5-AEBC-41B5-A861-F635C37DAB47}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1C663AB5-AEBC-41B5-A861-F635C37DAB47}.Release|Any CPU.ActiveCfg = Release|Any CPU - {1C663AB5-AEBC-41B5-A861-F635C37DAB47}.Release|Any CPU.Build.0 = Release|Any CPU - {637A9A4D-A6D1-4C84-9A00-58AA440C2D58}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {637A9A4D-A6D1-4C84-9A00-58AA440C2D58}.Debug|Any CPU.Build.0 = Debug|Any CPU - {637A9A4D-A6D1-4C84-9A00-58AA440C2D58}.Release|Any CPU.ActiveCfg = Release|Any CPU - {637A9A4D-A6D1-4C84-9A00-58AA440C2D58}.Release|Any CPU.Build.0 = Release|Any CPU - {D607959E-5DE3-43B9-8731-C22E495FCEF7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D607959E-5DE3-43B9-8731-C22E495FCEF7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D607959E-5DE3-43B9-8731-C22E495FCEF7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D607959E-5DE3-43B9-8731-C22E495FCEF7}.Release|Any CPU.Build.0 = Release|Any CPU + {A9C3B088-8C44-4F0A-93E8-82FDB99A4205}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A9C3B088-8C44-4F0A-93E8-82FDB99A4205}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A9C3B088-8C44-4F0A-93E8-82FDB99A4205}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A9C3B088-8C44-4F0A-93E8-82FDB99A4205}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {889A8B70-2B62-472A-AB7C-33CA9A7F48A0} = {D7E812B2-E16E-4B90-9EF8-1C5F9F907E96} - {49B06F58-0510-4279-B6F1-90F23AB3768D} = {D7E812B2-E16E-4B90-9EF8-1C5F9F907E96} - {1C663AB5-AEBC-41B5-A861-F635C37DAB47} = {D7E812B2-E16E-4B90-9EF8-1C5F9F907E96} - {637A9A4D-A6D1-4C84-9A00-58AA440C2D58} = {EFF407A4-62ED-4B78-9573-7F65D70482C6} - {D607959E-5DE3-43B9-8731-C22E495FCEF7} = {D7E812B2-E16E-4B90-9EF8-1C5F9F907E96} - EndGlobalSection - GlobalSection(TestCaseManagementSettings) = postSolution - CategoryFile = Feather.vsmdi + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {BDAC553B-9127-44F3-B607-F1DBADC730B6} EndGlobalSection EndGlobal diff --git a/Feather.vsmdi b/Feather.vsmdi deleted file mode 100644 index c211b16c2..000000000 --- a/Feather.vsmdi +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/FxCop/CustomDictionary.xml b/FxCop/CustomDictionary.xml deleted file mode 100644 index 1fde60202..000000000 --- a/FxCop/CustomDictionary.xml +++ /dev/null @@ -1,586 +0,0 @@ - - - - - - cb - ch - csc - elem - gt - idx - img - lg - multi - num - ps - pw - scp - si - sig - tk - tw - val - meth - - - - - - mvc - Thumbler - Reddit - SiteMapNode - ContentBlock - HttpContext - ControllerContext - Params - Param - Unshare - Js - Sf - Img - Div - Configs - Infos - RouteData - - - - Dropbox - Everlive - Lucene - Crontab - Impl - Marketo - Telerik - Sitefinity - frontend - backend - - - accessor - accessors - acos - aes - ansi - aptca - arg - args - asin - asm - aspx - async - atan - baml - bcl - bidi - bindable - bitrate - blittable - blog - bool - bootstrapper - bootstrappers - browsable - cacheability - callee - callees - canonicalize - cdecl - cdo - chtml - cim - cloneable - clr - clr's - cls - clsid - clsids - cmd - cmdlet - cmdlets - cng - comparand - concat - config - const - contravariant - cookieless - cos - crm - css - csv - cyclomatic - db - debuggable - decommission - deformatter - delegator - dequeue - dereferenced - des - deserialization - deserialize - deserialized - deserializing - dev - dhcp - diffie - discardable - dll - dns - documentable - dsa - dsig - dtd - dtds - eg - em - email - emails - emf - encodable - endian - enqueue - enum - enums - equatable - etc - eventing - expando - finalizer - finalizers - fixup - fixups - formattable - func - fx - fxcop - gac - goto - guid - guids - hashtable - hashtables - hashtable's - hdc - hijri - hmac - href - idn - ie - iis - il - ime - init - initializer - initializers - inlining - int - interop - intrinsics - ipv - iterator - iterators - jit - json - lcid - lcids - ldap - linq - localhost - loopback - loopbacks - mapper - mappers - marshaler - marshalers - mdi - mergable - misc - miscased - monitorable - mscoree - mscorlib - msdn - msh - multiline - multipanel - multipanels - multiview - multiviews - mutator - mutators - mutex - mutexes - ndpsec - nls - nop - ntfs - ntlm - nullable - numerics - obj - odbc - oks - overridable - pageable - partitioner - partitioners - parameterless - pdb - persister - persistable - playlist - pragma - prepend - prog - ptr - queryable - ras - rect - rects - recurse - refactor - reg - regex - remoted - remoting - representable - res - resolver - resolvers - rethrow - rethrows - rijndael - rpc - rsa - rtc - rtm - runspace - rva - sdl - saml - sdk - searchspace - searchspaces - seekable - seq - serializable - serializer - serializers - silverlight - smtp - specifier - specifiers - spline - sortable - sql - sddl - ssl - sta - stickies - struct - structs - stylesheet - subaddress - subaddresses - subclass - subclasses - subdirectories - subdirectory - subexpression - subexpressions - subitem - subitems - subkey - subkeys - submenu - submenus - subpath - subpaths - subsegment - subsegments - subtree - subtrees - tcp - templated - thunk - thunks - tlb - tuple - tuples - udp - udt - ui - unbox - unboxing - unc - uncategorize - uncheck - unchecked - unchecking - unescape - unindent - uninitialize - uninitialized - uninstantiated - unmaintainable - unmarshal - unregister - unregistering - unregisters - unregistration - unrepresentable - unterminated - untrusted - uri - uris - url - urls - utc - utf - validator - var - vs - vsa - virtualize - virtualizes - virtualizing - visualizer - visualizers - weblog - wiki - wcf - wmf - wmi - wml - wpf - wql - wsdl - xaml - xhtml - xmlns - xor - xrml - xsd - xsi - xsl - xslt - - - - complus - cancelled - cancelling - cancelation - cancelations - indices - login - logout - signon - signoff - writeable - cant - arent - dont - doesnt - didnt - couldnt - wouldnt - shouldnt - wont - havent - hasnt - hadnt - isnt - wasnt - werent - flag - flags - - - - databind - databinds - databinding - datastore - datastores - dataset - datasets - textbox - textboxes - codepage - codepages - checkbox - checkboxes - pushbutton - pushbuttons - dropdown - dropdowns - toolbar - toolbars - scrollbar - scrollbars - bitflag - bitflags - filename - filenames - fileserver - fileservers - username - usernames - hostname - hostnames - fieldname - fieldnames - pathname - pathnames - assemblyname - assemblynames - whitespace - whitespaces - logon - logons - logoff - logoffs - signin - signins - signout - signouts - stylesheet - stylesheets - frontend - frontends - backend - backends - sitemap - sitemaps - datatype - datatypes - designtime - designtimes - readonly - truetype - netbios - autodetect - autodetects - autoscroll - autoscrolls - autocomplete - autocompletes - autosave - autosaves - javascript - jscript - voiceview - appletalk - mapinfo - newline - newlines - qword - qwords - keyset - keysets - codebase - codebases - gridline - gridlines - opcode - opcodes - fxcop - - - - onset - inset - byname - setout - countertype - editor - longtime - drawstring - hookup - cleanup - breakout - setline - maybe - nods - classis - gettable - inform - beset - settable - standalone - threadlike - infield - infields - meantime - mackey - jscript - ipv - tooltip - tooltips - indispose - webhost - webhosts - preshow - superfast - goto - endpoint - strongbox - nonbreaking - nonliteral - insource - charset - timespan - - - - - Pv - Pi - Na - NESW - NWSE - Op - - - diff --git a/FxCop/Feather.ruleset b/FxCop/Feather.ruleset deleted file mode 100644 index 8d25e15dd..000000000 --- a/FxCop/Feather.ruleset +++ /dev/null @@ -1,379 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Gruntfile.js b/Gruntfile.js deleted file mode 100644 index 6a3ce7ae9..000000000 --- a/Gruntfile.js +++ /dev/null @@ -1,76 +0,0 @@ -module.exports = function (grunt) { - 'use strict'; - - //Project Configuration - grunt.initConfig({ - - pkg: grunt.file.readJSON('package.json'), - - jshint: { - //define the files to lint - files: ['gruntfile.js', - 'Telerik.Sitefinity.Frontend/Designers/Scripts/*.js', - 'Telerik.Sitefinity.Frontend/MVC/Scripts/*.js', - 'Telerik.Sitefinity.Frontend/MVC/Scripts/Designer/*.js', - 'Telerik.Sitefinity.Frontend/Selectors/*.js', - 'Telerik.Sitefinity.Frontend/Services/*.js' - ] - }, - - jasmine: { - unit:{ - src: ['Tests/Telerik.Sitefinity.Frontend.ClientTest/helpers/jquery-1.8.3.min.js', - 'Tests/Telerik.Sitefinity.Frontend.ClientTest/helpers/angular.js', - 'Tests/Telerik.Sitefinity.Frontend.ClientTest/helpers/angular-resource.js', - 'Tests/Telerik.Sitefinity.Frontend.ClientTest/helpers/angular-route.js', - 'Tests/Telerik.Sitefinity.Frontend.ClientTest/helpers/angular-mocks.js', - 'Tests/Telerik.Sitefinity.Frontend.ClientTest/templates.js', - 'Telerik.Sitefinity.Frontend/MVC/Scripts/Bootstrap/js/*.js', - 'Telerik.Sitefinity.Frontend/Designers/Scripts/*.js', - 'Telerik.Sitefinity.Frontend/MVC/Scripts/Designer/*.js', - 'Telerik.Sitefinity.Frontend/MVC/Scripts/*.js', - 'Telerik.Sitefinity.Frontend/Services/services.js', - 'Telerik.Sitefinity.Frontend/Services/generic-data-service.js', - 'Telerik.Sitefinity.Frontend/Selectors/selectors.js', - 'Telerik.Sitefinity.Frontend/Selectors/content-selector.js', - '!Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/**', - '!Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor.js', - 'Tests/Telerik.Sitefinity.Frontend.ClientTest/helpers/mocks/*.js'], - options: { - specs: ['Tests/Telerik.Sitefinity.Frontend.ClientTest/unit/**/*.js'], - template: require('grunt-template-jasmine-istanbul'), - templateOptions: { - coverage: 'Tests/Telerik.Sitefinity.Frontend.ClientTest/coverage/coverage.json', - report: [ - {type: 'html', options: {dir: 'Tests/Telerik.Sitefinity.Frontend.ClientTest/coverage'}}, - {type: 'cobertura', options: {dir: 'Tests/Telerik.Sitefinity.Frontend.ClientTest/coverage/cobertura'}}, - {type: 'text-summary'} - ] - } - } - } - }, - - //Converts directive's external html templates into javascript strings and stores them in the Angular's $templateCache service. - html2js: { - options: { - singleModule: true, - module: 'templates', - base: 'Telerik.Sitefinity.Frontend' - }, - main: { - src: ['Telerik.Sitefinity.Frontend/Selectors/*.html'], - dest: 'Tests/Telerik.Sitefinity.Frontend.ClientTest/templates.js' - }, - }, - }); - - //Load the needed plugins - grunt.loadNpmTasks('grunt-contrib-jshint'); - grunt.loadNpmTasks('grunt-contrib-jasmine'); - grunt.loadNpmTasks('grunt-html2js'); - - //Default task(s) - grunt.registerTask('default', ['jshint','html2js', 'jasmine']); - -}; \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md index 83f7ad8d5..edbff986d 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,9 +1,12 @@ -This project has been released under the Apache License, version 2.0, the text of which is included below. This license applies ONLY to the project-specific source of each repository and does not extend to Telerik Sitefinity CMS itself, or any other 3rd party libraries used in a repository. For licensing information about Telerik Sitefinity CMS, see the [License Agreements page](http://www.sitefinity.com/purchase/license-agreement) at [Sitefinity.com](http://www.sitefinity.com/). -Copyright © 2014 Telerik + +This project has been released under the Apache License, version 2.0, the text of which is included below. This license applies ONLY to the source of this repository and does not extend to any other Sitefinity distribution or variant, or any other 3rd party libraries used in a repository. For licensing information about Sitefinity, see https://www.progress.com/legal/license-agreements/sitefinity/license-agreement. + +Copyright © 2018 Progress Software Corporation and/or one of its subsidiaries or affiliates. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + diff --git a/NuGet.Config b/NuGet.Config new file mode 100644 index 000000000..0970df1f5 --- /dev/null +++ b/NuGet.Config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index 6d75f2b39..3c8c4b347 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,13 @@ The Feather Project ======= -This repository contains the core infrastructure related to the [Feather project](http://projectfeather.sitefinity.com). Note that the current implementation is not final, that it is a subject to changes as well as breaking API changes and should not be used in production. +This repository contains the core infrastructure related to [Project Feather](http://projectfeather.sitefinity.com). + + +| Test | Status | +|----|----| +| Unit | [![Build Status](https://feather-ci.sitefinity.com/buildStatus/icon?job=Master_FeatherUnitTests)](https://feather-ci.sitefinity.com/job/Master_FeatherUnitTests/) | +| Integration | [![Build Status](https://feather-ci.sitefinity.com/buildStatus/icon?job=Master_FeatherIntegrationTests)](https://feather-ci.sitefinity.com/job/Master_FeatherIntegrationTests/) | # Related Repositories @@ -11,53 +17,38 @@ This repository contains the core infrastructure related to the [Feather project [feather-samples](https://github.com/Sitefinity/feather-samples) - This repository contains code samples related to the Feather project. -# Documentation - -[Getting Started](https://github.com/Sitefinity/feather/wiki/Getting-Started) - -[FAQ](https://github.com/Sitefinity/feather/wiki/FAQ) - -[Create a MVC List widget](https://github.com/Sitefinity/feather/wiki/Create-a-MVC-List-widget) - -[Change MVC widget templates](https://github.com/Sitefinity/feather/wiki/Change-MVC-widget-templates) - -[Create a layout file](https://github.com/Sitefinity/feather/wiki/Create-a-layout-file) - -[Feather resource packages](https://github.com/Sitefinity/feather/wiki/Feather-resource-packages) - -[Page templates based on layout files with Feather](https://github.com/Sitefinity/feather/wiki/Page-templates-based-on-layout-files-with-Feather) +# Sitefinity compatibility + +| Feather version | Sitefinity version | +|----|----| +| v.1.9.800.0 - latest | 10.0.6400.0 to 10.0.9999 | +| v.1.7.600.0 - 1.7.690.0 | 9.2.6200.0 to 9.2.9999 | +| v.1.6.500.0 - 1.6.560.0 | 9.1.6100.0 to 9.1.9999 | +| v.1.5.470.0 - 1.5.490.0 | 9.0.6000.0 to 9.0.9999 | +| v.1.4.360.0 - 1.4.460.0 | 8.2.5900.0 to 8.2.9999 | +| v.1.3.300.1 - 1.3.350.0 | 8.1.5800.0 to 8.1.9999 | +| v.1.2.120.0 - 1.2.290.1 | 8.0.5700.0 to 8.0.9999 | +| v.1.1.20.3 - 1.1.110.0 | 7.3.5600.0 to 7.3.9999 | +| v.1.0.0.0 - 1.0.10.2 | 7.2.5300.0 to 7.2.9999 | +| v.0.5.1000.4 | 7.1.5208.0 to 7.1.9999 | +| v.0.4.1000.2 | 7.1.5200.0 to 7.1.9999 | +| v0.1.1000.1 - v.0.3.1000.4 | 7.0.5100.0 to 7.0.9999 | -[Refer to resources inside MVC views](https://github.com/Sitefinity/feather/wiki/Refer-to-resources-inside-MVC-views) - -[VirtualFile structure explained](https://github.com/Sitefinity/feather/wiki/VirtualFile-structure-explained) - -[Create a “Hello World” MVC widget in a separate assembly](https://github.com/Sitefinity/feather/wiki/Create-a-%E2%80%9CHello-World%E2%80%9D-MVC-widget-in-a-separate-assembly) - -[Create a custom designer view](https://github.com/Sitefinity/feather/wiki/Create-a-custom-designer-view) - -[Extend widget designer with additional client logic](https://github.com/Sitefinity/feather/wiki/Extend-widget-designer-with-additional-client-logic) - -[Add custom commands for editing widget with Feather ](https://github.com/Sitefinity/feather/wiki/Add-custom-commands-for-editing-widget-with-Feather) - -[Use the old WebForms widget designer with Feather widgets](https://github.com/Sitefinity/feather/wiki/Use-the-old-WebForms-widget-designer-with-Feather-widgets) - -[Use a custom widget designer window](https://github.com/Sitefinity/feather/wiki/Use-a-custom-widget-designer-window) - -[Overriding the default widget designer buttons] (https://github.com/Sitefinity/feather/wiki/Overriding-the-default-widget-designer-buttons) +# Documentation -[Pass server data to widget designer views ] (https://github.com/Sitefinity/feather/wiki/Pass-server-data-to-widget-designer-views) +[Getting Started](https://github.com/Sitefinity/feather/wiki/getting-started) - Follow the intallation installation to get started with Feather -[Customize properties displayed inside the property editor ] (https://github.com/Sitefinity/feather/wiki/Customize-properties-displayed-inside-the-property-editor) +[Upgrade Instructions](https://github.com/Sitefinity/feather/wiki/upgrade-instructions) - Upgrade your existing Feather projects following this guide -[Use a single content item selector] (https://github.com/Sitefinity/feather/wiki/Use-a-single-content-item-selector) +[What's new](https://github.com/Sitefinity/feather/releases/latest) - See what's new in Feather -[Add related data to News widget] (https://github.com/Sitefinity/feather/wiki/Add-related-data-to-News-widget) +[Documentation Home](https://github.com/Sitefinity/feather/wiki) - See full project Feather documentation in the wiki # License Information This project has been released under the Apache License, version 2.0, the text of which is included below. This license applies ONLY to the project-specific source of each repository and does not extend to Telerik Sitefinity CMS itself, or any other 3rd party libraries used in a repository. For licensing information about Telerik Sitefinity CMS, see the [License Agreements page](http://www.sitefinity.com/purchase/license-agreement) at [Sitefinity.com](http://www.sitefinity.com/). -Copyright © 2014 Telerik +Copyright © 2005-2017 Telerik AD Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at diff --git a/Settings.StyleCop b/Settings.StyleCop deleted file mode 100644 index d00e52c87..000000000 --- a/Settings.StyleCop +++ /dev/null @@ -1,274 +0,0 @@ - - - - \..\Builds\StyleCop\StyleCop 4.7\ - - - flag - Sitemap - Sitefinity - Ninject - css - queryable - Guid - Unshare - parameterless - Json - - - - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - False - - - - - True - True - - - - - - - False - - - - - False - - - - - - - - - - False - - - - - - - - - - False - - - - - - - \ No newline at end of file diff --git a/SetupScripts/Cleanup.bat b/SetupScripts/Cleanup.bat deleted file mode 100644 index 2e63d0706..000000000 --- a/SetupScripts/Cleanup.bat +++ /dev/null @@ -1,3 +0,0 @@ -set logsDir="C:\Tests\Logs" -for /f %%a in ('%windir%\sysnative\WindowsPowerShell\v1.0\powershell.exe -Command "Get-Date -format yyyy_MM_dd__HH_mm_ss"') do set datetime=%%a -"%windir%\sysnative\WindowsPowerShell\v1.0\powershell.exe" -executionpolicy unrestricted -file Cleanup.ps1 > %logsDir%\%datetime%_Cleanup.log 2>%logsDir%\%datetime%_Cleanup_Error.log \ No newline at end of file diff --git a/SetupScripts/Cleanup.ps1 b/SetupScripts/Cleanup.ps1 deleted file mode 100644 index 931d65855..000000000 --- a/SetupScripts/Cleanup.ps1 +++ /dev/null @@ -1,25 +0,0 @@ -Import-Module WebAdministration - -$currentPath = Split-Path $script:MyInvocation.MyCommand.Path -$variables = Join-Path $currentPath "\Variables.ps1" -. $variables -. $functionsModule - -write-output "Restarting TestAgent process..." -try{ - $testAgentProcess = Get-Process QTAgentProcessUI - $testAgentProcess.Kill() - $testAgentProcess.WaitForExit() -}catch [Exception]{ -}finally{ - write-output "Cleaning test agent temp folders..." - Start-Sleep -s 5 - CleanDirectory $agentTempFolder - Start-Process -FilePath $testAgentExe - Remove-Item $aspNetTempFolder -Force -Recurse -ErrorAction Continue - write-output "TestAgent process started." -} - -write-output "Restarting WebApp pools..." -Restart-WebAppPool $appPollName -ErrorAction Continue -Restart-WebAppPool $secondAppPollName -ErrorAction Continue \ No newline at end of file diff --git a/SetupScripts/FeatherSetup.ps1 b/SetupScripts/FeatherSetup.ps1 deleted file mode 100644 index 91483d437..000000000 --- a/SetupScripts/FeatherSetup.ps1 +++ /dev/null @@ -1,74 +0,0 @@ -Import-Module WebAdministration - -$currentPath = Split-Path $script:MyInvocation.MyCommand.Path -$variables = Join-Path $currentPath "\Variables.ps1" -. $variables -. $iisModule - -$websiteConfigDir = $defaultWebsiteRootDirectory + "\App_Data\Sitefinity\Configuration" - -function UpdateSystemConfig -{ - $systemConfig = $websiteConfigDir+"\SystemConfig.config" - $doc = New-Object System.Xml.XmlDocument - $doc.Load($systemConfig) - $servicesNode = $doc.CreateElement("systemServices") - $addNode = $doc.CreateElement("add") - $addNode.SetAttribute("title","Telerik.Sitefinity.Frontend") - $addNode.SetAttribute("description","Telerik.Sitefinity.Frontend") - $addNode.SetAttribute("moduleId","00000000-0000-0000-0000-000000000000") - $addNode.SetAttribute("type","Telerik.Sitefinity.Frontend.FrontendService, Telerik.Sitefinity.Frontend") - $addNode.SetAttribute("startupType","OnApplicationStart") - $addNode.SetAttribute("name","Telerik.Sitefinity.Frontend") - $servicesNode.AppendChild($addNode) - $rootNode = $doc.SelectSingleNode("//systemConfig") - $rootNode.AppendChild($servicesNode) - $doc.Save($systemConfig) -} - -function InstallFeather($featherBinDirectory) -{ - Write-Output "----- Installing Feather ------" - - Write-Output "Deploying feather assemblies to '$websiteBinariesDirectory'..." - Get-ChildItem Telerik.Sitefinity.Frontend.dll -recurse -path $featherBinDirectory | Copy-Item -destination $websiteBinariesDirectory - Get-ChildItem Ninject.dll -recurse -path $featherBinDirectory | Copy-Item -destination $websiteBinariesDirectory - - Write-Output "Updating Sitefinity SystemConfig.config..." - UpdateSystemConfig - - Write-Output "Restarting $appPollName application pool..." - Restart-WebAppPool $appPollName -ErrorAction Continue - GetRequest $defaultWebsiteUrl - - Write-Output "----- Feather successfully installed ------" -} - -function InstallFeatherWidgets($featherWidgetsBinDirectory, $featherNavigationWidgetBinDirectory) -{ - Write-Output "Deploying feather widgets assembly to '$websiteBinariesDirectory'..." - Get-ChildItem ContentBlock.dll -recurse -path $featherWidgetsBinDirectory | Copy-Item -destination $websiteBinariesDirectory - Get-ChildItem Navigation.dll -recurse -path $featherNavigationWidgetBinDirectory | Copy-Item -destination $websiteBinariesDirectory - InstallFeather $featherBinDirectory -} - -function InstallFeatherPackages($featherPackagesDirectory) -{ - Write-Output "----- Create Resource Packages directory in SitefinityWebApp ------" - - $resourcePackagesFolder = $defaultWebsiteRootDirectory + "\ResourcePackages" - if(!(Test-Path -Path $resourcePackagesFolder )){ - New-Item -ItemType directory -Path $resourcePackagesFolder - } - - Write-Output "----- Copy packages ------" - Get-ChildItem Bootstrap -path $featherPackagesDirectory | Copy-Item -destination $resourcePackagesFolder -recurse - Get-ChildItem Foundation -path $featherPackagesDirectory | Copy-Item -destination $resourcePackagesFolder -recurse - Get-ChildItem SemanticUI -path $featherPackagesDirectory | Copy-Item -destination $resourcePackagesFolder -recurse - - Write-Output "Restarting $appPollName application pool..." - Restart-WebAppPool $appPollName -ErrorAction Continue - GetRequest $defaultWebsiteUrl - - Write-Output "----- Feather packages successfully installed ------" -} \ No newline at end of file diff --git a/SetupScripts/Functions.ps1 b/SetupScripts/Functions.ps1 deleted file mode 100644 index a1a1bc14d..000000000 --- a/SetupScripts/Functions.ps1 +++ /dev/null @@ -1,27 +0,0 @@ -Import-Module WebAdministration - -Function CleanDirectory($dir){ - Cmd /C "rmdir /S /Q $dir 2>NUL" -} - -function CleanWebsiteDirectory($dir, $retryCount, $appPollName) -{ - for ($i=1; $i -le $retryCount; $i++) - { - if(Test-Path $dir) - { - Restart-WebAppPool $appPollName - Start-Sleep -s 3 - CleanDirectory $dir - if($i -eq $retryCount) - { - $errorMsg = "Unable to clean "+ $dir +" directory..." - Throw New-Object System.Exception($errorMsg) - } - write-output "Cleaning $dir... [ Retry$i ]" - } else { - write-output "$dir cleaned successfully." - break - } - } -} \ No newline at end of file diff --git a/SetupScripts/IIS.ps1 b/SetupScripts/IIS.ps1 deleted file mode 100644 index 9459ee153..000000000 --- a/SetupScripts/IIS.ps1 +++ /dev/null @@ -1,46 +0,0 @@ -Import-Module WebAdministration - -function GetNextWebsiteId -{ - #There is issue for the first calling of Get-ChildItem method - try{ - (Get-ChildItem IIS:\Sites | foreach {$_.id} | sort -Descending | select -first 1) + 1 - }catch [Exception]{ - (Get-ChildItem IIS:\Sites | foreach {$_.id} | sort -Descending | select -first 1) + 1 - } -} - -function GetRequest($url) -{ - $request = [System.Net.WebRequest]::Create($url) - $request.Method = "GET" - $request.Timeout = 360000 - $request.AuthenticationLevel = "None" - return $request.GetResponse() -} - -function PostRequest($url) -{ - $request = [System.Net.WebRequest]::Create($url) - $request.Method = "POST" - $request.Timeout = 360000 - $request.ContentLength = 0 - $request.AuthenticationLevel = "None" - return $request.GetResponse() -} - -function DeleteAllSitesWithSameBinding($port) -{ - #There is issue for the first calling of Get-ChildItem method - try{ - $websites=Get-ChildItem IIS:\Sites | where-object {$_.bindings.collection.bindinginformation.Contains("*:"+$port+":")} - }catch [Exception]{ - $websites=Get-ChildItem IIS:\Sites | where-object {$_.bindings.collection.bindinginformation.Contains("*:"+$port+":")} - } - - foreach ($site in $websites) - { - write-output "Deleting $site.Name website from IIS." - Remove-Website -Name $site.Name - } -} \ No newline at end of file diff --git a/SetupScripts/SQL.ps1 b/SetupScripts/SQL.ps1 deleted file mode 100644 index d6e045fa8..000000000 --- a/SetupScripts/SQL.ps1 +++ /dev/null @@ -1,48 +0,0 @@ -[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null - -function EnsureDBDeleted($databaseServer, $dbName) -{ - # Ensure data base is deleted - write-output "Ensure data base is deleted" - $Server = New-Object Microsoft.SqlServer.Management.Smo.Server($databaseServer) - $DBObject = $Server.Databases[$dbName] - - #check database exists on server - if ($DBObject) - { - - Try - { - #instead of drop we will use KillDatabase - #KillDatabase drops all active connections before dropping the database. - write-output "Deleting $dbName database from SqlServer." - $Server.KillAllProcesses($dbName) - $Server.KillDatabase($dbName) - } - - Catch - { - write-output $_.Exception.Message - write-output $_.Exception.InnerException - write-output $_.Exception.Stack - write-output $_.Exception.GetBaseException().Message - write-output "username is:" $env:username - } - } -} - -function BackupDatabase($databaseServer, $dbName, $bakupFolder) -{ - New-Item -ItemType Directory -Path $bakupFolder -Force - $dbBakFullPath = $bakupFolder+"\" + $dbName +".bak" - SQLCMD.EXE -S $databaseServer -E -q "exit(BACKUP DATABASE [$dbName] TO DISK='$dbBakFullPath')" -} - -function RestoreDatabaseWithMove($databaseServer, $dbName, $restoredDbName, $dbLocation) -{ - $dbBakFullPath = $dbLocation+"\"+$dbName+".bak" - $dbDestinationFullPath = $dbLocation+"\"+$dbName+".mdf" - $logDestinationFullPath = $dbLocation+"\"+$dbName+"_log.ldf" - $logName = $dbName+'_log' - SQLCMD.EXE -S $databaseServer -E -q "exit(RESTORE DATABASE [$restoredDbName] FROM DISK='$dbBakFullPath' WITH MOVE '$dbName' TO '$dbDestinationFullPath', MOVE '$logName' TO '$logDestinationFullPath')" -} \ No newline at end of file diff --git a/SetupScripts/Setup.bat b/SetupScripts/Setup.bat deleted file mode 100644 index dbc619dc7..000000000 --- a/SetupScripts/Setup.bat +++ /dev/null @@ -1,4 +0,0 @@ -set logsDir="C:\Tests\Logs" -for /f %%a in ('%windir%\sysnative\WindowsPowerShell\v1.0\powershell.exe -Command "Get-Date -format yyyy_MM_dd__HH_mm_ss"') do set datetime=%%a -if not exist %logsDir% mkdir %logsDir% -"%windir%\sysnative\WindowsPowerShell\v1.0\powershell.exe" -executionpolicy unrestricted -file Setup.ps1 > %logsDir%\%datetime%_Setup.log 2>%logsDir%\%datetime%_Setup_Error.log \ No newline at end of file diff --git a/SetupScripts/Setup.ps1 b/SetupScripts/Setup.ps1 deleted file mode 100644 index a45f40338..000000000 --- a/SetupScripts/Setup.ps1 +++ /dev/null @@ -1,5 +0,0 @@ -$currentPath = Split-Path $script:MyInvocation.MyCommand.Path -$variables = Join-Path $currentPath "\Variables.ps1" - -. $variables -. $sitefinitySetup \ No newline at end of file diff --git a/SetupScripts/SitefinitySetup.ps1 b/SetupScripts/SitefinitySetup.ps1 deleted file mode 100644 index 2771e5632..000000000 --- a/SetupScripts/SitefinitySetup.ps1 +++ /dev/null @@ -1,73 +0,0 @@ -Import-Module WebAdministration -[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null -$currentPath = Split-Path $script:MyInvocation.MyCommand.Path -$variables = Join-Path $currentPath "\Variables.ps1" -. $variables -. $iisModule -. $sqlModule -. $functionsModule - -write-output "------- Installing Sitefinity --------" - -EnsureDBDeleted $databaseServer $databaseName - -DeleteAllSitesWithSameBinding $defaultWebsitePort - -write-output "Setting up Application pool..." - -Remove-WebAppPool $appPollName -ErrorAction continue - -New-WebAppPool $appPollName -Force - -Set-ItemProperty IIS:\AppPools\$appPollName managedRuntimeVersion v4.0 -Force - -#Setting application pool identity to NetworkService -Set-ItemProperty IIS:\AppPools\$appPollName processmodel.identityType -Value 2 - -write-output "Deploy SitefinityWebApp to test execution machine $machineName" - -if (Test-Path $defaultWebsiteRootDirectory){ - CleanWebsiteDirectory $defaultWebsiteRootDirectory 10 $appPollName -} - -write-output "Sitefinity deploying from $projectLocationShare..." - -Copy-Item -Path Microsoft.PowerShell.Core\FileSystem::$projectLocationShare $projectDeploymentDirectory -Recurse -ErrorAction stop - -write-output "Sitefinity successfully deployed." - - -function CopyTestAssemblies($workingDirectory, $destinationDirectory) -{ - write-output "Start copying test assemblies from $workingDirectory to $destinationDirectory." - Get-ChildItem *Test*.dll -recurse -path $workingDirectory | Copy-Item -destination $destinationDirectory -} - -function InstallSitefinity() -{ - $siteId = GetNextWebsiteId - write-output "Registering $siteName website with id $siteId in IIS." - New-WebSite -Id $siteId -Name $siteName -Port $defaultWebsitePort -HostHeader localhost -PhysicalPath $defaultWebsiteRootDirectory -ApplicationPool $appPollName -Force - Start-WebSite -Name $siteName - - write-output "Setting up Sitefinity..." - - $installed = $false - - while(!$installed){ - try{ - $response = GetRequest $defaultWebsiteUrl - if($response.StatusCode -eq "OK"){ - $installed = $true; - $response - } - }catch [Exception]{ - Restart-WebAppPool $appPollName -ErrorAction Continue - write-output "$_.Exception.Message" - $installed = $false - } - } - - write-output "----- Sitefinity successfully installed ------" -} - diff --git a/SetupScripts/SitefinitySetupWithoutInstall.ps1 b/SetupScripts/SitefinitySetupWithoutInstall.ps1 deleted file mode 100644 index 8ec0c4a8d..000000000 --- a/SetupScripts/SitefinitySetupWithoutInstall.ps1 +++ /dev/null @@ -1,29 +0,0 @@ -Import-Module WebAdministration -[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null -$currentPath = Split-Path $script:MyInvocation.MyCommand.Path -$variables = Join-Path $currentPath "\Variables.ps1" -. $variables -. $iisModule -. $sqlModule -. $functionsModule - -write-output "------- Installing Sitefinity --------" - -if (Test-Path $defaultWebsiteRootDirectory){ - CleanWebsiteDirectory $defaultWebsiteRootDirectory 10 $appPollName -} - -write-output "Sitefinity deploying from $projectLocationShare..." - -Copy-Item -Path Microsoft.PowerShell.Core\FileSystem::$projectLocationShare $projectDeploymentDirectory -Recurse -ErrorAction stop - -write-output "Sitefinity successfully deployed." - - -function CopyTestAssemblies($workingDirectory, $destinationDirectory) -{ - write-output "Start copying test assemblies from $workingDirectory to $destinationDirectory." - Get-ChildItem *Test*.dll -recurse -path $workingDirectory | Copy-Item -destination $destinationDirectory -} - -write-output "------- Sitefinity Installed --------" diff --git a/SetupScripts/Variables.ps1 b/SetupScripts/Variables.ps1 deleted file mode 100644 index 27f53da14..000000000 --- a/SetupScripts/Variables.ps1 +++ /dev/null @@ -1,53 +0,0 @@ -$machineName = gc env:computername -$currentPath = Split-Path $script:MyInvocation.MyCommand.Path - -$doc = New-Object System.Xml.XmlDocument -$doc.Load($currentPath + "\Variables.xml") - - -#Modules -$iisModule = Join-Path $currentPath "\IIS.ps1" -$sqlModule = Join-Path $currentPath "\SQL.ps1" -$functionsModule = Join-Path $currentPath "\Functions.ps1" -$sitefinitySetup = Join-Path $currentPath "\SitefinitySetup.ps1" -$analyticsSetup = Join-Path $currentPath "\EnableAnalytics.ps1" -$multilingualSetup = Join-Path $currentPath "\Setup_Multilingual.ps1" -$siteSyncSetup = Join-Path $currentPath "\Setup_SiteSync.ps1" - -#Website setup properties - -$defaultWebsiteUrl = $doc.SelectSingleNode("//variables/defaultWebsiteUrl").InnerText -$defaultWebsitePort = $doc.SelectSingleNode("//variables/defaultWebsitePort").InnerText -$secondWebsiteUrl = $doc.SelectSingleNode("//variables/secondWebsiteUrl").InnerText -$secondWebsitePort = $doc.SelectSingleNode("//variables/secondWebsitePort").InnerText -$siteName = $doc.SelectSingleNode("//variables/siteName").InnerText -$secondSiteName = $doc.SelectSingleNode("//variables/secondSiteName").InnerText -$projectLocationShare = $doc.SelectSingleNode("//variables/projectLocationShare").InnerText -$projectDeploymentDirectory = $doc.SelectSingleNode("//variables/projectDeploymentDirectory").InnerText -$defaultWebsiteRootDirectory = $doc.SelectSingleNode("//variables/defaultWebsiteRootDirectory").InnerText -$secondWebsiteRootDirectory = $doc.SelectSingleNode("//variables/secondWebsiteRootDirectory").InnerText -$databaseServer = $doc.SelectSingleNode("//variables/databaseServer").InnerText -$analyticsEnabled = $doc.SelectSingleNode("//variables/analyticsEnabled").InnerText -$multilingualEnabled = $doc.SelectSingleNode("//variables/multilingualEnabled").InnerText -$siteSyncEnabled = $doc.SelectSingleNode("//variables/siteSyncEnabled").InnerText - -$appPollName = $siteName -$secondAppPollName = $secondSiteName -$databaseName = $siteName -$secondSiteDatabaseName = $secondSiteName -$websiteBinariesDirectory = $defaultWebsiteRootDirectory + "\bin" - -#TEST AGENT -$testAgentExe = "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\QTAgentProcessUI.exe" -$agentTempFolder = "C:\Users\sfbuild\AppData\Local\VSEQT\QTAgent" - -$aspNetTempFolder = "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root" - -$setupSitefinityForSiteSyncArrangement = "AutomationTests/AutomationTestsArrangemets.svc/ExecuteArrangement/SetupSitefinityForSiteSync" - -$stagingServerSetupUrl = $defaultWebsiteUrl + $setupSitefinityForSiteSyncArrangement -$productionServerSetupUrl = $secondWebsiteUrl + $setupSitefinityForSiteSyncArrangement - -$enableMultilingualUrl = $defaultWebsiteUrl + "AutomationTests/AutomationTestsArrangemets.svc/ExecuteArrangement/SetupSitefinityForMultilingual/EnableLocalization" - -$localBackupFileCopyPath = "C:\temp\backup" \ No newline at end of file diff --git a/SetupScripts/Variables.xml b/SetupScripts/Variables.xml deleted file mode 100644 index 74b59750f..000000000 --- a/SetupScripts/Variables.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - FeatherIntegrationTests - FeatherIntegrationTests_2 - http://localhost:80/ - http://localhost:82/ - 80 - 82 - C:\Installation\SitefinityWebApp\ - C:\Tests\ - C:\Tests\SitefinityWebApp - C:\Tests\SitefinityWebApp_2 - .\SQLSERVER - false - false - false - \ No newline at end of file diff --git a/StyleCop/StyleCop 4.7/CustomDictionary.en-GB.xml b/StyleCop/StyleCop 4.7/CustomDictionary.en-GB.xml deleted file mode 100644 index 1eb0de215..000000000 --- a/StyleCop/StyleCop 4.7/CustomDictionary.en-GB.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - canonicalise - canonicalised - canonicaliser - canonicalisers - canonicalises - deserialise - deserialised - deserialiser - deserialisers - deserialises - favourited - initialiser - initialisers - serialisable - serialiser - uninitialise - uninitialises - - - preprocessed - shortlived - - - - diff --git a/StyleCop/StyleCop 4.7/CustomDictionary.en-US.xml b/StyleCop/StyleCop 4.7/CustomDictionary.en-US.xml deleted file mode 100644 index 95004ff18..000000000 --- a/StyleCop/StyleCop 4.7/CustomDictionary.en-US.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - canonicalize - canonicalized - canonicalizer - canonicalizers - canonicalizes - deserialize - deserialized - deserializes - deserialized - favorited - initializer - initializers - serializable - serializer - uninitialize - uninitializes - - - - diff --git a/StyleCop/StyleCop 4.7/CustomDictionary.xml b/StyleCop/StyleCop 4.7/CustomDictionary.xml deleted file mode 100644 index efbb52253..000000000 --- a/StyleCop/StyleCop 4.7/CustomDictionary.xml +++ /dev/null @@ -1,108 +0,0 @@ - - - - - typeparam - accessor - accessors - addin - addins - Args - async - backend - cacheability - callee - captcha - CodePlex - comparand - comparands - config - csproj - declarator - declarators - decryptable - dependant - dialog - Elasticsearch - elif - endif - enqueue - enqueued - enqueueing - enqueues - Env - etc - Foo - foreach - frontend - goto - guids - hexidecimal - ietf - inlined - iterator - iterators - leaderboard - leaderboards - leafname - lexer - loggable - lossiness - minification - mutex - muxer - muxing - overridable - ownable - packshot - plugin - plugins - prepend - prepends - readonly - refactored - reformatter - remoted - restartable - rethrow - retriable - retval - rewindable - rfc - seekable - settings - signalled - Sitefinity - sizeof - stackalloc - streamable - struct - structs - StyleCop - Sitemap - sitemap - subkey - typeof - typeless - uname - unassessed - unbias - undefine - undefines - unencoded - unescaped - Unescapes - unix - unowned - Unsecures - unsecuring - uploader - url - Usings - utils - wildcarded - xpath - - - - diff --git a/StyleCop/StyleCop 4.7/Settings.StyleCop b/StyleCop/StyleCop 4.7/Settings.StyleCop deleted file mode 100644 index 8df264eb7..000000000 --- a/StyleCop/StyleCop 4.7/Settings.StyleCop +++ /dev/null @@ -1,38 +0,0 @@ - - - - preprocessor,pre-processor - shortlived,short-lived - - - - - - - \.g\.cs$ - \.generated\.cs$ - \.g\.i\.cs$ - - - - - - - - - as - do - id - if - in - is - my - no - on - to - ui - - - - - \ No newline at end of file diff --git a/StyleCop/StyleCop 4.7/StyleCop.CSharp.Rules.dll b/StyleCop/StyleCop 4.7/StyleCop.CSharp.Rules.dll deleted file mode 100644 index 16ca241c5..000000000 Binary files a/StyleCop/StyleCop 4.7/StyleCop.CSharp.Rules.dll and /dev/null differ diff --git a/StyleCop/StyleCop 4.7/StyleCop.CSharp.dll b/StyleCop/StyleCop 4.7/StyleCop.CSharp.dll deleted file mode 100644 index 0ab21df4d..000000000 Binary files a/StyleCop/StyleCop 4.7/StyleCop.CSharp.dll and /dev/null differ diff --git a/StyleCop/StyleCop 4.7/StyleCop.VSPackage.dll b/StyleCop/StyleCop 4.7/StyleCop.VSPackage.dll deleted file mode 100644 index 4b9f05a55..000000000 Binary files a/StyleCop/StyleCop 4.7/StyleCop.VSPackage.dll and /dev/null differ diff --git a/StyleCop/StyleCop 4.7/StyleCop.dll b/StyleCop/StyleCop 4.7/StyleCop.dll deleted file mode 100644 index 38943720c..000000000 Binary files a/StyleCop/StyleCop 4.7/StyleCop.dll and /dev/null differ diff --git a/StyleCop/StyleCop 4.7/StyleCopSettingsEditor.exe b/StyleCop/StyleCop 4.7/StyleCopSettingsEditor.exe deleted file mode 100644 index 06966218c..000000000 Binary files a/StyleCop/StyleCop 4.7/StyleCopSettingsEditor.exe and /dev/null differ diff --git a/StyleCop/StyleCop 4.7/de-DE/StyleCop.CSharp.Rules.resources.dll b/StyleCop/StyleCop 4.7/de-DE/StyleCop.CSharp.Rules.resources.dll deleted file mode 100644 index 42db53cb3..000000000 Binary files a/StyleCop/StyleCop 4.7/de-DE/StyleCop.CSharp.Rules.resources.dll and /dev/null differ diff --git a/StyleCop/StyleCop 4.7/en-GB/StyleCop.CSharp.Rules.resources.dll b/StyleCop/StyleCop 4.7/en-GB/StyleCop.CSharp.Rules.resources.dll deleted file mode 100644 index e63f98e6d..000000000 Binary files a/StyleCop/StyleCop 4.7/en-GB/StyleCop.CSharp.Rules.resources.dll and /dev/null differ diff --git a/StyleCop/StyleCop 4.7/fr-FR/StyleCop.CSharp.Rules.resources.dll b/StyleCop/StyleCop 4.7/fr-FR/StyleCop.CSharp.Rules.resources.dll deleted file mode 100644 index 2ac90783d..000000000 Binary files a/StyleCop/StyleCop 4.7/fr-FR/StyleCop.CSharp.Rules.resources.dll and /dev/null differ diff --git a/StyleCop/StyleCop 4.7/mssp7en.dll b/StyleCop/StyleCop 4.7/mssp7en.dll deleted file mode 100644 index 392381f67..000000000 Binary files a/StyleCop/StyleCop 4.7/mssp7en.dll and /dev/null differ diff --git a/StyleCop/StyleCop 4.7/mssp7en.lex b/StyleCop/StyleCop 4.7/mssp7en.lex deleted file mode 100644 index da4c60930..000000000 Binary files a/StyleCop/StyleCop 4.7/mssp7en.lex and /dev/null differ diff --git a/StyleCop/StyleCop 4.7/pl-PL/StyleCop.CSharp.Rules.resources.dll b/StyleCop/StyleCop 4.7/pl-PL/StyleCop.CSharp.Rules.resources.dll deleted file mode 100644 index 0d3c0f791..000000000 Binary files a/StyleCop/StyleCop 4.7/pl-PL/StyleCop.CSharp.Rules.resources.dll and /dev/null differ diff --git a/StyleCop/StyleCop 4.7/pt-BR/StyleCop.CSharp.Rules.resources.dll b/StyleCop/StyleCop 4.7/pt-BR/StyleCop.CSharp.Rules.resources.dll deleted file mode 100644 index a6aad0f0e..000000000 Binary files a/StyleCop/StyleCop 4.7/pt-BR/StyleCop.CSharp.Rules.resources.dll and /dev/null differ diff --git a/StyleCop/StyleCop 4.7/ru-RU/StyleCop.CSharp.Rules.resources.dll b/StyleCop/StyleCop 4.7/ru-RU/StyleCop.CSharp.Rules.resources.dll deleted file mode 100644 index 5e32c6a3a..000000000 Binary files a/StyleCop/StyleCop 4.7/ru-RU/StyleCop.CSharp.Rules.resources.dll and /dev/null differ diff --git a/StyleCop/StyleCop 4.7/tools/StyleCopReport.xsl b/StyleCop/StyleCop 4.7/tools/StyleCopReport.xsl deleted file mode 100644 index e1e038360..000000000 --- a/StyleCop/StyleCop 4.7/tools/StyleCopReport.xsl +++ /dev/null @@ -1,49 +0,0 @@ - - - - - -
- - -
StyleCop Report
- - -
No StyleCop information in build logs.
-
-
- -
-
- - -
- - - error - - - success - - - Number of Violations: -
-
    - - - -
  1. -
    - -
  2. -
    -
-
- -
\ No newline at end of file diff --git a/StyleCop/StyleCop.targets b/StyleCop/StyleCop.targets deleted file mode 100644 index f839b9c56..000000000 --- a/StyleCop/StyleCop.targets +++ /dev/null @@ -1,121 +0,0 @@ - - - - - - $(BuildDependsOn);StyleCop - StyleCopForceFullAnalysis;$(RebuildDependsOn) - - - - - $(SourceAnalysisForceFullAnalysis) - - - false - - - - - $(SourceAnalysisCacheResults) - - - true - - - - - false - - - false - - - - - $(SourceAnalysisEnabled) - - - true - - - - - $(SourceAnalysisOverrideSettingsFile) - - - - - - - - $(SourceAnalysisOutputFile) - - - $(IntermediateOutputPath)StyleCopViolations.xml - - - - - - 0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileData.cs b/Telerik.Sitefinity.Frontend.Data/FileData.cs similarity index 100% rename from Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileData.cs rename to Telerik.Sitefinity.Frontend.Data/FileData.cs diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorDataManager.cs b/Telerik.Sitefinity.Frontend.Data/FileMonitorDataManager.cs similarity index 100% rename from Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorDataManager.cs rename to Telerik.Sitefinity.Frontend.Data/FileMonitorDataManager.cs diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorDataProvider.cs b/Telerik.Sitefinity.Frontend.Data/FileMonitorDataProvider.cs similarity index 100% rename from Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorDataProvider.cs rename to Telerik.Sitefinity.Frontend.Data/FileMonitorDataProvider.cs diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorFluentMapping.cs b/Telerik.Sitefinity.Frontend.Data/FileMonitorFluentMapping.cs similarity index 91% rename from Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorFluentMapping.cs rename to Telerik.Sitefinity.Frontend.Data/FileMonitorFluentMapping.cs index d72610236..18c0c1d5a 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorFluentMapping.cs +++ b/Telerik.Sitefinity.Frontend.Data/FileMonitorFluentMapping.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using Telerik.OpenAccess; using Telerik.OpenAccess.Metadata.Fluent; +using Telerik.OpenAccess.Metadata.Fluent.Advanced; using Telerik.Sitefinity.Model; namespace Telerik.Sitefinity.Frontend.FilesMonitoring.Data @@ -49,6 +50,8 @@ private void MapFileData(List mappings) fileDataMapping.HasProperty(p => p.FilePath).ToColumn("file_path"); fileDataMapping.HasProperty(p => p.PackageName).ToColumn("package_name"); + fileDataMapping.HasIndex(p => new { p.FilePath }).IsUnique().WithName("idx_sf_fls_mntr_dta_path"); + mappings.Add(fileDataMapping); } diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorFluentMetadataSource.cs b/Telerik.Sitefinity.Frontend.Data/FileMonitorFluentMetadataSource.cs similarity index 94% rename from Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorFluentMetadataSource.cs rename to Telerik.Sitefinity.Frontend.Data/FileMonitorFluentMetadataSource.cs index 4cfdc4abc..1da7c8866 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorFluentMetadataSource.cs +++ b/Telerik.Sitefinity.Frontend.Data/FileMonitorFluentMetadataSource.cs @@ -7,7 +7,7 @@ namespace Telerik.Sitefinity.Frontend.FilesMonitoring.Data /// /// A concrete implementation of the for the file monitoring. /// - internal class FileMonitorFluentMetadataSource : SitefinityMetadataSourceBase + public class FileMonitorFluentMetadataSource : SitefinityMetadataSourceBase { #region Contructors diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/OpenAccessFileMonitorDataProvider.cs b/Telerik.Sitefinity.Frontend.Data/OpenAccessFileMonitorDataProvider.cs similarity index 100% rename from Telerik.Sitefinity.Frontend/FilesMonitoring/Data/OpenAccessFileMonitorDataProvider.cs rename to Telerik.Sitefinity.Frontend.Data/OpenAccessFileMonitorDataProvider.cs diff --git a/Telerik.Sitefinity.Frontend.Data/Properties/AssemblyInfo.cs b/Telerik.Sitefinity.Frontend.Data/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..de8521556 --- /dev/null +++ b/Telerik.Sitefinity.Frontend.Data/Properties/AssemblyInfo.cs @@ -0,0 +1,10 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Telerik.Sitefinity.Frontend.Data")] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("14d8a400-6989-4870-ada1-766622caeb86")] diff --git a/Telerik.Sitefinity.Frontend.Data/Telerik.Sitefinity.Frontend.Data.csproj b/Telerik.Sitefinity.Frontend.Data/Telerik.Sitefinity.Frontend.Data.csproj new file mode 100644 index 000000000..971cd5129 --- /dev/null +++ b/Telerik.Sitefinity.Frontend.Data/Telerik.Sitefinity.Frontend.Data.csproj @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + $(PkgTelerik_DataAccess_Fluent)\tools\enhancer\enhancer.exe + + + + + \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/ControllerProvider.cs b/Telerik.Sitefinity.Frontend/ControllerProvider.cs new file mode 100644 index 000000000..91757aeec --- /dev/null +++ b/Telerik.Sitefinity.Frontend/ControllerProvider.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; +using Telerik.Sitefinity.Mvc.Store; + +namespace Telerik.Sitefinity.Frontend +{ + internal class ControllerProvider : IControllerProvider + { + public IEnumerable GetControllers() + { + var controllerContainerInitializer = new ControllerContainerInitializer(); + return controllerContainerInitializer.GetControllers(); + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Designers/DesignerInitializer.cs b/Telerik.Sitefinity.Frontend/Designers/DesignerInitializer.cs index 70a1b2169..e4012c865 100644 --- a/Telerik.Sitefinity.Frontend/Designers/DesignerInitializer.cs +++ b/Telerik.Sitefinity.Frontend/Designers/DesignerInitializer.cs @@ -1,12 +1,14 @@ using System; +using System.Collections.Generic; using System.Text; +using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.UI; using Telerik.Microsoft.Practices.Unity; using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Frontend.Mvc.Helpers; using Telerik.Sitefinity.Frontend.Resources; -using Telerik.Sitefinity.Modules.Pages; using Telerik.Sitefinity.Services; using Telerik.Sitefinity.Web.UI; @@ -15,21 +17,21 @@ namespace Telerik.Sitefinity.Frontend.Designers /// /// This class contains logic for initializing the MVC designer. /// - public class DesignerInitializer + internal class DesignerInitializer : IInitializer { /// /// Initializes the MVC designer. /// public void Initialize() { - if (RouteTable.Routes["MvcDesigner"] == null) + if (RouteTable.Routes[DesignerInitializer.MvcDesignerRouteName] == null) { - RouteTable.Routes.MapRoute("MvcDesigner", "Telerik.Sitefinity.Frontend/{controller}/{action}/{widgetName}", new { controller = "DesignerController", action = "Master" }); + RouteTable.Routes.MapRoute(DesignerInitializer.MvcDesignerRouteName, "Telerik.Sitefinity.Frontend/{controller}/Master/{widgetName}", new { controller = "DesignerController", action = "Master" }); } - if (RouteTable.Routes["MvcDesignerView"] == null) + if (RouteTable.Routes[DesignerInitializer.MvcDesignerViewRouteName] == null) { - RouteTable.Routes.MapRoute("MvcDesignerView", "Telerik.Sitefinity.Frontend/{controller}/{action}/{widgetName}/{viewType}", new { controller = "DesignerController", action = "View", viewType = "PropertyGrid" }); + RouteTable.Routes.MapRoute(DesignerInitializer.MvcDesignerViewRouteName, "Telerik.Sitefinity.Frontend/{controller}/View/{widgetName}/{viewType}", new { controller = "DesignerController", action = "View", viewType = "PropertyGrid" }); } ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); @@ -38,6 +40,15 @@ public void Initialize() EventHub.Subscribe(this.RegisteringScriptsHandler); } + /// + /// Uninitializes the MVC designer. + /// + public void Uninitialize() + { + RouteTable.Routes.Remove(RouteTable.Routes[DesignerInitializer.MvcDesignerRouteName]); + RouteTable.Routes.Remove(RouteTable.Routes[DesignerInitializer.MvcDesignerViewRouteName]); + } + /// /// Registering the scripts for ZoneEditor. /// @@ -46,21 +57,23 @@ private void RegisteringScriptsHandler(IScriptsRegisteringEvent @event) { if (@event.Sender.GetType() == typeof(ZoneEditor)) { - var scriptRootPath = "~/" + FrontendManager.VirtualPathBuilder.GetVirtualPath(this.GetType().Assembly); + var scriptRootPath = VirtualPathUtility.ToAbsolute("~/" + FrontendManager.VirtualPathBuilder.GetVirtualPath(this.GetType().Assembly)); + + @event.Scripts.Add(new ScriptReference(UrlHelpers.AppendVersion(scriptRootPath + "Mvc/Scripts/Angular/angular.min.js"))); + @event.Scripts.Add(new ScriptReference(UrlHelpers.AppendVersion(scriptRootPath + "Mvc/Scripts/Angular/angular-route.min.js"))); + @event.Scripts.Add(new ScriptReference(UrlHelpers.AppendVersion(scriptRootPath + "Mvc/Scripts/Angular/angular-sanitize.min.js"))); + @event.Scripts.Add(new ScriptReference(UrlHelpers.AppendVersion(scriptRootPath + "Mvc/Scripts/Bootstrap/js/ui-bootstrap-tpls.min.js"))); + + ////var references = PageManager.GetScriptReferences(ScriptRef.KendoAll); + ////foreach (var scriptRef in references) + ////{ + //// @event.Scripts.Add(scriptRef); + ////} + + @event.Scripts.Add(new ScriptReference(UrlHelpers.AppendVersion(scriptRootPath + "Designers/Scripts/page-editor-services.js"))); + @event.Scripts.Add(new ScriptReference(UrlHelpers.AppendVersion(scriptRootPath + "Designers/Scripts/page-editor.js"))); - var references = PageManager.GetScriptReferences(ScriptRef.KendoWeb); - foreach (var scriptRef in references) - { - @event.Scripts.Add(scriptRef); - } - - @event.Scripts.Add(new ScriptReference(scriptRootPath + "Mvc/Scripts/Angular/angular.min.js")); - @event.Scripts.Add(new ScriptReference(scriptRootPath + "Mvc/Scripts/Angular/angular-route.min.js")); - @event.Scripts.Add(new ScriptReference(scriptRootPath + "Mvc/Scripts/Bootstrap/js/ui-bootstrap-tpls-0.11.0.min.js")); - - @event.Scripts.Add(new ScriptReference(scriptRootPath + "Designers/Scripts/page-editor-services.js")); - @event.Scripts.Add(new ScriptReference(scriptRootPath + "Designers/Scripts/page-editor.js")); - @event.Scripts.Add(new ScriptReference(scriptRootPath + "Mvc/Scripts/Kendo/angular-kendo.js")); + @event.Scripts.Add(new ScriptReference(UrlHelpers.AppendVersion(scriptRootPath + "Mvc/Scripts/LABjs/LAB.min.js"))); var currentPackage = new PackageManager().GetCurrentPackage(); if (!currentPackage.IsNullOrEmpty()) @@ -84,5 +97,8 @@ private void RegisteringScriptsHandler(IScriptsRegisteringEvent @event) } } } + + private const string MvcDesignerRouteName = "MvcDesigner"; + private const string MvcDesignerViewRouteName = "MvcDesignerView"; } } diff --git a/Telerik.Sitefinity.Frontend/Designers/DesignerResolver.cs b/Telerik.Sitefinity.Frontend/Designers/DesignerResolver.cs index 33d71f8cf..ad4a32feb 100644 --- a/Telerik.Sitefinity.Frontend/Designers/DesignerResolver.cs +++ b/Telerik.Sitefinity.Frontend/Designers/DesignerResolver.cs @@ -1,16 +1,32 @@ using System; +using System.Collections.Generic; using System.Linq; +using System.Text.RegularExpressions; +using System.Web.Mvc; using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Frontend.Mvc.Helpers; using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Mvc; +using Telerik.Sitefinity.Mvc.Proxy; +using Telerik.Sitefinity.Web.UI.ControlDesign; namespace Telerik.Sitefinity.Frontend.Designers { /// /// This class contains logic for resolving the designer responsible for the property editing of a widget. /// - public class DesignerResolver : IDesignerResolver + internal class DesignerResolver : IDesignerResolver { + /// + /// Initializes a new instance of the class. + /// + /// An instance of a package manager. + public DesignerResolver(PackageManager packageManager = null) + { + this.packageManager = packageManager ?? new PackageManager(); + } + #region Public members /// @@ -27,17 +43,69 @@ public string GetUrl(Type widgetType) if (widgetType == null) throw new ArgumentNullException("widgetType"); + if (this.HasCustomWebFormsDesigner(widgetType)) + return null; + string designerUrl; if (!this.TryResolveUrlFromAttribute(widgetType, out designerUrl)) designerUrl = this.GetDefaultUrl(widgetType); - return new PackageManager().EnhanceUrl(designerUrl); + return this.packageManager.EnhanceUrl(designerUrl); } - #endregion + /// + /// Checks if there are separate custom desiger views for the particular control type. + /// + /// The type of the control. + /// + public bool HasCustomDesigners(string controlType) + { + var mvcProxy = new MvcControllerProxy(); + mvcProxy.ControllerName = controlType; + var controller = mvcProxy.GetController() as Controller; + + if (controller == null) + return true; + + var designerNamePattern = "DesignerView.*"; + var views = controller.GetViews(null).Where(view => Regex.IsMatch(view, designerNamePattern)); + + return views.Count() > 0; + } + + /// + /// Gets all view names that match a pattern. + /// + /// The control type. + /// The view name pattern + /// + public IEnumerable GetViewNames(string controlType, string viewNamePattern) + { + var mvcProxy = new MvcControllerProxy(); + mvcProxy.ControllerName = controlType; + var controller = mvcProxy.GetController() as Controller; + + if (controller == null) + return new List(); + + return ViewSelectorHelpers.GetViewNames(null, controller, viewNamePattern); + } + + #endregion #region Private members - + + private bool HasCustomWebFormsDesigner(Type widgetType) + { + var attributes = widgetType.GetCustomAttributes(typeof(ControlDesignerAttribute), inherit: true); + var designerAttr = attributes.FirstOrDefault() as ControlDesignerAttribute; + + if (designerAttr != null) + return true; + + return false; + } + /// /// Resolve a designer URL for the specified widget type if such is specified with . /// @@ -68,6 +136,10 @@ private bool TryResolveUrlFromAttribute(Type widgetType, out string designerUrl) private string GetDefaultUrl(Type widgetType) { string designerUrl = null; + + if (typeof(GridSystem.GridControl).IsAssignableFrom(widgetType)) + return DesignerResolver.DefaultGridActionUrlTemplate; + var controllerRegistry = FrontendManager.ControllerFactory; bool isController = controllerRegistry.IsController(widgetType); @@ -85,7 +157,11 @@ private string GetDefaultUrl(Type widgetType) #region Constants private const string DefaultActionUrlTemplate = "~/Telerik.Sitefinity.Frontend/Designer/Master/{0}"; + private const string DefaultGridActionUrlTemplate = "~/Telerik.Sitefinity.Frontend/GridDesigner/Master/GridDesigner"; + private readonly PackageManager packageManager; - #endregion + public object ViewSelectorHelper { get; private set; } + + #endregion } } diff --git a/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor-services.js b/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor-services.js index 01b2aa9c6..a605cac44 100644 --- a/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor-services.js +++ b/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor-services.js @@ -24,6 +24,22 @@ }; }); + pageEditorServices.provider('gridContext', function () { + var context = sitefinity.pageEditor.gridContext; + + this.$get = function () { + return { + contentId: context.Id, + pageId: context.PageId, + mediaType: context.MediaType, + layoutRoot: context.LayoutRoot, + layoutContainer: context.LayoutContainer, + dock: context.Dock, + zoneEditorId: context.ZoneEditorId + }; + }; + }); + //this is the service responsible for managing the properties data for all interested parties pageEditorServices.factory('propertyService', function ($rootScope, $http, $q, widgetContext) { @@ -56,7 +72,7 @@ */ var getUrl = function () { if (!httpGetUrl) { - httpGetUrl = widgetContext.webServiceUrl + widgetContext.widgetId + '/'; + httpGetUrl = widgetContext.webServiceUrl + widgetContext.widgetId + '/?pageId=' + widgetContext.pageId + "&mediaType=" + widgetContext.mediaType; } return httpGetUrl; }; @@ -79,6 +95,25 @@ return widget; }; + var toHierarchyArray = function (propertyBag) { + var widget = {}; + for (var i = 0; i < propertyBag.length; i++) { + var prop = propertyBag[i]; + if (!prop.NeedsEditor) { + var pathArray = prop.PropertyPath.split('/').splice(2); + + var temp = widget; + for (var j = 0; j < pathArray.length - 1; j++) { + temp[pathArray[j]] = temp[pathArray[j]] || {}; + temp = temp[pathArray[j]]; + } + temp[prop.PropertyName] = prop; + } + } + + return widget; + }; + //get the property data from the service var load = function () { if (loadingPromise) @@ -87,16 +122,15 @@ var deferred = $q.defer(); $http.get(getUrl(), requestOptions()) - .success(function (data) { - properties = data; + .then(function (response) { + properties = response.data; //clone the result in initialData - initialData = $.extend(true, {}, data); + initialData = $.extend(true, {}, response.data); loadingPromise = null; - deferred.resolve(data); - }) - .error(function (data) { + deferred.resolve(response.data); + }, function (err) { loadingPromise = null; - deferred.reject(data); + deferred.reject(err); }); loadingPromise = deferred.promise; @@ -143,17 +177,24 @@ save: function (saveMode, modifiedData) { if (!modifiedData || modifiedData.length === 0) { modifiedData = this.getDirty(); + + // If any of the property values is not string - convert it to json + for (var i = 0; i < modifiedData.length; i++) { + var value = modifiedData[i].PropertyValue; + if (value !== null && typeof value !== 'string') { + modifiedData[i].PropertyValue = JSON.stringify(value); + } + } } var deferred = $q.defer(); $http.put(updateUrl(saveMode), modifiedData, requestOptions()) - .success(function (data) { + .then(function (response) { initialData = $.extend(true, {}, properties); - deferred.resolve(data); - }) - .error(function (data) { - deferred.reject(data); + deferred.resolve(response.data); + }, function (err) { + deferred.reject(err); }); return deferred.promise; @@ -188,7 +229,209 @@ */ toAssociativeArray: function (propertyBag) { return toAssociativeArray(propertyBag); + }, + + toHierarchyArray: function (propertyBag) { + return toHierarchyArray(propertyBag); + } + }; + + return service; + }); + + + //this is the service responsible for managing the grid data for all interested parties + pageEditorServices.factory('gridService', function ($rootScope, $http, $q, gridContext) { + + var loadingPromise, + elements; + + /** + * Generates the headers dictionary for the HTTP request + * to be performed. The headers will contain by default the + * Sitefinity UI culture header. + */ + var requestOptions = function () { + return { + cache: false + }; + }; + + var gridElement = function (id, name, css, label, isPlaceholder) { + this.id = id; + this.name = name; + this.css = css; + this.label = label; + this.isPlaceholder = isPlaceholder; + }; + + var getInnerElements = function (layoutRoot) { + var gridElements = []; + var elements = $(layoutRoot).findExcludeNested('[data-sf-element]'); + + //Sort out the inner columns + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + var id = $(element).attr('id'); + var classValue = $(element).attr('class'); + var displayClass = classValue.replace('sf_colsIn', '').trim(); + var columnName = $(element).attr('data-sf-element'); + var label = $(element).attr('data-placeholder-label'); + var isPlaceholder = $(element).hasClass('sf_colsIn'); + + gridElements.push(new gridElement(id, columnName, displayClass, label, isPlaceholder)); + } + + return gridElements; + }; + + var constructLayoutHtml = function (elements) { + var tempLayout = $(gridContext.layoutRoot).clone(); + + for (var i = 0; i < elements.length; i++) { + var innerDiv = elements[i].id ? $(tempLayout).findExcludeNested('#' + elements[i].id) : $(tempLayout).findExcludeNested('[data-sf-element="' + elements[i].name + '"]'); + + if (innerDiv) { + var label = elements[i].label; + + if (label) { + $(innerDiv).attr('data-placeholder-label', label); + } + else { + $(innerDiv).removeAttr('data-placeholder-label'); + } + + var css = elements[i].isPlaceholder ? 'sf_colsIn ' + elements[i].css : elements[i].css; + $(innerDiv).attr('class', css.trim()); + + $(innerDiv).removeAttr('id'); + } + } + + $(tempLayout).find('.RadDockZone').each(function () { + $(this).remove(); + }); + + return tempLayout.html(); + }; + + var refreshContainer = function (elements) { + for (var i = 0; i < elements.length; i++) { + var innerDiv = elements[i].id ? $(gridContext.layoutContainer).findExcludeNested('#' + elements[i].id) : $(gridContext.layoutContainer).findExcludeNested('[data-sf-element="' + elements[i].name + '"]'); + + if (innerDiv) { + var css = elements[i].isPlaceholder ? 'sf_colsIn ' + elements[i].css : elements[i].css; + $(innerDiv).attr('class', css.trim()); + + var label = elements[i].label; + var labelElement = $(innerDiv).find('.zeDockZoneLabel b'); + + if (labelElement && labelElement.length > 0) { + labelElement.html(label); + } + else if (label) { + $(innerDiv).find('.RadDockZone').addClass('zeDockZoneHasLabel'); + $(innerDiv).find('.RadDockZone .emptyZoneDraggingText').after('
' + label + '
'); + } + + if (label) { + $(innerDiv).attr('data-placeholder-label', label); + } + else { + $(innerDiv).removeAttr('data-placeholder-label'); + } + } + } + }; + + // find all child elements until you find child grid widget inside the current grid + $.fn.findExcludeNested = function (selector, result) { + + // Default result to an empty jQuery object if not provided + result = typeof result !== 'undefined' ? result : new jQuery(); + + // Iterate through all children, except those with the RadDockZone class + this.children().each(function () { + + var thisObject = jQuery(this); + if (thisObject.is(selector)) + result.push(this); + + // Recursively seek children without RadDockZone class + if (!thisObject.hasClass('RadDockZone')) + thisObject.findExcludeNested(selector, result); + }); + + return result; + }; + + var invokePut = function (url, data, deferred, success) { + var wRequest = new Sys.Net.WebRequest(); + wRequest.set_url(url); + wRequest.set_httpVerb('PUT'); + wRequest.set_body(Sys.Serialization.JavaScriptSerializer.serialize(data)); + wRequest.get_headers()['Cache-Control'] = 'no-cache, no-store, must-revalidate'; + wRequest.get_headers().Pragma = 'no-cache'; + wRequest.get_headers().Expires = '0'; + wRequest.get_headers()['Content-Type'] = 'application/json'; + wRequest.add_completed( + function (executor, eventArgs) { + if (executor.get_responseAvailable()) { + success(); + } + else { + deferred.reject(data); + } + }); + + // Execute the request. + wRequest.invoke(); + }; + + /** + * Constructs and returns the PUT URL for the server side web service + * that saves grid layout. + */ + var updateUrl = function (url) { + return String.format(url, gridContext.contentId, gridContext.pageId, (gridContext.mediaType === 1)); + }; + + + var service = { + + /** + * Retrieves the placeholders for the current grid context. + * + * @returns {object} promise The promise object that is resolved or rejected once the operation completes. + */ + get: function () { + var deferred = $q.defer(); + var elements = getInnerElements(gridContext.layoutRoot); + deferred.resolve(elements); + return deferred.promise; + }, + + /** + * Saves the grid html to the server. + * + * @returns {object} promise The promise object that is resolved or rejected once the operation completes. + */ + save: function (elements, serviceUrl) { + var modifiedData = $find(gridContext.zoneEditorId)._getWebServiceParameters('reload', gridContext.dock); + modifiedData.LayoutHtml = constructLayoutHtml(elements); + + var deferred = $q.defer(); + + var success = function () { + refreshContainer(elements); + deferred.resolve(); + }; + + invokePut(updateUrl(serviceUrl), modifiedData, deferred, success); + + return deferred.promise; } + }; return service; diff --git a/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor.js b/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor.js index f3a596e8b..c664c7aec 100644 --- a/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor.js +++ b/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor.js @@ -1,102 +1,230 @@ -/* global $telerik, document, kendo */ +/* global $telerik, document, kendo */ var sitefinity = sitefinity || {}; (function ($) { - - var loader, - loaderMarkup = '
' + - '
', - loaderTemplate = kendo.template(loaderMarkup), - dialog; - - /** - * Represents the Sitefinity page editor. - */ - sitefinity.pageEditor = { - - /** - * Shows the loading animation in the page editor. - * - * @param {String} appPath The relative path of the application used to resolve the loading image. - */ - showLoader: function (appPath) { - if (loader) { - loader.show(); - } else { - loader = $(loaderTemplate({ appPath: appPath })); - $('body').append(loader); - } - }, - - /** - * Hides the loading animation in the page editor. - */ - hideLoader: function () { - $(loader).hide(); - }, - - /** - * Renders the dialog within page editor with the provided markup. - * - * @param {String} markup The HTML markup to be rendered within the dialog. - */ - renderDialog: function (markup) { - var jQueryAjaxSettingsCache = $.ajaxSettings.cache; - $.ajaxSettings.cache = true; - - dialog = $('
'); - $('body').append(dialog); - dialog.append(markup); - this.hideLoader(); - $.ajaxSettings.cache = jQueryAjaxSettingsCache; - - dialog.on('hidden.bs.modal', this.destroyDialog); - - if (typeof ($telerik) != 'undefined') { - $telerik.$(document).trigger('dialogRendered'); - } - }, - - /** - * Event handler that handles the needDialog event from the Sitefinity - * page editor. - */ - openDialog: function (ev, args) { - this.showLoader(args.AppPath); - this.widgetContext = args; - - $.get(this.widgetContext.url) - .done($.proxy(this.renderDialog, this)) - .fail(function (data) { - alert('There is a problem with loading the widget designer: ' + data); - }); - }, - - /** - * Destroys the currently opened dialog. - */ - destroyDialog: function () { - if (dialog) { - dialog.remove(); - this.widgetContext = null; - } - }, - - /** - * Provides the context for the currently active widget. - */ - widgetContext: null - - }; - - /** - * Register the global Sitefinity events with the pageEditor component. - */ - if (typeof ($telerik) != 'undefined') { - $telerik.$(document).on('needsModalDialog', $.proxy(sitefinity.pageEditor.openDialog, sitefinity.pageEditor)); - $telerik.$(document).on('modalDialogClosed', $.proxy(sitefinity.pageEditor.destroyDialog, sitefinity.pageEditor)); - } -})(jQuery); \ No newline at end of file + $(function () { + var loader, + loaderMarkup = '
', + loaderTemplate = kendo.template(loaderMarkup), + dialog, + pageScripts = $('script').map(function () { + return $(this).attr('src'); + }).toArray(); + + function isScriptTag(tag) { + return tag.tagName == 'SCRIPT' && (!tag.type || tag.type.toLowerCase() == 'text/javascript'); + } + + function extractScripts(markup) { + var div = document.createElement('div'); + div.innerHTML = markup; + var scripts = div.getElementsByTagName('script'); + + var result = []; + for (var i = 0; i < scripts.length; i++) { + if (isScriptTag(scripts[i])) { + result.push(scripts[i]); + } + } + + return result; + } + + function stripScripts(markup) { + var div = document.createElement('div'); + div.innerHTML = markup; + var scripts = div.getElementsByTagName('script'); + + var i = scripts.length; + while (i--) { + if (isScriptTag(scripts[i])) { + scripts[i].parentNode.removeChild(scripts[i]); + } + } + + return div.innerHTML; + } + + function loadScripts(container, scriptTags, loadHandler) { + var lab = $LAB.setOptions({ + AlwaysPreserveOrder: true, + AllowDuplicates: true, + }); + + var labNoDuplicates = $LAB.setOptions({ + AlwaysPreserveOrder: true, + AllowDuplicates: false + }); + + for (var i = 0; i < scriptTags.length; i++) { + if (scriptTags[i].src) { + // Hack to not load bootstrap multiple times, should be removed with the next version of bootstrap or with feather designer script refactoring + if (scriptTags[i].src.indexOf('Mvc/Scripts/Bootstrap/js/bootstrap.min.js') >= 0) { + var src = $(scriptTags[i]).attr('src'); + + if (pageScripts.indexOf(src) < 0) { + labNoDuplicates.script(src); + } + } + else { + lab = lab.script(scriptTags[i].src); + } + } + else if (scriptTags[i].text) { + var text = scriptTags[i].text; + lab = lab.wait(function () { eval(text); }); // jshint ignore:line + } + } + + labNoDuplicates.wait(function () { + lab.wait(loadHandler); + }); + } + + /** + * Represents the Sitefinity page editor. + */ + sitefinity.pageEditor = { + /** + * Shows the loading animation in the page editor. + * + * @param {String} appPath The relative path of the application used to resolve the loading image. + */ + showLoader: function (appPath) { + if (loader) { + loader.show(); + } else { + loader = $(loaderTemplate({ appPath: appPath })); + $('body').append(loader); + } + }, + + /** + * Hides the loading animation in the page editor. + */ + hideLoader: function () { + $(loader).hide(); + }, + + /** + * Renders the dialog within page editor with the provided markup. + * + * @param {String} markup The HTML markup to be rendered within the dialog. + */ + renderDialog: function (markup) { + dialog = $('
'); + $('body').append(dialog); + + var scriptTags = extractScripts(markup); + markup = stripScripts(markup); + + dialog.append(markup); + dialog.on('hidden.bs.modal', this.destroyDialog); + + var that = this; + loadScripts(dialog[0], scriptTags, function () { + that.hideLoader(); + + if (typeof ($telerik) != 'undefined') { + $telerik.$(document).trigger('dialogRendered'); + } + }); + }, + + /** + * Event handler that handles the needDialog event from the Sitefinity + * page editor. + */ + openDialog: function (args) { + if (args.detail.openNewEditor) + return true; + + this.showLoader(args.detail.AppPath); + this.widgetContext = args.detail; + + var separator; + if (this.widgetContext.url.indexOf('?') > -1) + separator = '&'; + else + separator = '?'; + + var url = this.widgetContext.url + separator + 'controlId=' + this.widgetContext.Id; + if (this.widgetContext.ModuleName) { + url += '&moduleName=' + this.widgetContext.ModuleName; + } + if (this.widgetContext.MediaType) { + url += '&mediaType=' + this.widgetContext.MediaType; + } + + $.get(url) + .done($.proxy(this.renderDialog, this)) + .fail(function (data) { + alert('There is a problem with loading the widget designer: ' + data); + }); + }, + + openGridDialog: function (ev, args) { + this.showLoader(args.AppPath); + this.gridContext = args; + + var separator; + if (this.gridContext.url.indexOf('?') > -1) + separator = '&'; + else + separator = '?'; + + var url = this.gridContext.url + separator + 'controlId=' + this.gridContext.Id; + url += '&gridTitle=' + this.gridContext.GridTitle; + $.get(url) + .done($.proxy(this.renderDialog, this)) + .fail(function (data) { + alert('There is a problem with loading the grid designer: ' + data); + }); + }, + + openPersonalizationDialog: function (ev, args) { + this.showLoader(args.AppPath); + this.widgetContext = args; + + var url = this.widgetContext.AppPath + "Telerik.Sitefinity.Frontend/PersonalizationDesigner/Master/PersonalizationDesigner/"; + $.get(url) + .done($.proxy(this.renderDialog, this)) + .fail(function (data) { + alert('There is a problem with loading the widget designer: ' + data); + }); + }, + + /** + * Destroys the currently opened dialog. + */ + destroyDialog: function () { + if (dialog) { + dialog.remove(); + this.widgetContext = null; + this.gridContext = null; + } + }, + + /** + * Provides the context for the currently active widget. + */ + widgetContext: null, + gridContext: null + + }; + + /** + * Register the global Sitefinity events with the pageEditor component. + */ + if (typeof ($telerik) != 'undefined') { + $telerik.$(document).on('needsModalDialog', $.proxy(sitefinity.pageEditor.openDialog, sitefinity.pageEditor)); + + $telerik.$(document).on('needsPersonalizationModalDialog', $.proxy(sitefinity.pageEditor.openPersonalizationDialog, sitefinity.pageEditor)); + + $telerik.$(document).on('needsGridModalDialog', $.proxy(sitefinity.pageEditor.openGridDialog, sitefinity.pageEditor)); + $telerik.$(document).on('modalDialogClosed', $.proxy(sitefinity.pageEditor.destroyDialog, sitefinity.pageEditor)); + $telerik.$(document).on('gridModalDialogClosed', $.proxy(sitefinity.pageEditor.destroyDialog, sitefinity.pageEditor)); + } + }); +})(jQuery); diff --git a/Telerik.Sitefinity.Frontend/FeatherConfig.cs b/Telerik.Sitefinity.Frontend/FeatherConfig.cs new file mode 100644 index 000000000..232ea2dfd --- /dev/null +++ b/Telerik.Sitefinity.Frontend/FeatherConfig.cs @@ -0,0 +1,142 @@ +using System.Configuration; +using System.Diagnostics.CodeAnalysis; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure; +using Telerik.Sitefinity.Localization; + +namespace Telerik.Sitefinity.Frontend +{ + /// + /// Configuration for the Feather module + /// + [ObjectInfo(typeof(InfrastructureResources), Title = "FeatherConfigCaption", Description = "FeatherConfigDescription")] + public class FeatherConfig : ConfigSection + { + /// + /// Gets or sets a value indicating whether to disable precompilation. + /// + /// + /// true if precompilation is disabled; otherwise, false. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Precompilation")] + [ConfigurationProperty("disablePrecompilation")] + [ObjectInfo(typeof(InfrastructureResources), Title = "DisablePrecompilationCaption", Description = "DisablePrecompilationDescription")] + public bool DisablePrecompilation + { + get + { + return (bool)this["disablePrecompilation"]; + } + + set + { + this["disablePrecompilation"] = value; + } + } + + /// + /// Gets or sets a value indicating whether to always use the precompiled version of a resource regardless of changes to physical files. + /// + /// + /// true if precompiled version should be used regardless of changes to physical files; otherwise, false. + /// + [ConfigurationProperty("alwaysUsePrecompiledVersion")] + [ObjectInfo(typeof(InfrastructureResources), Title = "AlwaysUsePrecompiledVersionCaption", Description = "AlwaysUsePrecompiledVersionDescription")] + public bool AlwaysUsePrecompiledVersion + { + get + { + return (bool)this["alwaysUsePrecompiledVersion"]; + } + + set + { + this["alwaysUsePrecompiledVersion"] = value; + } + } + + /// + /// Gets or sets a value indicating whether to log when precompiled views are used. + /// + /// + /// true if usage of precompiled views should be logged; otherwise, false. + /// + [ConfigurationProperty("logPrecompiledViewUsage")] + [ObjectInfo(typeof(InfrastructureResources), Title = "LogPrecompiledViewUsageCaption", Description = "LogPrecompiledViewUsageDescription")] + public bool LogPrecompiledViewUsage + { + get + { + return (bool)this["logPrecompiledViewUsage"]; + } + + set + { + this["logPrecompiledViewUsage"] = value; + } + } + + /// + /// Gets or sets a value indicating whether to require parameter naming in the widget routings. + /// + /// + /// true if the routes will work only with named params (e.g /tag/london/page/2); otherwise, false when the route will be /london/2. + /// + [ConfigurationProperty("useNamedParametersRouting")] + [ObjectInfo(typeof(InfrastructureResources), Title = "UseNamedParametersRoutingCaption", Description = "UseNamedParametersRoutingDescription")] + public bool UseNamedParametersRouting + { + get + { + return (bool)this["useNamedParametersRouting"]; + } + + set + { + this["useNamedParametersRouting"] = value; + } + } + + /// + /// Gets or sets a value indicating whether cached controller assemblies to be used + /// + /// + /// true if the cached controller assemblies are used; otherwise, false + /// + [ConfigurationProperty("useCachedControllerContainerAssemblies", DefaultValue = true)] + [ObjectInfo(typeof(InfrastructureResources), Title = "UseCachedControllerContainerAssembliesTitle", Description = "UseCachedControllerContainerAssembliesDescription")] + public bool UseCachedControllerContainerAssemblies + { + get + { + return (bool)this["useCachedControllerContainerAssemblies"]; + } + + set + { + this["useCachedControllerContainerAssemblies"] = value; + } + } + + /// + /// Gets or sets a value indicating whether the Ninject kernel should automatically load extensions at startup + /// + /// + /// true if the Ninject kernel should automatically load extensions at startup; otherwise, false + /// + [ConfigurationProperty("ninjectLoadExtensions", DefaultValue = true)] + [ObjectInfo(typeof(InfrastructureResources), Title = "NinjectLoadExtensionsTitle", Description = "NinjectLoadExtensionsDescription")] + public bool NinjectLoadExtensions + { + get + { + return (bool)this["ninjectLoadExtensions"]; + } + + set + { + this["ninjectLoadExtensions"] = value; + } + } + } +} diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/FileChangeType.cs b/Telerik.Sitefinity.Frontend/FilesMonitoring/FileChangeType.cs index 5c6952a74..7724f3a9d 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/FileChangeType.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/FileChangeType.cs @@ -3,7 +3,7 @@ /// /// Represents the file operations that would trigger reactions during the file monitoring. /// - public enum FileChangeType + internal enum FileChangeType { Created, Deleted, diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/FileMonitor.cs b/Telerik.Sitefinity.Frontend/FilesMonitoring/FileMonitor.cs index adac0f822..4f4b0435a 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/FileMonitor.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/FileMonitor.cs @@ -1,564 +1,650 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Web; -using System.Web.Hosting; -using Telerik.Sitefinity.Abstractions; -using Telerik.Sitefinity.Frontend.FilesMonitoring.Data; -using Telerik.Sitefinity.Services; - -namespace Telerik.Sitefinity.Frontend.FilesMonitoring -{ - /// - /// This class manages the file monitoring and is responsible to fire events on changes in the observed file structure. - /// - public class FileMonitor : IFileMonitor - { - #region IFileMonitor methods - - /// - /// Observes the resources locations, watch for changes - /// and take certain actions depending on the change - /// - /// The monitored directories. - public void Start(IList directoriesInfo) - { - if (this.rootWatcher == null) - { - this.AddRootWatcher(); - } - - foreach (var directory in directoriesInfo) - { - var direcotryPath = this.MapPath(directory.Path); - - if (this.WatchedFoldersAndPackages.Contains(directory)) - continue; - - DirectoryInfo dir = new DirectoryInfo(direcotryPath); - - if (!dir.Exists) - { - this.QueuedFoldersAndPackages.Add(directory); - continue; - } - else - { - this.WatchedFoldersAndPackages.Add(directory); - this.ProcessDirecotryFiles(dir); - this.AddFileWatcher(directory); - } - } - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - if (this.fileWatchers != null) - { - foreach (var watcher in this.fileWatchers) - { - if (watcher.Value != null) - { - watcher.Value.Dispose(); - } - } - } - - if (this.rootWatcher != null) - this.rootWatcher.Dispose(); - - GC.SuppressFinalize(this); - } - - #endregion - - #region Protected methods - - /// - /// Takes appropriate actions based on the resource file type - /// - /// The file path. - /// Type of the change. - /// The old file path. - protected virtual void FileChanged(string filePath, FileChangeType changeType, string oldFilePath = "") - { - var virtualFilePath = this.ConvertToVirtualPath(filePath); - var oldFileVirtualPath = this.ConvertToVirtualPath(oldFilePath); - - var watchedDirInfo = this.WatchedFoldersAndPackages.FirstOrDefault(dirInfo => virtualFilePath.StartsWith(dirInfo.Path, StringComparison.Ordinal)); - - if (watchedDirInfo == null) - return; - - string packageName = string.Empty; - - var resourceDirecotryPath = VirtualPathUtility.GetDirectory(virtualFilePath); - var resourceDirectoryTree = resourceDirecotryPath.Split('/'); - - if (resourceDirectoryTree.Length < 3) - return; - - if (watchedDirInfo.IsPackage) - packageName = resourceDirectoryTree[2]; - - string resourceFolder = resourceDirectoryTree[resourceDirectoryTree.Length - 2]; - - var fileName = virtualFilePath.Replace(resourceDirecotryPath, string.Empty); - - SystemManager.RunWithElevatedPrivilegeDelegate elevDelegate = this.GetFileChangedDelegate(new FileChangedDelegateArguments() - { - FilePath = virtualFilePath, - ChangeType = changeType, - OldFilePath = oldFileVirtualPath, - PackageName = packageName, - ResourceFolder = resourceFolder, - FileName = fileName - }); - SystemManager.RunWithElevatedPrivilege(elevDelegate); - } - - /// - /// Removes the non existing files data. - /// - protected virtual void RemoveNonExistingData() - { - SystemManager.RunWithElevatedPrivilegeDelegate elevDelegate = (p) => - { - var fileMonitorDataManager = FileMonitorDataManager.GetManager(); - - // finds all records containing file paths which no longer exists - var nonExistingFilesData = fileMonitorDataManager.GetFilesData().Select(fd => fd.FilePath).ToArray() - .Where(f => !File.Exists(f)); - - if (nonExistingFilesData != null && nonExistingFilesData.Any()) - { - // remove all records in the lists - foreach (var filePath in nonExistingFilesData) - { - var resourceDirectoryTree = VirtualPathUtility.GetDirectory(filePath).Split('/'); - - if (resourceDirectoryTree.Length >= 2) - { - string resourceFolder = resourceDirectoryTree[resourceDirectoryTree.Length - 2]; - IFileManager resourceFilesManager = this.GetResourceFileManager(resourceFolder); - resourceFilesManager.FileDeleted(filePath); - } - } - } - }; - - SystemManager.RunWithElevatedPrivilege(elevDelegate); - } - - /// - /// Gets the resource file manager. - /// - /// Type of the resource. - /// FileManager - protected virtual IFileManager GetResourceFileManager(string resourceFolder) - { - IFileManager resourceFilesManager = null; - var resourceType = this.GetResourceType(resourceFolder); - - // the resource folder must follow the convention and the folder name must corresponds to a resource type - if (resourceType != null) - { - if (ObjectFactory.IsTypeRegistered(resourceType.ToString())) - resourceFilesManager = ObjectFactory.Resolve(resourceType.ToString()); - } - - return resourceFilesManager; - } - - /// - /// Gets the type of the resource. - /// - /// The resource folder. - /// - protected virtual ResourceType? GetResourceType(string resourceFolder) - { - ResourceType resourceType; - if (Enum.TryParse(resourceFolder, true, out resourceType)) - return resourceType; - else - return null; - } - - /// - /// Gets the physical path of the application. - /// - /// - protected virtual string GetApplicationPhysicalPath() - { - return HostingEnvironment.ApplicationPhysicalPath; - } - - /// - /// Maps the virtual path to physical path. - /// - /// The virtual Path. - /// The physical path on the server specified by virtualPath. - protected virtual string MapPath(string virtualPath) - { - return FrontendManager.VirtualPathBuilder.MapPath(virtualPath); - } - - #endregion - - #region Private methods - - /// - /// Adds the root watcher. - /// - private void AddRootWatcher() - { - this.rootWatcher = new FileSystemWatcher(); - - this.rootWatcher.Created += this.OnRootCreated; - this.rootWatcher.Deleted += this.OnRootDeleted; - this.rootWatcher.Renamed += this.OnRootRenamed; - - this.rootWatcher.IncludeSubdirectories = true; - this.rootWatcher.Path = this.GetApplicationPhysicalPath(); - this.rootWatcher.NotifyFilter = NotifyFilters.DirectoryName; - this.rootWatcher.EnableRaisingEvents = true; - - this.RemoveNonExistingData(); - } - - /// - /// Adds the file watcher. - /// - /// The directory. - private void AddFileWatcher(MonitoredDirectory directory) - { - var fileWatcher = new FileSystemWatcher(); - - fileWatcher.IncludeSubdirectories = directory.IsPackage; - fileWatcher.Path = this.MapPath(directory.Path); - fileWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName; - - fileWatcher.Created += this.OnFileCreated; - fileWatcher.Deleted += this.OnFileDeleted; - fileWatcher.Renamed += this.OnFileRenamed; - - fileWatcher.EnableRaisingEvents = true; - - this.FileWatchers.Add(directory.Path, fileWatcher); - } - - /// - /// Removes the file watcher. - /// - /// The queued dir information key. - private void RemoveFileWatcher(string queuedDirInfoKey) - { - if (this.FileWatchers.ContainsKey(queuedDirInfoKey)) - { - var watcher = this.FileWatchers.Where(f => f.Key.Equals(queuedDirInfoKey)).First(); - - watcher.Value.EnableRaisingEvents = false; - - this.FileWatchers.Remove(queuedDirInfoKey); - - watcher.Value.Created -= new FileSystemEventHandler(this.OnFileCreated); - watcher.Value.Deleted -= new FileSystemEventHandler(this.OnFileDeleted); - watcher.Value.Renamed -= new RenamedEventHandler(this.OnFileRenamed); - - watcher.Value.Dispose(); - } - } - - /// - /// Converts to virtual path. - /// - /// The path. - /// - private string ConvertToVirtualPath(string path) - { - var appPhysicalPath = this.GetApplicationPhysicalPath(); - - // converting the file path to a virtual file path - if (!appPhysicalPath.IsNullOrEmpty() && !path.IsNullOrEmpty()) - path = path.Substring(appPhysicalPath.Length - 1); - - var virtualFilePath = path.Replace('\\', '/').Insert(0, "~"); - - return virtualFilePath; - } - - /// - /// Processes all files under a directory, including subfolders. - /// - /// The directory information. - private void ProcessDirecotryFiles(DirectoryInfo dirInfo) - { - var files = dirInfo.GetFiles("*", SearchOption.AllDirectories); - - foreach (var file in files) - { - try - { - var filePath = file.FullName; - this.FileChanged(filePath, FileChangeType.Created); - } - catch (IOException ex) - { - Log.Write(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Exception occurred while processing the file named {0}, details: {1}", file.Name, ex)); - } - } - } - - /// - /// Called when root directory is renamed. - /// - /// The sender. - /// The instance containing the event data. - private void OnRootRenamed(object sender, RenamedEventArgs e) - { - string directoryPath = e.FullPath; - string oldDirecotoryPath = e.OldFullPath; - - this.QueueWatch(oldDirecotoryPath); - - this.StartWatch(directoryPath); - } - - /// - /// Called when root directory is created. - /// - /// The sender. - /// The instance containing the event data. - private void OnRootCreated(object sender, FileSystemEventArgs e) - { - this.StartWatch(e.FullPath); - } - - /// - /// Called when root directory is deleted. - /// - /// The sender. - /// The instance containing the event data. - private void OnRootDeleted(object sender, FileSystemEventArgs e) - { - this.QueueWatch(e.FullPath); - } - - /// - /// Called when a file is renamed. - /// - /// The source. - /// The instance containing the event data. - private void OnFileRenamed(object source, RenamedEventArgs e) - { - if (string.IsNullOrEmpty(Path.GetExtension(e.FullPath))) - { - this.RemoveNonExistingData(); - - DirectoryInfo dirInfo = new DirectoryInfo(e.FullPath); - - if (dirInfo.Exists) - this.ProcessDirecotryFiles(dirInfo); - } - else - { - this.FileChanged(e.FullPath, FileChangeType.Renamed, e.OldFullPath); - } - } - - /// - /// Called when a file is created. - /// - /// The source. - /// The instance containing the event data. - private void OnFileCreated(object source, FileSystemEventArgs e) - { - if (string.IsNullOrEmpty(Path.GetExtension(e.FullPath))) - return; - - this.FileChanged(e.FullPath, FileChangeType.Created); - } - - /// - /// Called when a file is deleted. - /// - /// The source. - /// The instance containing the event data. - private void OnFileDeleted(object source, FileSystemEventArgs e) - { - if (string.IsNullOrEmpty(Path.GetExtension(e.FullPath))) - this.RemoveNonExistingData(); - else - this.FileChanged(e.FullPath, FileChangeType.Deleted); - } - - /// - /// Queues the watch action for certain directory. - /// - /// The directory path. - private void QueueWatch(string directoryPath) - { - var virtualFilePath = this.ConvertToVirtualPath(directoryPath); - - var queuedDirInfo = this.WatchedFoldersAndPackages.FirstOrDefault(dirInfo => dirInfo.Path.StartsWith(virtualFilePath, StringComparison.OrdinalIgnoreCase)); - - if (queuedDirInfo == null) - return; - - this.QueuedFoldersAndPackages.Add(queuedDirInfo); - - this.WatchedFoldersAndPackages.Remove(queuedDirInfo); - - this.RemoveFileWatcher(queuedDirInfo.Path); - - var directories = new List(); - this.Start(directories); - } - - /// - /// Starts the watch action for certain directory. - /// - /// The directory path. - private void StartWatch(string directoryPath) - { - var virtualFilePath = this.ConvertToVirtualPath(directoryPath); - - var queuedDirInfo = this.QueuedFoldersAndPackages.FirstOrDefault(dirInfo => dirInfo.Path.StartsWith(virtualFilePath, StringComparison.OrdinalIgnoreCase)); - - if (queuedDirInfo == null) - return; - - this.QueuedFoldersAndPackages.Remove(queuedDirInfo); - - var directories = new List(); - directories.Add(queuedDirInfo); - this.Start(directories); - } - - /// - /// Gets the file changed delegate. It will call the appropriate methods of when the file structure has changed. - /// - /// The arguments. - /// RunWithElevatedPrivilegeDelegate - private SystemManager.RunWithElevatedPrivilegeDelegate GetFileChangedDelegate(FileChangedDelegateArguments args) - { - return (p) => - { - // get the resource file manager depending on its type - IFileManager resourceFilesManager = this.GetResourceFileManager(args.ResourceFolder); - - if (resourceFilesManager != null) - { - switch (args.ChangeType) - { - case FileChangeType.Created: - { - resourceFilesManager.FileAdded(args.FileName, args.FilePath, args.PackageName); - break; - } - - case FileChangeType.Deleted: - { - resourceFilesManager.FileDeleted(args.FilePath); - break; - } - - case FileChangeType.Renamed: - { - var fileNameStartIndex = args.OldFilePath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase) + 1; - var oldFileName = args.OldFilePath.Substring(fileNameStartIndex); - resourceFilesManager.FileRenamed(args.FileName, oldFileName, args.FilePath, args.OldFilePath, args.PackageName); - break; - } - } - } - }; - } - - #endregion - - #region Private fields - - private Dictionary fileWatchers; - private FileSystemWatcher rootWatcher = null; - private IList queuedFoldersAndPackages; - private IList watchedFoldersAndPackages; - - #endregion - - #region Properties - - /// - /// Gets the watched folders and packages. - /// - internal IList WatchedFoldersAndPackages - { - get - { - if (this.watchedFoldersAndPackages == null) - this.watchedFoldersAndPackages = new List(); - - return this.watchedFoldersAndPackages; - } - } - - /// - /// Gets the queued folders and packages. - /// - internal IList QueuedFoldersAndPackages - { - get - { - if (this.queuedFoldersAndPackages == null) - this.queuedFoldersAndPackages = new List(); - - return this.queuedFoldersAndPackages; - } - } - - /// - /// Gets the file watchers. - /// - /// - /// The file watchers. - /// - internal IDictionary FileWatchers - { - get - { - if (this.fileWatchers == null) - this.fileWatchers = new Dictionary(); - - return this.fileWatchers; - } - } - - #endregion - - #region Private classes - - /// - /// This class represents the arguments for invoking the GetFileChangedDelegate method. - /// - private class FileChangedDelegateArguments - { - public string FilePath { get; set; } - - public FileChangeType ChangeType { get; set; } - - public string OldFilePath { get; set; } - - public string PackageName { get; set; } - - public string ResourceFolder { get; set; } - - public string FileName { get; set; } - } - - #endregion - } -} +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Web; +using System.Web.Hosting; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Frontend.FilesMonitoring.Data; +using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Services; + +namespace Telerik.Sitefinity.Frontend.FilesMonitoring +{ + /// + /// This class manages the file monitoring and is responsible to fire events on changes in the observed file structure. + /// + internal class FileMonitor : IFileMonitor + { + #region IFileMonitor methods + + /// + /// Observes the resources locations, watch for changes + /// and take certain actions depending on the change + /// + /// The monitored directories. + public void Start(IList directoriesInfo) + { + lock (FileMonitor.FileMonitorStartLockObj) + { + if (this.rootWatcher == null) + { + this.AddRootWatcher(); + } + + foreach (var directory in directoriesInfo) + { + var direcotryPath = this.MapPath(directory.Path); + + if (this.WatchedFoldersAndPackages.Contains(directory)) + continue; + + DirectoryInfo dir = new DirectoryInfo(direcotryPath); + + if (!dir.Exists) + { + this.QueuedFoldersAndPackages.Add(directory); + continue; + } + else + { + this.WatchedFoldersAndPackages.Add(directory); + this.ProcessDirecotryFiles(dir); + this.AddFileWatcher(directory); + } + } + } + } + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + if (this.fileWatchers != null) + { + foreach (var watcher in this.fileWatchers) + { + if (watcher.Value != null) + { + watcher.Value.Dispose(); + } + } + } + + if (this.rootWatcher != null) + this.rootWatcher.Dispose(); + + GC.SuppressFinalize(this); + } + + #endregion + + #region Protected methods + + /// + /// Takes appropriate actions based on the resource file type + /// + /// The file path. + /// Type of the change. + /// The file data. + /// The old file path. + protected virtual void FileChanged(string filePath, FileChangeType changeType, string oldFilePath = "", FileData fileData = null) + { + var virtualFilePath = this.ConvertToVirtualPath(filePath); + var oldFileVirtualPath = this.ConvertToVirtualPath(oldFilePath); + + var watchedDirInfo = this.WatchedFoldersAndPackages.FirstOrDefault(dirInfo => virtualFilePath.StartsWith(dirInfo.Path, StringComparison.Ordinal)); + + if (watchedDirInfo == null) + return; + + string packageName = string.Empty; + + var resourceDirecotryPath = VirtualPathUtility.GetDirectory(virtualFilePath); + var resourceDirectoryTree = resourceDirecotryPath.Split('/'); + + if (resourceDirectoryTree.Length < 3) + return; + + if (watchedDirInfo.IsPackage) + packageName = resourceDirectoryTree[2]; + + string resourceFolder = resourceDirectoryTree[resourceDirectoryTree.Length - 2]; + + var fileName = virtualFilePath.Replace(resourceDirecotryPath, string.Empty); + + SystemManager.RunWithElevatedPrivilegeDelegate elevDelegate = this.GetFileChangedDelegate(new FileChangedDelegateArguments() + { + FilePath = virtualFilePath, + ChangeType = changeType, + OldFilePath = oldFileVirtualPath, + PackageName = packageName, + ResourceFolder = resourceFolder, + FileName = fileName, + FileData = fileData + }); + + SystemManager.RunWithElevatedPrivilege(elevDelegate); + } + + /// + /// Removes the non existing files data. + /// + protected virtual void RemoveNonExistingData() + { + SystemManager.RunWithElevatedPrivilegeDelegate elevDelegate = (p) => + { + var fileMonitorDataManager = FileMonitorDataManager.GetManager(); + + // finds all records containing file paths which no longer exists + var nonExistingFilesData = fileMonitorDataManager.GetFilesData().Select(fd => fd.FilePath).ToArray() + .Where(f => !HostingEnvironment.VirtualPathProvider.FileExists(f)); + + if (nonExistingFilesData != null && nonExistingFilesData.Any()) + { + // remove all records in the lists + foreach (var filePath in nonExistingFilesData) + { + var resourceDirectoryTree = VirtualPathUtility.GetDirectory(filePath).Split('/'); + + if (resourceDirectoryTree.Length >= 2) + { + var packageFolderIdx = Array.IndexOf(resourceDirectoryTree, PackageManager.PackagesFolder); + string packageName = packageFolderIdx > 0 && packageFolderIdx + 1 < resourceDirectoryTree.Length ? resourceDirectoryTree[packageFolderIdx + 1] : string.Empty; + string resourceFolder = resourceDirectoryTree[resourceDirectoryTree.Length - 2]; + IFileManager resourceFilesManager = this.GetResourceFileManager(resourceFolder, filePath); + resourceFilesManager.FileDeleted(filePath, packageName); + } + } + } + }; + + SystemManager.RunWithElevatedPrivilege(elevDelegate); + } + + /// + /// Gets the resource file manager. + /// + /// The resource folder. + /// The resource path. + /// FileManager + protected virtual IFileManager GetResourceFileManager(string resourceFolder, string resourcePath) + { + IFileManager resourceFilesManager = null; + var resourceType = this.GetResourceType(resourceFolder, resourcePath); + + // the resource folder must follow the convention and the folder name must corresponds to a resource type + if (resourceType != null) + { + if (ObjectFactory.IsTypeRegistered(resourceType.ToString())) + resourceFilesManager = ObjectFactory.Resolve(resourceType.ToString()); + } + + return resourceFilesManager; + } + + /// + /// Gets the type of the resource. + /// + /// The resource folder. + /// The resource path. + /// Resource type + protected virtual ResourceType? GetResourceType(string resourceFolder, string resourcePath) + { + if (resourcePath.Contains("/GridSystem/Templates/")) + return ResourceType.Grid; + + ResourceType resourceType; + if (Enum.TryParse(resourceFolder, true, out resourceType)) + return resourceType; + else + return null; + } + + /// + /// Gets the physical path of the application. + /// + /// + protected virtual string GetApplicationPhysicalPath() + { + return HostingEnvironment.ApplicationPhysicalPath; + } + + /// + /// Maps the virtual path to physical path. + /// + /// The virtual Path. + /// The physical path on the server specified by virtualPath. + protected virtual string MapPath(string virtualPath) + { + return FrontendManager.VirtualPathBuilder.MapPath(virtualPath); + } + + #endregion + + #region Private methods + + private static void CreateFiles(FileMonitor monitor) + { + if (FileMonitor.filesNeedCreation) + { + lock (FileMonitor.FilesNeedCreationLockObj) + { + if (FileMonitor.filesNeedCreation) + { + FileMonitor.filesNeedCreation = false; + + SystemManager.BackgroundTasksService.EnqueueTask(() => + { + Thread.Sleep(1000); + string file; + lock (FileMonitor.FileMonitorStartLockObj) + { + while (FileMonitor.FilesToCreate.TryDequeue(out file)) + { + monitor.FileChanged(file, FileChangeType.Created); + } + } + + Thread.Sleep(1000); + FileMonitor.filesNeedCreation = true; + if (!FileMonitor.FilesToCreate.IsEmpty) + { + CreateFiles(monitor); + } + }); + } + } + } + } + + /// + /// Adds the root watcher. + /// + private void AddRootWatcher() + { + this.rootWatcher = new FileSystemWatcher(); + + this.rootWatcher.Created += this.OnRootCreated; + this.rootWatcher.Deleted += this.OnRootDeleted; + this.rootWatcher.Renamed += this.OnRootRenamed; + + this.rootWatcher.IncludeSubdirectories = true; + this.rootWatcher.Path = this.GetApplicationPhysicalPath(); + this.rootWatcher.NotifyFilter = NotifyFilters.DirectoryName; + this.rootWatcher.EnableRaisingEvents = true; + + this.RemoveNonExistingData(); + } + + /// + /// Adds the file watcher. + /// + /// The directory. + private void AddFileWatcher(MonitoredDirectory directory) + { + var fileWatcher = new FileSystemWatcher(); + + fileWatcher.IncludeSubdirectories = directory.IsPackage; + fileWatcher.Path = this.MapPath(directory.Path); + fileWatcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName; + + fileWatcher.Created += this.OnFileCreated; + fileWatcher.Deleted += this.OnFileDeleted; + fileWatcher.Renamed += this.OnFileRenamed; + + fileWatcher.EnableRaisingEvents = true; + + this.FileWatchers.Add(directory.Path, fileWatcher); + } + + /// + /// Removes the file watcher. + /// + /// The queued dir information key. + private void RemoveFileWatcher(string queuedDirInfoKey) + { + if (this.FileWatchers.ContainsKey(queuedDirInfoKey)) + { + var watcher = this.FileWatchers.Where(f => f.Key.Equals(queuedDirInfoKey)).First(); + + watcher.Value.EnableRaisingEvents = false; + + this.FileWatchers.Remove(queuedDirInfoKey); + + watcher.Value.Created -= new FileSystemEventHandler(this.OnFileCreated); + watcher.Value.Deleted -= new FileSystemEventHandler(this.OnFileDeleted); + watcher.Value.Renamed -= new RenamedEventHandler(this.OnFileRenamed); + + watcher.Value.Dispose(); + } + } + + /// + /// Converts to virtual path. + /// + /// The path. + /// + private string ConvertToVirtualPath(string path) + { + var appPhysicalPath = this.GetApplicationPhysicalPath(); + + // converting the file path to a virtual file path + if (!appPhysicalPath.IsNullOrEmpty() && !path.IsNullOrEmpty()) + { + if (path.StartsWith(appPhysicalPath)) + { + // path within site root + path = path.Substring(appPhysicalPath.Length - 1); + } + else + { + // path within virtual directory + foreach (var monitoredDirectory in this.WatchedFoldersAndPackages) + { + var physicalPath = this.MapPath(monitoredDirectory.Path); + if (path.StartsWith(physicalPath)) + { + // path within site root + path = path.Substring(physicalPath.Length).Replace('\\', '/'); + path = string.Concat(monitoredDirectory.Path, path); + return path; + } + } + } + } + + var virtualFilePath = path.Replace('\\', '/').Insert(0, "~"); + + return virtualFilePath; + } + + /// + /// Processes all files under a directory, including subfolders. + /// + /// The directory information. + private void ProcessDirecotryFiles(DirectoryInfo dirInfo) + { + var files = dirInfo.GetFiles("*", SearchOption.AllDirectories); + + var fileManager = FileMonitorDataManager.GetManager(); + var fileDatasList = fileManager.GetFilesData().ToList(); + + foreach (var file in files) + { + try + { + var virtualFilePath = this.ConvertToVirtualPath(file.FullName); + + // Get the file monitoring data for the files that are already monitored. If the file data exist we don't have to create new monitoring for this file. + var fileData = fileDatasList.Where(x => x.FilePath.Equals(virtualFilePath, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); + + this.FileChanged(file.FullName, FileChangeType.Created, fileData: fileData); + } + catch (IOException ex) + { + Log.Write(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Exception occurred while processing the file named {0}, details: {1}", file.Name, ex)); + } + } + } + + /// + /// Called when root directory is renamed. + /// + /// The sender. + /// The instance containing the event data. + private void OnRootRenamed(object sender, RenamedEventArgs e) + { + string directoryPath = e.FullPath; + string oldDirecotoryPath = e.OldFullPath; + + this.QueueWatch(oldDirecotoryPath); + + this.StartWatch(directoryPath); + } + + /// + /// Called when root directory is created. + /// + /// The sender. + /// The instance containing the event data. + private void OnRootCreated(object sender, FileSystemEventArgs e) + { + this.StartWatch(e.FullPath); + } + + /// + /// Called when root directory is deleted. + /// + /// The sender. + /// The instance containing the event data. + private void OnRootDeleted(object sender, FileSystemEventArgs e) + { + this.QueueWatch(e.FullPath); + } + + /// + /// Called when a file is renamed. + /// + /// The source. + /// The instance containing the event data. + private void OnFileRenamed(object source, RenamedEventArgs e) + { + if (string.IsNullOrEmpty(Path.GetExtension(e.FullPath))) + { + this.RemoveNonExistingData(); + + DirectoryInfo dirInfo = new DirectoryInfo(e.FullPath); + + if (dirInfo.Exists) + this.ProcessDirecotryFiles(dirInfo); + } + else + { + this.FileChanged(e.FullPath, FileChangeType.Renamed, e.OldFullPath); + } + } + + /// + /// Called when a file is created. + /// + /// The source. + /// The instance containing the event data. + private void OnFileCreated(object source, FileSystemEventArgs e) + { + if (string.IsNullOrEmpty(Path.GetExtension(e.FullPath))) + return; + + FilesToCreate.Enqueue(e.FullPath); + CreateFiles(this); + } + + /// + /// Called when a file is deleted. + /// + /// The source. + /// The instance containing the event data. + private void OnFileDeleted(object source, FileSystemEventArgs e) + { + if (string.IsNullOrEmpty(Path.GetExtension(e.FullPath))) + this.RemoveNonExistingData(); + else + this.FileChanged(e.FullPath, FileChangeType.Deleted); + } + + /// + /// Queues the watch action for certain directory. + /// + /// The directory path. + private void QueueWatch(string directoryPath) + { + var virtualFilePath = this.ConvertToVirtualPath(directoryPath); + + var queuedDirInfo = this.WatchedFoldersAndPackages.FirstOrDefault(dirInfo => dirInfo.Path.StartsWith(virtualFilePath, StringComparison.OrdinalIgnoreCase)); + + if (queuedDirInfo == null) + return; + + this.QueuedFoldersAndPackages.Add(queuedDirInfo); + + this.WatchedFoldersAndPackages.Remove(queuedDirInfo); + + this.RemoveFileWatcher(queuedDirInfo.Path); + + var directories = new List(); + this.Start(directories); + } + + /// + /// Starts the watch action for certain directory. + /// + /// The directory path. + private void StartWatch(string directoryPath) + { + var virtualFilePath = this.ConvertToVirtualPath(directoryPath); + + var queuedDirInfo = this.QueuedFoldersAndPackages.FirstOrDefault(dirInfo => dirInfo.Path.StartsWith(virtualFilePath, StringComparison.OrdinalIgnoreCase)); + + if (queuedDirInfo == null) + return; + + this.QueuedFoldersAndPackages.Remove(queuedDirInfo); + + var directories = new List(); + directories.Add(queuedDirInfo); + this.Start(directories); + } + + /// + /// Gets the file changed delegate. It will call the appropriate methods of when the file structure has changed. + /// + /// The arguments. + /// RunWithElevatedPrivilegeDelegate + private SystemManager.RunWithElevatedPrivilegeDelegate GetFileChangedDelegate(FileChangedDelegateArguments args) + { + return (p) => + { + // get the resource file manager depending on its type + IFileManager resourceFilesManager = this.GetResourceFileManager(args.ResourceFolder, args.FilePath); + + if (resourceFilesManager != null) + { + switch (args.ChangeType) + { + case FileChangeType.Created: + { + resourceFilesManager.FileAdded(args.FileName, args.FilePath, args.FileData, args.PackageName); + break; + } + + case FileChangeType.Deleted: + { + resourceFilesManager.FileDeleted(args.FilePath, args.PackageName); + break; + } + + case FileChangeType.Renamed: + { + var fileNameStartIndex = args.OldFilePath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase) + 1; + var oldFileName = args.OldFilePath.Substring(fileNameStartIndex); + resourceFilesManager.FileRenamed(args.FileName, oldFileName, args.FilePath, args.OldFilePath, args.PackageName); + break; + } + } + } + }; + } + + #endregion + + #region Private fields + + private Dictionary fileWatchers; + private FileSystemWatcher rootWatcher = null; + private IList queuedFoldersAndPackages; + private IList watchedFoldersAndPackages; + + private static readonly ConcurrentQueue FilesToCreate = new ConcurrentQueue(); + private static bool filesNeedCreation = true; + private static readonly object FilesNeedCreationLockObj = new object(); + private static readonly object FileMonitorStartLockObj = new object(); + + #endregion + + #region Properties + + /// + /// Gets the watched folders and packages. + /// + internal IList WatchedFoldersAndPackages + { + get + { + if (this.watchedFoldersAndPackages == null) + this.watchedFoldersAndPackages = new List(); + + return this.watchedFoldersAndPackages; + } + } + + /// + /// Gets the queued folders and packages. + /// + internal IList QueuedFoldersAndPackages + { + get + { + if (this.queuedFoldersAndPackages == null) + this.queuedFoldersAndPackages = new List(); + + return this.queuedFoldersAndPackages; + } + } + + /// + /// Gets the file watchers. + /// + /// + /// The file watchers. + /// + internal IDictionary FileWatchers + { + get + { + if (this.fileWatchers == null) + this.fileWatchers = new Dictionary(); + + return this.fileWatchers; + } + } + + #endregion + + #region Private classes + + /// + /// This class represents the arguments for invoking the GetFileChangedDelegate method. + /// + private class FileChangedDelegateArguments + { + public string FilePath { get; set; } + + public FileChangeType ChangeType { get; set; } + + public string OldFilePath { get; set; } + + public string PackageName { get; set; } + + public string ResourceFolder { get; set; } + + public string FileName { get; set; } + + public FileData FileData { get; set; } + } + + #endregion + } +} diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/FileMonitoringInitializer.cs b/Telerik.Sitefinity.Frontend/FilesMonitoring/FileMonitoringInitializer.cs index 2193c1111..c1111b12d 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/FileMonitoringInitializer.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/FileMonitoringInitializer.cs @@ -1,38 +1,126 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; +using System.Configuration; using Telerik.Microsoft.Practices.Unity; using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Configuration; using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Utilities.TypeConverters; namespace Telerik.Sitefinity.Frontend.FilesMonitoring { /// /// This class contains logic for configuring the file monitoring functionality. /// - public class FileMonitoringInitializer + internal class FileMonitoringInitializer : IInitializer { /// /// Initializes and configure file monitoring functionality. /// public void Initialize() { - ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); - ObjectFactory.Container.RegisterType(ResourceType.Layouts.ToString(), new ContainerControlledLifetimeManager()); + if (!ObjectFactory.IsTypeRegistered(typeof(IFileMonitor))) + { + ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); + } + + if (!ObjectFactory.IsTypeRegistered(ResourceType.Layouts.ToString())) + { + ObjectFactory.Container.RegisterType(ResourceType.Layouts.ToString(), new ContainerControlledLifetimeManager()); + } + + if (!ObjectFactory.IsTypeRegistered(ResourceType.Grid.ToString())) + { + ObjectFactory.Container.RegisterType(ResourceType.Grid.ToString(), new ContainerControlledLifetimeManager()); + } this.RegisterFileObservers(); } + /// + /// Uninitializes the file monitoring functionality. + /// + public void Uninitialize() + { + if (this.fileMonitor != null) + { + this.fileMonitor.Dispose(); + } + } + /// /// Registers the file observers. /// private void RegisterFileObservers() { - var fileObserver = ObjectFactory.Resolve(); + if (this.IsFileMonitoringEnabled()) + { + this.fileMonitor = ObjectFactory.Resolve(); + + var monitoredDirectories = new List(); + + monitoredDirectories.Add(new MonitoredDirectory("~/" + PackageManager.PackagesFolder, true)); + monitoredDirectories.Add(new MonitoredDirectory("~/Mvc/Views/Layouts", false)); + monitoredDirectories.Add(new MonitoredDirectory("~/GridSystem/Templates", false)); + + this.fileMonitor.Start(monitoredDirectories); + } + } + + private bool IsFileMonitoringEnabled() + { + // temporary solution to avoid any public APIs + var enableWatcherSetting = ConfigurationManager.AppSettings["sf:featherFileSystemWatcherBehaviour"]; + if (!string.IsNullOrEmpty(enableWatcherSetting)) + { + if (string.Equals(enableWatcherSetting, "true", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + else if (string.Equals(enableWatcherSetting, "false", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + } + + ////var sectionType = TypeResolutionService.ResolveType("Telerik.Sitefinity.SiteSync.Configuration.SiteSyncConfig", false); + ////if (sectionType != null) + ////{ + //// try + //// { + //// var siteSyncConfig = Config.Get(sectionType); + //// var isTarget = (bool)siteSyncConfig["enabledAsTarget"]; + //// if (isTarget) + //// return false; + //// } + //// catch (Exception) + //// { + //// // the config is not available + //// } + ////} - var monitoredDirectories = new List(); - monitoredDirectories.Add(new MonitoredDirectory("~/" + PackageManager.PackagesFolder, true)); - monitoredDirectories.Add(new MonitoredDirectory("~/Mvc/Views/Layouts", false)); + ////var sectionType = TypeResolutionService.ResolveType("Telerik.Sitefinity.Packaging.Configuration.PackagingConfig", false); + ////if (sectionType != null) + ////{ + //// try + //// { + //// var packagingConfig = Config.Get(sectionType); + //// var packagingMode = packagingConfig["packagingMode"]; - fileObserver.Start(monitoredDirectories); + //// var enumType = TypeResolutionService.ResolveType("Telerik.Sitefinity.Packaging.Restriction.PackagingMode", true); + //// var enumName = Enum.GetName(enumType, packagingMode); + //// if (enumName == "Target") + //// return false; + //// } + //// catch (Exception) + //// { + //// // the config is not available + //// } + ////} + + return true; } + + private IFileMonitor fileMonitor; } } diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/GridFileManager.cs b/Telerik.Sitefinity.Frontend/FilesMonitoring/GridFileManager.cs new file mode 100644 index 000000000..7b885edb5 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/GridFileManager.cs @@ -0,0 +1,245 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Web.Hosting; +using Telerik.Sitefinity.Frontend.FilesMonitoring.Data; +using Telerik.Sitefinity.Frontend.GridSystem; +using Telerik.Sitefinity.Frontend.Resources; + +namespace Telerik.Sitefinity.Frontend.FilesMonitoring +{ + /// + /// This class manages the behavior when a grid file is moved over the application folder structure. + /// + internal class GridFileManager : IFileManager + { + #region Properties + + /// + /// Gets the required folder path structure. Only grid files placed inside the specified folder structure will trigger automatic creation of the templates. + /// + /// + /// The folder path structure. + /// + protected virtual IEnumerable FolderPathStructure + { + get + { + if (this.folderPathStructure == null) + this.folderPathStructure = new string[] { "GridSystem", "Templates" }; + + return this.folderPathStructure; + } + } + + /// + /// Gets the widget registrator. + /// + /// + /// The widget registrator. + /// + protected virtual GridWidgetRegistrator WidgetRegistrator + { + get + { + return new GridWidgetRegistrator(); + } + } + + #endregion + + #region IFileManager + + /// + /// Process the file if such is added to the existing folder. + /// + /// Name of the file. + /// The file path. + /// The file data. + /// Name of the package. + public void FileAdded(string fileName, string filePath, FileData fileData, string packageName = "") + { + var fileMonitorDataManager = FileMonitorDataManager.GetManager(); + + if (this.AddToToolboxAndFileData(fileMonitorDataManager, fileName, filePath, packageName, fileData)) + { + fileMonitorDataManager.SaveChanges(); + } + } + + /// + /// Called on file deletion + /// + /// The file path. + /// Name of the package. + public void FileDeleted(string filePath, string packageName) + { + var fileMonitorDataManager = FileMonitorDataManager.GetManager(); + var fileData = fileMonitorDataManager.GetFilesData().Where(file => file.FilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); + + if (fileData != null) + { + fileMonitorDataManager.Delete(fileData); + fileMonitorDataManager.SaveChanges(); + } + + this.WidgetRegistrator.UnregisterToolboxItem(this.GetFileName(filePath)); + } + + /// + /// Reacts on file renaming + /// + /// New name of the file. + /// Old name of the file. + /// + /// + /// Name of the package. + public void FileRenamed(string newFileName, string oldFileName, string newFilePath, string oldFilePath, string packageName = "") + { + var fileMonitorDataManager = FileMonitorDataManager.GetManager(); + var fileData = fileMonitorDataManager.GetFilesData().Where(file => file.FilePath.Equals(oldFilePath, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); + + if (fileData != null) + { + fileData.FilePath = newFilePath; + if (this.AddToToolboxAndFileData(fileMonitorDataManager, newFileName, newFilePath, packageName, fileData, oldFileName)) + { + this.WidgetRegistrator.UpdateControlData(newFileName, oldFileName); + fileMonitorDataManager.SaveChanges(); + } + else + { + fileMonitorDataManager.Delete(fileData); + fileMonitorDataManager.SaveChanges(); + } + } + else + { + this.FileAdded(newFileName, newFilePath, null, packageName); + } + } + + #endregion + + #region Private methods + + private bool AddToToolboxAndFileData(FileMonitorDataManager fileMonitorDataManager, string newFileName, string newFilePath, string packageName, FileData fileData, string oldFileName = "") + { + if (!this.IsFileValid(newFileName, newFilePath, packageName)) + return false; + + this.WidgetRegistrator.RegisterToolboxItem(newFileName, oldFileName); + + return this.CreateOrUpdateFileData(fileMonitorDataManager, newFileName, newFilePath, packageName, fileData); + } + + /// + /// Determines whether a file exists on the specified location and whether it is applicable for the current application. + /// + /// + /// Valid locations depends on the values inside the . + /// + /// The file path. + /// Name of the package. + /// true if the file exists and is placed under the application root in a folder [package]/GridSystem/Templates/ . + private bool IsFileInValidFolder(string filePath, string packageName = "") + { + bool isFileInValidFolder = false; + + FileInfo info = new FileInfo(filePath); + + if (!info.Exists) + return false; + + var directory = info.Directory; + + var expectedGridFolderStructure = string.Join(Path.DirectorySeparatorChar.ToString(), this.FolderPathStructure); + + if (!string.IsNullOrEmpty(packageName)) + expectedGridFolderStructure = expectedGridFolderStructure.Insert(0, packageName + Path.DirectorySeparatorChar); + + var resourcePackagesPath = FrontendManager.VirtualPathBuilder.MapPath(string.Concat("~/", PackageManager.PackagesFolder)); + if (directory.FullName.EndsWith(expectedGridFolderStructure, StringComparison.OrdinalIgnoreCase) && + ( + directory.FullName.StartsWith(HostingEnvironment.ApplicationPhysicalPath, StringComparison.OrdinalIgnoreCase) || + directory.FullName.StartsWith(resourcePackagesPath, StringComparison.OrdinalIgnoreCase) + ) + ) + isFileInValidFolder = true; + + return isFileInValidFolder; + } + + /// + /// Determines whether specified file is exist and is eligible for registration. + /// + /// Name of the file. + /// The file path. + /// Name of the package. + /// + private bool IsFileValid(string fileName, string filePath, string packageName) + { + var extension = fileName.Split('.').LastOrDefault(); + var absolutePath = FrontendManager.VirtualPathBuilder.MapPath(filePath); + var isSupproted = extension == GridFileManager.GridTemplateExtension; + + var isValid = isSupproted && this.IsFileInValidFolder(absolutePath, packageName); + + return isValid; + } + + private bool CreateOrUpdateFileData(FileMonitorDataManager dataManager, string fileName, string filePath, string packageName, FileData fileData) + { + var changed = false; + if (fileData == null) + { + fileData = dataManager.CreateFileData(); + fileData.FilePath = filePath; + changed = true; + } + + if (fileData.FileName != fileName) + { + fileData.FileName = fileName; + changed = true; + } + + if (fileData.PackageName != packageName) + { + fileData.PackageName = packageName; + changed = true; + } + + return changed; + } + + /// + /// Gets the name of the file. + /// + /// The file path. + /// + private string GetFileName(string filePath) + { + var fileName = filePath.Substring(filePath.LastIndexOf('/') + 1); + + return fileName; + } + + #endregion + + #region Private fileds and constants + + /// + /// The folder path structure + /// + private string[] folderPathStructure; + + /// + /// Allowed extension for grid template files. + /// + internal const string GridTemplateExtension = "html"; + + #endregion + } +} diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/IFileManager.cs b/Telerik.Sitefinity.Frontend/FilesMonitoring/IFileManager.cs index ba6ac454c..8097346ae 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/IFileManager.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/IFileManager.cs @@ -1,29 +1,35 @@ -namespace Telerik.Sitefinity.Frontend.FilesMonitoring +using Telerik.Sitefinity.Frontend.FilesMonitoring.Data; + +namespace Telerik.Sitefinity.Frontend.FilesMonitoring { /// /// Classes that implement this interface should define the Sitefinity's behavior when a file is moved over the application folder structure. /// - public interface IFileManager + internal interface IFileManager { /// /// Reacts when a file is added to the folder. /// - /// The virtual file path. + /// Name of the file. + /// The file path. + /// The file data. /// Name of the package. - void FileAdded(string fileName, string filePath, string packageName = ""); + void FileAdded(string fileName, string filePath, FileData fileData, string packageName = ""); /// /// Reacts on file deletion. /// - /// The file path. - void FileDeleted(string filePath); + /// The file path. + /// Name of the package. + void FileDeleted(string filePath, string packageName = ""); /// /// Reacts on file renaming. /// /// New name of the file. /// Old name of the file. - /// The file path. + /// The new file path. + /// The old file path. /// Name of the package. void FileRenamed(string newFileName, string oldFileName, string newFilePath, string oldFilePath, string packageName = ""); } diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/IFileMonitor.cs b/Telerik.Sitefinity.Frontend/FilesMonitoring/IFileMonitor.cs index 5ff438a49..9c31caf7f 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/IFileMonitor.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/IFileMonitor.cs @@ -7,7 +7,7 @@ namespace Telerik.Sitefinity.Frontend.FilesMonitoring /// Classes that implement this interface must observe the resource locations, watch for changes /// and take certain actions depending on the change. ///
- public interface IFileMonitor : IDisposable + internal interface IFileMonitor : IDisposable { /// /// Starts this instance. diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/LayoutFileManager.cs b/Telerik.Sitefinity.Frontend/FilesMonitoring/LayoutFileManager.cs index 2c64ce7d0..2f2bfc6dc 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/LayoutFileManager.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/LayoutFileManager.cs @@ -1,244 +1,724 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Web; -using System.Web.Hosting; -using System.Web.Mvc; -using Telerik.Sitefinity.Abstractions; -using Telerik.Sitefinity.Configuration; -using Telerik.Sitefinity.Data; -using Telerik.Sitefinity.Frontend.FilesMonitoring.Data; -using Telerik.Sitefinity.Modules.Pages; -using Telerik.Sitefinity.Multisite; -using Telerik.Sitefinity.Project.Configuration; -using Telerik.Sitefinity.Services; -using Telerik.Sitefinity.Web.UI; - -namespace Telerik.Sitefinity.Frontend.FilesMonitoring -{ - /// - /// This class manages the behavior when a layout file is moved over the application folder structure. - /// - public class LayoutFileManager : IFileManager - { - #region Properties - - /// - /// Gets the required folder path structure. Only layout files placed inside the specified folder structure will trigger automatic creation of the templates. - /// - /// - /// The folder path structure. - /// - public virtual ICollection FolderPathStructure - { - get - { - if (this.folderPathStructure == null) - this.folderPathStructure = new List { "Mvc", "Views" }; - - return this.folderPathStructure; - } - } - - #endregion - - #region IFileManager - - /// - /// Process the file if such is added to the existing folder. - /// - /// The virtual file path. - /// Name of the package. - public void FileAdded(string fileName, string filePath, string packageName = "") - { - var fileMonitorDataManager = FileMonitorDataManager.GetManager(); - - var fileData = fileMonitorDataManager.GetFilesData().Where(file => file.FilePath.Equals(filePath, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); - - this.CreateTemplateAndFileData(fileName, filePath, packageName, fileMonitorDataManager, fileData); - } - - /// - /// Called on file deletion - /// - /// The file path. - public void FileDeleted(string filePath) - { - var fileMonitorDataManager = FileMonitorDataManager.GetManager(); - - var fileData = fileMonitorDataManager.GetFilesData().Where(file => file.FilePath.Equals(filePath, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); - - if (fileData != null) - { - fileMonitorDataManager.Delete(fileData); - fileMonitorDataManager.SaveChanges(); - } - } - - /// - /// Reacts on file renaming - /// - /// New name of the file. - /// Old name of the file. - /// - /// - /// Name of the package. - public void FileRenamed(string newFileName, string oldFileName, string newFilePath, string oldFilePath, string packageName = "") - { - var fileMonitorDataManager = FileMonitorDataManager.GetManager(); - - var fileData = fileMonitorDataManager.GetFilesData().Where(file => file.FilePath.Equals(oldFilePath, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); - - if (fileData != null) - this.CreateTemplateAndFileData(newFileName, newFilePath, packageName, fileMonitorDataManager, fileData); - else - this.FileAdded(newFileName, newFilePath, packageName); - } - - #endregion - - #region Private methods - - /// - /// Determines whether a file exists on the specified location and whether it is applicable for the current application. - /// - /// - /// Valid locations depends on the values inside the . - /// - /// The file path. - /// Name of the package. - /// true if the file exists and is placed under the application root in a folder [package]/Mvc/Views/Layouts. - private bool IsFileInValidFolder(string filePath, string packageName = "") - { - bool isFileInValidFolder = false; - - FileInfo info = new FileInfo(filePath); - - if (!info.Exists) - return false; - - var directory = info.Directory; - - var expectedBaseFolderStructure = string.Join(Path.DirectorySeparatorChar.ToString(), this.FolderPathStructure); - var expectedLayoutFolderStructure = expectedBaseFolderStructure + Path.DirectorySeparatorChar + ResourceType.Layouts.ToString(); - - if (!string.IsNullOrEmpty(packageName)) - expectedLayoutFolderStructure = packageName + Path.DirectorySeparatorChar + expectedLayoutFolderStructure; - - if (directory.FullName.EndsWith(expectedLayoutFolderStructure, StringComparison.OrdinalIgnoreCase) && directory.FullName.StartsWith(HostingEnvironment.ApplicationPhysicalPath, StringComparison.OrdinalIgnoreCase)) - isFileInValidFolder = true; - - return isFileInValidFolder; - } - - /// - /// Creates the template and file data. - /// - /// Name of the file. - /// The file path. - /// Name of the package. - /// The file monitor data manager. - /// The file data. - private void CreateTemplateAndFileData(string fileName, string filePath, string packageName, FileMonitorDataManager fileMonitorDataManager, FileData fileData) - { - var absolutePath = FrontendManager.VirtualPathBuilder.MapPath(filePath); - - if (!this.IsFileInValidFolder(absolutePath, packageName)) - return; - - var extension = fileName.Split('.').LastOrDefault(); - var fileNameWithoutExtension = fileName.Substring(0, fileName.Length - (extension.Length + 1)); - - var viewFileExtensions = this.GetViewExtensions(); - - if (viewFileExtensions.Contains(extension, StringComparer.Ordinal)) - { - string templateTitle = string.Empty; - - if (string.IsNullOrEmpty(packageName)) - templateTitle = fileNameWithoutExtension; - else - templateTitle = packageName + "." + fileNameWithoutExtension; - - if (fileData == null) - fileData = fileMonitorDataManager.CreateFileData(); - - fileData.FilePath = filePath; - fileData.FileName = fileName; - fileData.PackageName = packageName; - - fileMonitorDataManager.SaveChanges(); - - this.CreateTemplate(templateTitle); - } - } - - /// - /// Gets the allowed views extensions. - /// - /// - private string[] GetViewExtensions() - { - return ViewEngines.Engines.OfType() - .SelectMany(p => p.FileExtensions).ToArray(); - } - - /// - /// Creates the page template. - /// - /// The template title. - private void CreateTemplate(string templateTitle) - { - var multisiteContext = SystemManager.CurrentContext as MultisiteContext; - var prevSite = SystemManager.CurrentContext.CurrentSite; - if (multisiteContext != null) - { - var id = Config.Get().DefaultSite.Id; - multisiteContext.ChangeCurrentSite(multisiteContext.GetSiteById(id)); - } - - try - { - PageManager pageManager = PageManager.GetManager(); - using (new ElevatedModeRegion(pageManager)) - { - if (pageManager.GetTemplates().Where(pt => pt.Title.Equals(templateTitle, StringComparison.InvariantCultureIgnoreCase)).Count() == 0) - { - var template = pageManager.CreateTemplate(); - - template.Category = SiteInitializer.CustomTemplatesCategoryId; - template.Name = templateTitle; - template.Title = templateTitle; - template.Framework = Pages.Model.PageTemplateFramework.Mvc; - template.Theme = ThemeController.NoThemeName; - - var languageData = pageManager.CreatePublishedInvarianLanguageData(); - template.LanguageData.Add(languageData); - - pageManager.SaveChanges(); - - var master = pageManager.TemplatesLifecycle.Edit(template); - pageManager.TemplatesLifecycle.Publish(master); - pageManager.SaveChanges(); - } - } - } - finally - { - if (multisiteContext != null) - { - multisiteContext.ChangeCurrentSite(prevSite); - } - } - } - - #endregion - - #region Private fileds - - private List folderPathStructure; - - #endregion - } -} +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using System.Web.Hosting; +using System.Web.Mvc; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Data; +using Telerik.Sitefinity.Frontend.FilesMonitoring.Data; +using Telerik.Sitefinity.Frontend.GridSystem; +using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Libraries.Model; +using Telerik.Sitefinity.Modules.Libraries; +using Telerik.Sitefinity.Modules.Libraries.ImageProcessing; +using Telerik.Sitefinity.Modules.Libraries.Images; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Multisite; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Services.RelatedData.Messages; +using Telerik.Sitefinity.Taxonomies; +using Telerik.Sitefinity.Taxonomies.Model; +using Telerik.Sitefinity.Web.UI; + +namespace Telerik.Sitefinity.Frontend.FilesMonitoring +{ + /// + /// This class manages the behavior when a layout file is moved over the application folder structure. + /// + [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Code that works with the PageManager could be moved away from this class.")] + internal class LayoutFileManager : IFileManager + { + #region Properties + + /// + /// Gets the required folder path structure. Only layout files placed inside the specified folder structure will trigger automatic creation of the templates. + /// + /// + /// The folder path structure. + /// + public virtual ICollection FolderPathStructure + { + get + { + if (this.folderPathStructure == null) + this.folderPathStructure = new List { "Mvc", "Views" }; + + return this.folderPathStructure; + } + } + + #endregion + + #region Public methods + + /// + /// Gets the or create template category identifier. + /// + /// The template category name. + /// if set to true [create if not exist]. + /// The id of the category. + public virtual Guid GetOrCreateTemplateCategoryId(string templateCategoryName, bool createIfNotExist = true) + { + if (string.IsNullOrWhiteSpace(templateCategoryName)) + return SiteInitializer.CustomTemplatesCategoryId; + + var createdIds = this.CreateTemplateCategories(new HashSet() { templateCategoryName }, createIfNotExist); + + return createdIds[0]; + } + + /// + /// Attaches image to a template (if available). + /// + /// The template. + /// The page manager. + /// Name of the image file. + public virtual void AttachImageToTemplate(PageTemplate template, PageManager pageManager, string imageName) + { + var templateImage = this.GetTemplateImage(template, imageName); + if (templateImage != null) + { + this.AddTemplatePresentation(template, pageManager, imageName); + this.AddTemplateRelatedData(template, templateImage, pageManager); + } + } + + #endregion + + #region IFileManager + + /// + /// Process the file if such is added to the existing folder. + /// + /// The virtual file name. + /// The virtual file path. + /// The file data + /// Name of the package. + public void FileAdded(string fileName, string filePath, FileData fileData, string packageName = "") + { + var fileMonitorDataManager = FileMonitorDataManager.GetManager(); + + if (fileData == null && this.CreateTemplateAndFileData(fileName, filePath, packageName, fileMonitorDataManager, ref fileData)) + { + fileMonitorDataManager.SaveChanges(); + } + } + + /// + /// Called on file deletion + /// + /// The file path. + /// Name of the package. + public void FileDeleted(string filePath, string packageName) + { + var fileMonitorDataManager = FileMonitorDataManager.GetManager(); + + var fileData = fileMonitorDataManager.GetFilesData().Where(file => file.FilePath.Equals(filePath, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); + + if (fileData != null) + { + fileMonitorDataManager.Delete(fileData); + fileMonitorDataManager.SaveChanges(); + } + } + + /// + /// Reacts on file renaming + /// + /// New name of the file. + /// Old name of the file. + /// + /// + /// Name of the package. + public void FileRenamed(string newFileName, string oldFileName, string newFilePath, string oldFilePath, string packageName = "") + { + var fileMonitorDataManager = FileMonitorDataManager.GetManager(); + + var fileData = fileMonitorDataManager.GetFilesData().Where(file => file.FilePath.Equals(oldFilePath, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); + + if (fileData != null) + { + fileData.FilePath = newFilePath; + if (this.CreateTemplateAndFileData(newFileName, newFilePath, packageName, fileMonitorDataManager, ref fileData)) + { + fileMonitorDataManager.SaveChanges(); + } + else + { + fileMonitorDataManager.Delete(fileData); + fileMonitorDataManager.SaveChanges(); + } + } + else + { + this.FileAdded(newFileName, newFilePath, null, packageName); + } + } + + #endregion + + #region Internal methods + + /// + /// The same logic can be found in PageTemplateHelper -> UpdateDefaultTemplateImages(). In need of a change do it in both places + /// + internal static void UpdateDefaultTemplateImages(LibrariesManager librariesManager) + { + var imagesToUpgrade = new List + { + LayoutFileManager.TemplateImage1Column, + LayoutFileManager.TemplateImage2Columns, + LayoutFileManager.TemplateImage3Columns, + LayoutFileManager.TemplateImage4Columns, + LayoutFileManager.TemplateImageLeftSidebar, + LayoutFileManager.TemplateImageRightSidebar, + "default" + }; + + var templateThumbsImageLibrary = librariesManager.GetAlbums().FirstOrDefault(lib => lib.Id == LibrariesModule.DefaultTemplateThumbnailsLibraryId); + if (templateThumbsImageLibrary != null) + { + var images = templateThumbsImageLibrary.Images().ToList(); + foreach (var imageToUpgrade in imagesToUpgrade) + { + var image = images.FirstOrDefault(i => i.Title == "MVC_" + imageToUpgrade && i.Status == GenericContent.Model.ContentLifecycleStatus.Master); + + if (image != null) + { + var iconResource = string.Format(CultureInfo.InvariantCulture, LayoutFileManager.PageTemplateIconPathFormat, imageToUpgrade); + if (Assembly.GetExecutingAssembly().GetManifestResourceNames().Any(mrn => mrn.Equals(iconResource, StringComparison.OrdinalIgnoreCase))) + { + using (var imageStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(iconResource)) + { + using (var resourceImage = ImagesHelper.CurrentImageProcessor.GetImageFromStream(imageStream)) + { + var resourceImageStream = new MemoryStream(); + resourceImage.Save(resourceImageStream, System.Drawing.Imaging.ImageFormat.Png); + + librariesManager.Upload(image, resourceImageStream, ".png", true); + librariesManager.Lifecycle.Publish(image); + librariesManager.SaveChanges(); + } + } + } + } + } + } + } + + internal IList CreateTemplateCategories(ISet categoryNames, bool createIfNotExist) + { + var categoryIds = new List(); + var taxonomyManager = TaxonomyManager.GetManager(); + + foreach (var templateCategoryName in categoryNames) + { + var pageTemplatesTaxonomy = taxonomyManager.GetTaxonomy(SiteInitializer.PageTemplatesTaxonomyId); + var templateCategory = pageTemplatesTaxonomy.Taxa.SingleOrDefault(t => t.Name != null && t.Name.Equals(templateCategoryName, StringComparison.OrdinalIgnoreCase)); + + if (templateCategory == null && createIfNotExist) + { + var guid = this.GuidFromString(templateCategoryName); + templateCategory = taxonomyManager.CreateTaxon(guid); + templateCategory.Name = templateCategoryName; + templateCategory.UrlName = templateCategoryName; + templateCategory.RenderAsLink = false; + templateCategory.Title = templateCategoryName; + templateCategory.Description = string.Format(CultureInfo.InvariantCulture, "Represents category for {0} page templates.", templateCategoryName); + + pageTemplatesTaxonomy.Taxa.Add(templateCategory); + categoryIds.Add(guid); + } + else + { + categoryIds.Add(templateCategory.Id); + } + } + + taxonomyManager.SaveChanges(); + + return categoryIds; + } + + internal void CreateDefaultTemplates(string packageName, string layoutFile) + { + var header = new LayoutControlDescription() + { + Caption = LayoutFileManager.LayoutCaptionHeader, + Description = LayoutFileManager.LayoutDescriptionHeader, + Path = LayoutFileManager.GridTemplatePathContainer + }; + + var content = new LayoutControlDescription() + { + Caption = LayoutFileManager.LayoutCaptionContent, + Description = LayoutFileManager.LayoutDescriptionContent, + Path = LayoutFileManager.GridTemplatePathContainer + }; + + var footer = new LayoutControlDescription() + { + Caption = LayoutFileManager.LayoutCaptionFooter, + Description = LayoutFileManager.LayoutDescriptionFooter, + Path = LayoutFileManager.GridTemplatePathContainer + }; + + var twoColumns = new LayoutControlDescription() + { + Caption = LayoutFileManager.LayoutCaption2Columns, + Description = LayoutFileManager.LayoutDescriptionContentColumns, + Path = LayoutFileManager.GridTemplatePath2Columns + }; + + var threeColumns = new LayoutControlDescription() + { + Caption = LayoutFileManager.LayoutCaption3Columns, + Description = LayoutFileManager.LayoutDescriptionContentColumns, + Path = LayoutFileManager.GridTemplatePath3Columns + }; + + var fourColumns = new LayoutControlDescription() + { + Caption = LayoutFileManager.LayoutCaption4Columns, + Description = LayoutFileManager.LayoutDescriptionContentColumns, + Path = LayoutFileManager.GridTemplatePath4Columns + }; + + var leftSidebar = new LayoutControlDescription() + { + Caption = LayoutFileManager.LayoutCaptionContentSidebar, + Description = LayoutFileManager.LayoutDescriptionContentSidebar, + Path = LayoutFileManager.GridTemplatePathLeftSidebar + }; + + var rightSidebar = new LayoutControlDescription() + { + Caption = LayoutFileManager.LayoutCaptionContentSidebar, + Description = LayoutFileManager.LayoutDescriptionContentSidebar, + Path = LayoutFileManager.GridTemplatePathRightSidebar + }; + + if (!packageName.StartsWith("Bootstrap4") && !packageName.StartsWith("Bootstrap5")) + { + this.CreateTemplate(packageName, layoutFile, LayoutFileManager.TemplateCaption2Columns, LayoutFileManager.TemplateImage2Columns, new LayoutControlDescription[] { header, twoColumns, footer }); + this.CreateTemplate(packageName, layoutFile, LayoutFileManager.TemplateCaption3Columns, LayoutFileManager.TemplateImage3Columns, new LayoutControlDescription[] { header, threeColumns, footer }); + this.CreateTemplate(packageName, layoutFile, LayoutFileManager.TemplateCaption4Columns, LayoutFileManager.TemplateImage4Columns, new LayoutControlDescription[] { header, fourColumns, footer }); + } + + this.CreateTemplate(packageName, layoutFile, LayoutFileManager.TemplateCaption1Column, LayoutFileManager.TemplateImage1Column, new LayoutControlDescription[] { header, content, footer }); + this.CreateTemplate(packageName, layoutFile, LayoutFileManager.TemplateCaptionLeftSidebar, LayoutFileManager.TemplateImageLeftSidebar, new LayoutControlDescription[] { header, leftSidebar, footer }); + this.CreateTemplate(packageName, layoutFile, LayoutFileManager.TemplateCaptionRightSidebar, LayoutFileManager.TemplateImageRightSidebar, new LayoutControlDescription[] { header, rightSidebar, footer }); + } + + #endregion + + #region Private methods + + /// + /// Determines whether a file exists on the specified location and whether it is applicable for the current application. + /// + /// + /// Valid locations depends on the values inside the . + /// + /// The file path. + /// Name of the package. + /// true if the file exists and is placed under the application root in a folder [package]/Mvc/Views/Layouts. + private bool IsFileInValidFolder(string filePath, string packageName = "") + { + bool isFileInValidFolder = false; + + FileInfo info = new FileInfo(filePath); + + if (!info.Exists) + return false; + + var directory = info.Directory; + + var expectedBaseFolderStructure = string.Join(Path.DirectorySeparatorChar.ToString(), this.FolderPathStructure); + var expectedLayoutFolderStructure = expectedBaseFolderStructure + Path.DirectorySeparatorChar + ResourceType.Layouts.ToString(); + + if (!string.IsNullOrEmpty(packageName)) + expectedLayoutFolderStructure = packageName + Path.DirectorySeparatorChar + expectedLayoutFolderStructure; + + var resourcePackagesPath = FrontendManager.VirtualPathBuilder.MapPath(string.Concat("~/", PackageManager.PackagesFolder)); + if (directory.FullName.EndsWith(expectedLayoutFolderStructure, StringComparison.OrdinalIgnoreCase) && + ( + directory.FullName.StartsWith(HostingEnvironment.ApplicationPhysicalPath, StringComparison.OrdinalIgnoreCase) || + directory.FullName.StartsWith(resourcePackagesPath, StringComparison.OrdinalIgnoreCase) + ) + ) + isFileInValidFolder = true; + + return isFileInValidFolder; + } + + /// + /// Creates the template and file data. + /// + /// Name of the file. + /// The file path. + /// Name of the package. + /// The file monitor data manager. + /// The file data. + /// + private bool CreateTemplateAndFileData(string fileName, string filePath, string packageName, FileMonitorDataManager fileMonitorDataManager, ref FileData fileData) + { + var absolutePath = FrontendManager.VirtualPathBuilder.MapPath(filePath); + + if (this.IsFileInValidFolder(absolutePath, packageName)) + { + var extension = fileName.Split('.').LastOrDefault(); + var fileNameWithoutExtension = fileName.Substring(0, fileName.Length - (extension.Length + 1)); + + var viewFileExtensions = this.GetViewExtensions(); + + if (viewFileExtensions.Contains(extension, StringComparer.Ordinal)) + { + var changed = false; + if (fileData == null) + { + fileData = fileMonitorDataManager.CreateFileData(); + fileData.FilePath = filePath; + fileData.FileName = fileName; + fileData.PackageName = packageName; + changed = true; + } + else + { + if (fileData.FilePath != filePath) + { + fileData.FilePath = filePath; + changed = true; + } + + if (fileData.FileName != fileName) + { + fileData.FileName = fileName; + changed = true; + } + + if (fileData.PackageName != packageName) + { + fileData.PackageName = packageName; + changed = true; + } + } + + if (changed) + { + this.CreateTemplate(packageName, fileNameWithoutExtension); + return true; + } + } + } + + return false; + } + + /// + /// Gets the allowed views extensions. + /// + /// + private string[] GetViewExtensions() + { + return ViewEngines.Engines.OfType() + .SelectMany(p => p.FileExtensions).ToArray(); + } + + private void CreateTemplate(string packageName, string fileNameWithoutExtension) + { + this.CreateTemplate(packageName, fileNameWithoutExtension, fileNameWithoutExtension, null, null); + } + + private void CreateTemplate(string packageName, string fileNameWithoutExtension, string title, string image, LayoutControlDescription[] layoutControls) + { + var multisiteContext = SystemManager.CurrentContext as MultisiteContext; + var prevSite = SystemManager.CurrentContext.CurrentSite; + if (multisiteContext != null) + { + var defaultSite = multisiteContext.GetSites().Single(s => s.IsDefault); + multisiteContext.ChangeCurrentSite(defaultSite); + } + + try + { + PageManager pageManager = PageManager.GetManager(); + using (new ElevatedModeRegion(pageManager)) + { + var fullTemplateName = string.IsNullOrEmpty(packageName) ? fileNameWithoutExtension : string.Format("{0}.{1}", packageName, fileNameWithoutExtension); + + if (!pageManager.GetTemplates().Any(pt => (string.Compare(pt.Name, fullTemplateName, true) == 0 && string.Compare(pt.Title, title, true) == 0) || string.Compare(pt.Title, fullTemplateName, true) == 0)) + { + var templateGuid = this.GuidFromString(string.Concat(fullTemplateName, title)); + var template = pageManager.CreateTemplate(templateGuid); + + template.Category = this.GetOrCreateTemplateCategoryId(packageName); + template.Name = fullTemplateName; + template.Title = title; + template.Framework = Pages.Model.PageTemplateFramework.Mvc; + template.Theme = ThemeController.NoThemeName; + var languageData = pageManager.CreatePublishedLanguageData(); + template.LanguageData.Add(languageData); + + this.AttachImageToTemplate(template, pageManager, image ?? "default"); + + this.AddLayoutControls(pageManager, template, layoutControls); + + var master = pageManager.TemplatesLifecycle.Edit(template); + pageManager.TemplatesLifecycle.Publish(master); + pageManager.SaveChanges(); + + if (string.Equals(LayoutFileManager.Bootstrap5DefaultTemplateName, fullTemplateName, StringComparison.OrdinalIgnoreCase)) + this.CreateDefaultTemplates("Bootstrap5", "default"); + if (string.Equals(LayoutFileManager.Bootstrap4DefaultTemplateName, fullTemplateName, StringComparison.OrdinalIgnoreCase)) + this.CreateDefaultTemplates("Bootstrap4", "default"); + if (string.Equals(LayoutFileManager.BootstrapDefaultTemplateName, fullTemplateName, StringComparison.OrdinalIgnoreCase)) + this.CreateDefaultTemplates("Bootstrap", "default"); + else if (string.Equals(LayoutFileManager.FoundationDefaultTemplateName, fullTemplateName, StringComparison.OrdinalIgnoreCase)) + this.CreateDefaultTemplates("Foundation", "default"); + else if (string.Equals(LayoutFileManager.SemanticUIDefaultTemplateName, fullTemplateName, StringComparison.OrdinalIgnoreCase)) + this.CreateDefaultTemplates("SemanticUI", "default"); + } + } + } + catch (Exception) + { + Log.Write("Automatic template generation failed. To disable the automatic generation, set 'sf:featherFileSystemWatcherBehaviour' to false in the AppSettings in web.config.", ConfigurationPolicy.ErrorLog); + } + finally + { + if (multisiteContext != null) + { + multisiteContext.ChangeCurrentSite(prevSite); + } + } + } + + private void AddLayoutControls(PageManager pageManager, PageTemplate template, LayoutControlDescription[] layoutControls) + { + if (layoutControls == null) + return; + + var siblingId = Guid.Empty; + for (int i = 0; i < layoutControls.Length; i++) + { + var description = layoutControls[i]; + var layout = new GridControl(); + layout.Layout = description.Path; + var ctrlData = pageManager.CreateControl(isBackendObject: false); + ctrlData.ObjectType = layout.GetType().FullName; + ctrlData.PlaceHolder = "Contentplaceholder1"; + ctrlData.SiblingId = siblingId; + siblingId = ctrlData.Id; + ctrlData.Caption = description.Caption; + ctrlData.Description = description.Description; + + pageManager.ReadProperties(layout, ctrlData); + pageManager.SetControlId(template, ctrlData); + + ctrlData.SetDefaultPermissions(pageManager); + template.Controls.Add(ctrlData); + } + } + + private Image GetTemplateImage(PageTemplate template, string imageName) + { + Image image = null; + + if (template != null) + { + var libraryManager = LibrariesManager.GetManager("SystemLibrariesProvider"); + if (libraryManager != null) + { + var templateThumbsImageLibrary = libraryManager.GetAlbums().FirstOrDefault(lib => lib.Id == LibrariesModule.DefaultTemplateThumbnailsLibraryId); + + if (templateThumbsImageLibrary != null) + { + // Try get image from library + image = templateThumbsImageLibrary.Images().FirstOrDefault(i => i.Title == "MVC_" + imageName && i.Status == GenericContent.Model.ContentLifecycleStatus.Master); + if (image == null) + { + // Check if image is in the resources and upload it + var iconResource = string.Format(LayoutFileManager.PageTemplateIconPathFormat, imageName); + if (Assembly.GetExecutingAssembly().GetManifestResourceNames().Any(mrn => mrn.Equals(iconResource, StringComparison.OrdinalIgnoreCase))) + { + image = this.UploadTemplateImage(libraryManager, templateThumbsImageLibrary, "MVC_" + imageName, iconResource); + } + } + } + } + } + + return image; + } + + private Image UploadTemplateImage(LibrariesManager libraryManager, Album templateThumbsImageLibrary, string templateName, string iconResource) + { + Image image = null; + + var suppressSecurityChecks = libraryManager.Provider.SuppressSecurityChecks; + try + { + libraryManager.Provider.SuppressSecurityChecks = true; + + image = libraryManager.CreateImage(); + image.Parent = templateThumbsImageLibrary; + image.Title = templateName; + image.UrlName = templateName.ToLower().Replace(' ', '-'); + image.Description = "Description_" + templateName; + image.AlternativeText = "AltText_" + templateName; + image.ApprovalWorkflowState = "Published"; + libraryManager.RecompileItemUrls(image); + + using (var imageStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(iconResource)) + { + using (var resourceImage = ImagesHelper.CurrentImageProcessor.GetImageFromStream(imageStream)) + { + var resourceImageStream = new MemoryStream(); + resourceImage.Save(resourceImageStream, System.Drawing.Imaging.ImageFormat.Png); + + libraryManager.Upload(image, resourceImageStream, ".png"); + libraryManager.Lifecycle.Publish(image); + libraryManager.SaveChanges(); + } + } + } + finally + { + libraryManager.Provider.SuppressSecurityChecks = suppressSecurityChecks; + } + + return image; + } + + private void AddTemplatePresentation(PageTemplate template, PageManager pageManager, string imageName) + { + var present = pageManager.CreatePresentationItem(); + present.DataType = Presentation.ImageUrl; + present.Name = "icon"; + present.Theme = ThemeController.NoThemeName; + present.Data = string.Format(LayoutFileManager.PageTemplateIconPathFormat, imageName); + template.Presentation.Add(present); + } + + private void AddTemplateRelatedData(PageTemplate template, Image image, PageManager pageManager) + { + var changedRelations = new ContentLinkChange[] + { + new ContentLinkChange() + { + ChildItemId = image.Id, + ChildItemProviderName = image.GetProviderName(), + ChildItemType = image.GetType().FullName, + ComponentPropertyName = PageTemplate.ThumbnailFieldName, + Ordinal = -2, + State = Telerik.Sitefinity.Web.UI.Fields.Enums.ContentLinkChangeState.Added + } + }; + + var type = Type.GetType("Telerik.Sitefinity.RelatedData.RelatedDataHelper, Telerik.Sitefinity"); + var method = type.GetMethod("SaveRelatedDataChanges", BindingFlags.NonPublic | BindingFlags.Static); + method.Invoke(null, new object[] { pageManager, template, changedRelations, false }); + } + + private Guid GuidFromString(string key) + { + using (var md5 = MD5.Create()) + { + byte[] hash = md5.ComputeHash(Encoding.Default.GetBytes(key)); + return new Guid(hash); + } + } + + #endregion + + #region Private fileds + + private List folderPathStructure; + + #endregion + + #region Private classes + + private class LayoutControlDescription + { + [Localizable(false)] + public string Caption { get; set; } + + [Localizable(false)] + public string Description { get; set; } + + [Localizable(false)] + public string Path { get; set; } + } + + #endregion + + #region Constants + + /// + /// The page template icon path format + /// + public const string PageTemplateIconPathFormat = "Telerik.Sitefinity.Frontend.Resources.PageTemplateImages.{0}.gif"; + + public const string Bootstrap5DefaultTemplateName = "Bootstrap5.default"; + public const string Bootstrap4DefaultTemplateName = "Bootstrap4.default"; + public const string BootstrapDefaultTemplateName = "Bootstrap.default"; + public const string SemanticUIDefaultTemplateName = "SemanticUI.default"; + public const string FoundationDefaultTemplateName = "Foundation.default"; + + public static readonly string[] DefaultTemplateNames = new string[] + { + LayoutFileManager.Bootstrap5DefaultTemplateName, + LayoutFileManager.Bootstrap4DefaultTemplateName, + LayoutFileManager.BootstrapDefaultTemplateName, + LayoutFileManager.SemanticUIDefaultTemplateName, + LayoutFileManager.FoundationDefaultTemplateName + }; + + private const string TemplateCaption1Column = "1 Column, Header, Footer"; + private const string TemplateCaption2Columns = "2 Equal Columns, Header, Footer"; + private const string TemplateCaption3Columns = "3 Equal Columns, Header, Footer"; + private const string TemplateCaption4Columns = "4 Equal Columns, Header, Footer"; + private const string TemplateCaptionLeftSidebar = "Left Sidebar, Header, Footer"; + private const string TemplateCaptionRightSidebar = "Right Sidebar, Header, Footer"; + + private const string TemplateImage1Column = "1ColumnHeaderFooter"; + private const string TemplateImage2Columns = "2EqualColumnsHeaderFooter"; + private const string TemplateImage3Columns = "3EqualColumnsHeaderFooter"; + private const string TemplateImage4Columns = "4EqualColumnsHeaderFooter"; + private const string TemplateImageLeftSidebar = "LeftSidebarHeaderFooter"; + private const string TemplateImageRightSidebar = "RightSidebarHeaderFooter"; + + private const string LayoutCaptionHeader = "Header"; + private const string LayoutCaptionFooter = "Footer"; + private const string LayoutCaptionContent = "Content"; + private const string LayoutCaptionContentSidebar = "Sidebar + Content"; + private const string LayoutCaption2Columns = "2 Equal Columns"; + private const string LayoutCaption3Columns = "3 Equal Columns"; + private const string LayoutCaption4Columns = "4 Equal Columns"; + + private const string LayoutDescriptionHeader = "Represents the header of the template."; + private const string LayoutDescriptionFooter = "Represents the footer of the template."; + private const string LayoutDescriptionContent = "Represents the content area of the template."; + private const string LayoutDescriptionContentSidebar = "Represents the sidebar and content areas of the template."; + private const string LayoutDescriptionContentColumns = "Represents the content areas of the template."; + + private const string GridTemplatePathContainer = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/container.html"; + private const string GridTemplatePath2Columns = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-6+6.html"; + private const string GridTemplatePath3Columns = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+4+4.html"; + private const string GridTemplatePath4Columns = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+3+3+3.html"; + private const string GridTemplatePathLeftSidebar = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+9.html"; + private const string GridTemplatePathRightSidebar = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-9+3.html"; + + #endregion + } +} diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/MonitoredDirectory.cs b/Telerik.Sitefinity.Frontend/FilesMonitoring/MonitoredDirectory.cs index 611619124..57415c2f1 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/MonitoredDirectory.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/MonitoredDirectory.cs @@ -6,7 +6,7 @@ namespace Telerik.Sitefinity.Frontend.FilesMonitoring /// /// This class represents DTO for working with monitored directories. /// - public class MonitoredDirectory : IEqualityComparer + internal class MonitoredDirectory : IEqualityComparer { /// /// Initializes a new instance of the class. @@ -36,7 +36,7 @@ public MonitoredDirectory(string path, bool isPackage) public bool IsPackage { get; set; } /// - /// Determines whether the specified , is equal to this instance. /// /// The to compare with this instance. /// diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/ResourceType.cs b/Telerik.Sitefinity.Frontend/FilesMonitoring/ResourceType.cs index 96b4836c8..54a74331f 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/ResourceType.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/ResourceType.cs @@ -4,7 +4,7 @@ /// This enumeration represents the types of resources. /// Each type should correspond to a folder where the resource can be found. /// - public enum ResourceType + internal enum ResourceType { Css, Fonts, diff --git a/Telerik.Sitefinity.Frontend/FrontendManager.cs b/Telerik.Sitefinity.Frontend/FrontendManager.cs index 51df51881..8c8e5a32a 100644 --- a/Telerik.Sitefinity.Frontend/FrontendManager.cs +++ b/Telerik.Sitefinity.Frontend/FrontendManager.cs @@ -1,4 +1,5 @@ using System.Web.Mvc; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing; using Telerik.Sitefinity.Frontend.Resources; using Telerik.Sitefinity.Frontend.Security; using Telerik.Sitefinity.Mvc; @@ -8,7 +9,7 @@ namespace Telerik.Sitefinity.Frontend /// /// This class manages instances of classes that are that are used to integrate the web application with the MVC framework. /// - public static class FrontendManager + internal static class FrontendManager { /// /// Gets an instance of the virtual path builder. @@ -38,7 +39,7 @@ public static ISitefinityControllerFactory ControllerFactory } /// - /// Gets or sets an instance of authentication evaluator + /// Gets or sets an instance of authentication evaluator. /// public static AuthenticationEvaluator AuthenticationEvaluator { @@ -53,7 +54,22 @@ public static AuthenticationEvaluator AuthenticationEvaluator } } + /// + /// Gets the attribute routing manager. + /// + /// + /// The attribute routing manager. + /// + internal static AttributeRoutingManager AttributeRouting + { + get + { + return FrontendManager.attributeRouting ?? (FrontendManager.attributeRouting = new AttributeRoutingManager()); + } + } + private static VirtualPathBuilder virtualPathBuilder; private static AuthenticationEvaluator authenticationEvaluator; + private static AttributeRoutingManager attributeRouting; } } diff --git a/Telerik.Sitefinity.Frontend/FrontendModule.cs b/Telerik.Sitefinity.Frontend/FrontendModule.cs new file mode 100644 index 000000000..4ba38c3ed --- /dev/null +++ b/Telerik.Sitefinity.Frontend/FrontendModule.cs @@ -0,0 +1,328 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using System.Web.Mvc; +using Ninject; +using Ninject.Modules; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.Data; +using Telerik.Sitefinity.Frontend; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; +using Telerik.Sitefinity.Services; + +[assembly: SitefinityModule(FrontendModule.ModuleName, + typeof(FrontendModule), + "Feather", + "Modern, intuitive, convention based, mobile-first UI for Progress Sitefinity CMS.", + StartupType.OnApplicationStart)] + +namespace Telerik.Sitefinity.Frontend +{ + /// + /// A module that will be invoked by Sitefinity. + /// + [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Field is disposed on Unload.")] + public class FrontendModule : ModuleBase + { + /// + /// Gets the current instance of the module. + /// + /// + /// The current. + /// + public static FrontendModule Current + { + get + { + return (FrontendModule)SystemManager.GetModule(FrontendModule.ModuleName); + } + } + + /// + /// Gets the landing page id for each module inherit from class. + /// + /// The landing page id. + public override Guid LandingPageId + { + get { return Guid.Empty; } + } + + /// + /// Gets the CLR types of all data managers provided by this module. + /// + /// An array of objects. + public override Type[] Managers + { + get { return ManagerTypes; } + } + + /// + /// Gets the dependency resolver. Can be used for overriding the default implementations of some interfaces. + /// + /// + /// The dependency resolver. + /// + public IKernel DependencyResolver + { + get + { + return ninjectDependencyResolver; + } + } + + /// + /// Installs the specified initializer. + /// + /// The initializer. + public override void Install(SiteInitializer initializer) + { + FrontendModuleInstaller.Install(initializer); + } + + /// + /// Initializes the module with specified settings. + /// + /// The settings. + public override void Initialize(ModuleSettings settings) + { + base.Initialize(settings); + + App.WorkWith() + .Module(settings.Name) + .Initialize() + .Configuration(); + + this.PreloadControllerTypeCacheAsync(); + } + + /// + /// Integrate the module into the system. + /// + public override void Load() + { + base.Load(); + + this.InitializeDependencyResolver(); + + FrontendModuleInstaller.Initialize(); + + Bootstrapper.Initialized -= this.Bootstrapper_Initialized; + Bootstrapper.Initialized += this.Bootstrapper_Initialized; + } + + /// + /// This method is invoked during the unload process of an active module from Sitefinity, e.g. when a module is deactivated. For instance this method is also invoked for every active module during a restart of the application. + /// Typically you will use this method to unsubscribe the module from all events to which it has subscription. + /// + public override void Unload() + { + this.Uninitialize(); + FrontendModuleUninstaller.Unload(this.initializers.Value); + base.Unload(); + } + + /// + /// Uninstall the module from Sitefinity system. Deletes the module artifacts added with Install method. + /// + /// The site initializer instance. + public override void Uninstall(SiteInitializer initializer) + { + this.Uninitialize(); + FrontendModuleUninstaller.Uninstall(this.initializers.Value); + base.Uninstall(initializer); + } + + /// + /// Upgrades this module from the specified version. + /// + /// The Site Initializer. A helper class for installing Sitefinity modules. + /// The version this module us upgrading from. + public override void Upgrade(SiteInitializer initializer, Version upgradeFrom) + { + base.Upgrade(initializer, upgradeFrom); + FrontendModuleUpgrader.Upgrade(upgradeFrom, initializer); + } + + /// + /// Gets the module configuration. + /// + protected override ConfigSection GetModuleConfig() + { + return Config.Get(); + } + + /// + /// Gets the meta data aggregation mode of the module persistence. + /// + protected override ManagersInitializationMode ManagersInitializationMode + { + get + { + return ManagersInitializationMode.OnStartup; + } + } + + /// + /// Creates Ninject kernel. + /// + /// + protected virtual IKernel CreateKernel() + { + var bootstrapper = new Ninject.Web.Common.Bootstrapper(); + IKernel kernel; + if (bootstrapper.Kernel != null) + kernel = bootstrapper.Kernel; + else + { + var ninjectSettings = new NinjectSettings(); + ninjectSettings.LoadExtensions = Config.Get().NinjectLoadExtensions; + kernel = new SitefinityKernel(ninjectSettings); + } + + return kernel; + } + + /// + /// Handles the Initialized event of the Bootstrapper. + /// + /// The source of the event. + /// The instance containing the event data. + protected virtual void Bootstrapper_Initialized(object sender, ExecutedEventArgs e) + { + if (e.CommandName == "Bootstrapped") + { + using (new HealthMonitoring.MethodPerformanceRegion("Feather")) + { + FrontendModuleInstaller.Bootstrapper_Initialized(this.initializers.Value); + } + } + } + + // Called both by Unload and Uninstall + private void Uninitialize() + { + this.UninitializeDependencyResolver(); + + Bootstrapper.Initialized -= this.Bootstrapper_Initialized; + } + + /// + /// Triggers the initialization of the controller type cache for the default controller factory asynchroniously. + /// + private void PreloadControllerTypeCacheAsync() + { + Task.Run(() => this.InitializeControllerTypeCache()); + } + + /// + /// Initializes the controller type cache of the default controller factory. + /// + private void InitializeControllerTypeCache() + { + DefaultControllerFactory defaultControllerFactory = + System.Web.Mvc.DependencyResolver.Current.GetService() as DefaultControllerFactory ?? + (ControllerBuilder.Current.GetControllerFactory() as DefaultControllerFactory ?? new DefaultControllerFactory()); + + MethodInfo getControllerTypesMethod = defaultControllerFactory.GetType().GetMethod("GetControllerTypes", BindingFlags.Instance | BindingFlags.NonPublic); + getControllerTypesMethod.Invoke(defaultControllerFactory, null); + } + + private void InitializeDependencyResolver() + { + if (ninjectDependencyResolver != null) + return; + + ninjectDependencyResolver = this.CreateKernel(); + var assemblies = new ControllerContainerInitializer().ControllerContainerAssemblies; + var loadedModules = ninjectDependencyResolver.GetModules(); + + foreach (var assembly in assemblies) + { + var assemblyModules = this.GetNinjectModules(assembly); + + // check assembly for already registered ninject modules + var registeredAssemblyModules = assemblyModules.Where(module => loadedModules.Where(loadedModule => loadedModule.Name.Equals(module.Name, StringComparison.OrdinalIgnoreCase)).Any()); + if (registeredAssemblyModules.Any()) + { + foreach (var module in assemblyModules) + { + if (!registeredAssemblyModules.Any(registeredModule => registeredModule.Name.Equals(module.Name, StringComparison.OrdinalIgnoreCase))) + { + ninjectDependencyResolver.Load(module); + } + } + } + else + { + ninjectDependencyResolver.Load(assembly); + } + } + } + + private void UninitializeDependencyResolver() + { + if (ninjectDependencyResolver != null && !ninjectDependencyResolver.IsDisposed && ninjectDependencyResolver is SitefinityKernel) + { + ninjectDependencyResolver.Dispose(); + ninjectDependencyResolver = null; + } + } + + private Lazy> initializers = new Lazy>(() => + { + try + { + return typeof(FrontendModule).Assembly.GetTypes().Where(t => typeof(IInitializer).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract).Select(t => Activator.CreateInstance(t) as IInitializer).ToList(); + } + catch (System.Reflection.ReflectionTypeLoadException ex) + { + string message = string.Join(" ", ex.LoaderExceptions.Select(e => e.Message)); + throw new InvalidOperationException(message, ex); + } + catch (Exception) + { + throw; + } + }); + + private IEnumerable GetNinjectModules(Assembly assembly) + { + return assembly.GetExportedTypes().Where(new Func(this.IsLoadableModule)).Select((Type type) => Activator.CreateInstance(type) as INinjectModule); + } + + private bool IsLoadableModule(Type type) + { + if (!typeof(INinjectModule).IsAssignableFrom(type) || type.IsAbstract || type.IsInterface) + { + return false; + } + + return type.GetConstructor(Type.EmptyTypes) != null; + } + + /// + /// The name. + /// + public const string ModuleName = "Feather"; + + private static IKernel ninjectDependencyResolver; + private static readonly Type[] ManagerTypes = new Type[] { typeof(FilesMonitoring.Data.FileMonitorDataManager) }; + + private class SitefinityKernel : StandardKernel + { + public SitefinityKernel() + : base() + { + } + + public SitefinityKernel(INinjectSettings settings) + : base(settings) + { + } + } + } +} diff --git a/Telerik.Sitefinity.Frontend/FrontendModuleFilter.cs b/Telerik.Sitefinity.Frontend/FrontendModuleFilter.cs new file mode 100644 index 000000000..093a9cf36 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/FrontendModuleFilter.cs @@ -0,0 +1,23 @@ +using System.Web.Mvc; +using Telerik.Sitefinity.Services; + +namespace Telerik.Sitefinity.Frontend +{ + /// + /// Action filter that terminates the request to a controller if the Frontend (Feather) Module is disabled or uninstalled. + /// + internal sealed class FrontendModuleFilter : ActionFilterAttribute, IActionFilter + { + /// + /// Called by the ASP.NET MVC framework before the action method executes. + /// + /// The filter context. + public override void OnActionExecuting(ActionExecutingContext filterContext) + { + if (SystemManager.GetModule("Feather") == null && filterContext != null && filterContext.Controller != null && filterContext.Controller.GetType().FullName.StartsWith("Telerik.Sitefinity.Frontend")) + { + filterContext.Result = new EmptyResult(); + } + } + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/FrontendModuleInstaller.cs b/Telerik.Sitefinity.Frontend/FrontendModuleInstaller.cs new file mode 100644 index 000000000..3fb0520a4 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/FrontendModuleInstaller.cs @@ -0,0 +1,141 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Ninject; +using Telerik.Microsoft.Practices.Unity; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.Frontend.Modules.Comments; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; +using Telerik.Sitefinity.Frontend.Services.FilesService; +using Telerik.Sitefinity.Frontend.Services.ListsService; +using Telerik.Sitefinity.Frontend.Services.ReviewsService; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Modules.Pages.Configuration; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Services.Comments.Notifications; + +namespace Telerik.Sitefinity.Frontend +{ + /// + /// Handles the logic for Feather install/initialize + /// + internal static class FrontendModuleInstaller + { + /// + /// Installs the specified initializer. + /// + /// The initializer. + public static void Install(SiteInitializer initializer) + { + if (FrontendModuleInstaller.FrontendServiceExists()) + FrontendModuleInstaller.InitialUpgrade(initializer); + } + + /// + /// Initializes the specified settings. + /// + public static void Initialize() + { + SystemManager.RegisterServiceStackPlugin(new ListsServiceStackPlugin()); + SystemManager.RegisterServiceStackPlugin(new FilesServiceStackPlugin()); + IModule module = SystemManager.GetApplicationModule("Comments"); + if (module != null && !(module is InactiveModule)) + { + SystemManager.RegisterServiceStackPlugin(new ReviewsServiceStackPlugin()); + } + } + + /// + /// Bootstrapper_s the initialized. + /// + /// The initializers. + public static void Bootstrapper_Initialized(IEnumerable initializers) + { + foreach (var initializer in initializers) + { + using (new HealthMonitoring.MethodPerformanceRegion("Initializing '{0}'.".Arrange(initializer.GetType().Name))) + { + initializer.Initialize(); + } + } + + ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); + } + + #region Install + + private static bool FrontendServiceExists() + { + var systemConfig = Config.Get(); + return systemConfig.SystemServices.ContainsKey(FrontendModuleInstaller.FrontendServiceName); + } + + private static void InitialUpgrade(SiteInitializer initializer) + { + FrontendModuleInstaller.RemoveFrontendService(); + FrontendModuleInstaller.RenameControllers(initializer); + FrontendModuleInstaller.ClearToolboxItems(); + } + + private static void RemoveFrontendService() + { + var configManager = ConfigManager.GetManager(); + var systemConfig = configManager.GetSection(); + systemConfig.SystemServices.Remove(FrontendModuleInstaller.FrontendServiceName); + configManager.SaveSection(systemConfig); + } + + private static void RenameControllers(SiteInitializer initializer) + { + var manager = initializer.PageManager; + var controllerNameProperties = manager.GetControls() + .Where(c => c.ObjectType == "Telerik.Sitefinity.Mvc.Proxy.MvcControllerProxy" || c.ObjectType == "Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.MvcWidgetProxy, Telerik.Sitefinity.Frontend") + .SelectMany(c => c.Properties.Where(p => p.Name == "ControllerName")); + + foreach (var property in controllerNameProperties) + { + if (property.Value == "News.Mvc.Controllers.NewsController") + property.Value = "Telerik.Sitefinity.Frontend.News.Mvc.Controllers.NewsController"; + else if (property.Value == "ContentBlock.Mvc.Controllers.ContentBlockController") + property.Value = "Telerik.Sitefinity.Frontend.ContentBlock.Mvc.Controllers.ContentBlockController"; + else if (property.Value == "Navigation.Mvc.Controllers.NavigationController") + property.Value = "Telerik.Sitefinity.Frontend.Navigation.Mvc.Controllers.NavigationController"; + else if (property.Value == "DynamicContent.Mvc.Controllers.DynamicContentController") + property.Value = "Telerik.Sitefinity.Frontend.DynamicContent.Mvc.Controllers.DynamicContentController"; + } + } + + private static void ClearToolboxItems() + { + var configManager = ConfigManager.GetManager(); + var toolboxesConfig = configManager.GetSection(); + + var pagesToolbox = toolboxesConfig.Toolboxes["PageControls"]; + if (pagesToolbox == null) + return; + + var mvcWidgetsSection = pagesToolbox.Sections.FirstOrDefault(s => s.Name == "MvcWidgets"); + if (mvcWidgetsSection != null) + { + FrontendModuleInstaller.RemoveToolboxItemIfExists(mvcWidgetsSection, "ContentBlock"); + FrontendModuleInstaller.RemoveToolboxItemIfExists(mvcWidgetsSection, "Navigation"); + FrontendModuleInstaller.RemoveToolboxItemIfExists(mvcWidgetsSection, "News"); + + configManager.SaveSection(toolboxesConfig); + } + } + + private static void RemoveToolboxItemIfExists(ToolboxSection mvcWidgetsSection, string toolName) + { + var tool = mvcWidgetsSection.Tools.FirstOrDefault(t => t.Name == toolName); + if (tool != null && tool.Source == ConfigSource.Database) + mvcWidgetsSection.Tools.Remove(tool); + } + + private const string FrontendServiceName = "Telerik.Sitefinity.Frontend"; + + #endregion + } +} diff --git a/Telerik.Sitefinity.Frontend/FrontendModuleUninstaller.cs b/Telerik.Sitefinity.Frontend/FrontendModuleUninstaller.cs new file mode 100644 index 000000000..033701f64 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/FrontendModuleUninstaller.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.Data; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Modules.Pages.Configuration; +using Telerik.Sitefinity.Services; + +namespace Telerik.Sitefinity.Frontend +{ + /// + /// Handles the logic for Feather unload/uninstall + /// + internal static class FrontendModuleUninstaller + { + /// + /// Unloads the specified initializers. + /// + /// The initializers. + public static void Unload(IEnumerable initializers) + { + FrontendModuleUninstaller.Uninitialize(initializers); + } + + /// + /// Uninstalls the specified initializers. + /// + /// The initializers. + public static void Uninstall(IEnumerable initializers) + { + FrontendModuleUninstaller.Uninitialize(initializers); + } + + // Called both by Unload and Uninstall + private static void Uninitialize(IEnumerable initializers) + { + foreach (var initializer in initializers) + initializer.Uninitialize(); + + // Force mvc initialization to run again after feather uninstalls + typeof(SystemManager).GetField("mvcEnabled", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, false); + } + } +} diff --git a/Telerik.Sitefinity.Frontend/FrontendModuleUpgrader.cs b/Telerik.Sitefinity.Frontend/FrontendModuleUpgrader.cs new file mode 100644 index 000000000..307418959 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/FrontendModuleUpgrader.cs @@ -0,0 +1,405 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.Data; +using Telerik.Sitefinity.Frontend.FilesMonitoring; +using Telerik.Sitefinity.Frontend.GridSystem; +using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Modules.Libraries; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Modules.Pages.Configuration; +using Telerik.Sitefinity.Pages.Model; + +namespace Telerik.Sitefinity.Frontend +{ + /// + /// Handles upgrades for Feather module + /// + internal static class FrontendModuleUpgrader + { + /// + /// Upgrades the specified upgrade from. + /// + /// The upgrade from. + /// The site initializer. + public static void Upgrade(Version upgradeFrom, SiteInitializer initializer) + { + if (upgradeFrom < new Version(1, 2, 140, 0)) + { + FrontendModuleUpgrader.DeleteOldGridSection(); + FrontendModuleUpgrader.UpdateContentBlockTitle(); + } + + if (upgradeFrom <= new Version(1, 2, 180, 1)) + { + FrontendModuleUpgrader.RemoveMvcWidgetToolboxItems(); + FrontendModuleUpgrader.RenameDynamicContentMvcToolboxItems(); + } + + if (upgradeFrom <= new Version(1, 2, 260, 1)) + { + FrontendModuleUpgrader.RecategorizePageTemplates(); + } + + if (upgradeFrom <= new Version(1, 2, 270, 1)) + { + FrontendModuleUpgrader.UpdatePageTemplates(); + } + + if (upgradeFrom <= new Version(1, 2, 280, 2)) + { + FrontendModuleUpgrader.CreateDefaultTemplates(); + } + + if (upgradeFrom <= new Version(1, 3, 320, 0)) + { + FrontendModuleUpgrader.UpdateGridWidgetsToolbox(); + FrontendModuleUpgrader.UpdateGridWidgetPaths(); + } + + if (upgradeFrom <= new Version(1, 7, 600, 0)) + { + FrontendModuleUpgrader.UpgradeLimitCountProperty(initializer); + } + + if (upgradeFrom < new Version(12, 0)) + { + FrontendModuleUpgrader.UpdateDefaultTemplateImages(); + } + + if (upgradeFrom < new Version(14, 1)) + { + FrontendModuleUpgrader.CreateBootstrap5Templates(); + } + } + + // 1, 2, 140, 0 + private static void DeleteOldGridSection() + { + var configManager = ConfigManager.GetManager(); + using (new ElevatedConfigModeRegion()) + { + var toolboxConfig = configManager.GetSection(); + var layoutsToolbox = toolboxConfig.Toolboxes["PageLayouts"]; + if (layoutsToolbox != null) + { + var htmlLayoutsSection = layoutsToolbox.Sections.FirstOrDefault(s => s.Name == "HtmlLayouts"); + if (htmlLayoutsSection != null && htmlLayoutsSection.Source == ConfigSource.Database) + { + layoutsToolbox.Sections.Remove(htmlLayoutsSection); + configManager.SaveSection(toolboxConfig); + } + } + } + } + + // 1, 2, 140, 0 + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Telerik.Sitefinity.Pages.Model.ControlData.set_Caption(System.String)")] + private static void UpdateContentBlockTitle() + { + var configManager = ConfigManager.GetManager(); + using (new ElevatedConfigModeRegion()) + { + var toolboxConfig = configManager.GetSection(); + var controlsToolbox = toolboxConfig.Toolboxes["PageControls"]; + if (controlsToolbox != null) + { + var mvcWidgetsSection = controlsToolbox.Sections.FirstOrDefault(s => s.Name == "MvcWidgets"); + if (mvcWidgetsSection != null) + { + var contentBlockTool = mvcWidgetsSection.Tools.FirstOrDefault(t => t.Name == "ContentBlock"); + if (contentBlockTool != null) + { + contentBlockTool.Title = "Content Block"; + configManager.SaveSection(toolboxConfig); + } + } + } + } + + var pageManager = PageManager.GetManager(); + using (new ElevatedModeRegion(pageManager)) + { + var contentBlocks = pageManager.GetControls().Where(c => c.ObjectType == "Telerik.Sitefinity.Mvc.Proxy.MvcControllerProxy" && c.Caption == "ContentBlock").ToArray(); + foreach (var contentBlock in contentBlocks) + { + contentBlock.Caption = "Content Block"; + } + + pageManager.SaveChanges(); + } + } + + // 1, 2, 180, 1 + private static void RemoveMvcWidgetToolboxItems() + { + var configManager = ConfigManager.GetManager(); + using (new ElevatedConfigModeRegion()) + { + var toolboxConfig = configManager.GetSection(); + var pageControls = toolboxConfig.Toolboxes["PageControls"]; + + foreach (var section in pageControls.Sections) + { + var widgets = section.Tools.Where(t => t.ControllerType.StartsWith("Telerik.Sitefinity.Frontend.", StringComparison.Ordinal) && !t.ControllerType.StartsWith("Telerik.Sitefinity.Frontend.DynamicContent", StringComparison.Ordinal)).ToArray(); + foreach (ToolboxItem tool in widgets) + { + if (tool.Source == ConfigSource.Database) + section.Tools.Remove(tool); + } + } + + var mvcWidgetsSection = pageControls.Sections.FirstOrDefault(s => s.Name == "MvcWidgets"); + if (mvcWidgetsSection != null && mvcWidgetsSection.Source == ConfigSource.Database) + { + pageControls.Sections.Remove(mvcWidgetsSection); + } + + configManager.SaveSection(toolboxConfig); + } + } + + // 1, 2, 180, 1 + private static void RenameDynamicContentMvcToolboxItems() + { + var configManager = ConfigManager.GetManager(); + using (new ElevatedConfigModeRegion()) + { + var toolboxConfig = configManager.GetSection(); + var pageControls = toolboxConfig.Toolboxes["PageControls"]; + + foreach (var section in pageControls.Sections) + { + var widgets = section.Tools.Where(t => t.ControllerType.StartsWith("Telerik.Sitefinity.Frontend.DynamicContent", StringComparison.Ordinal)).ToArray(); + foreach (ToolboxItem tool in widgets) + { + tool.CssClass = "sfNewsViewIcn sfMvcIcn"; + var indexOfMvcSuffix = tool.Title.LastIndexOf(" MVC", StringComparison.Ordinal); + tool.Title = tool.Title.Substring(0, indexOfMvcSuffix); + } + } + + configManager.SaveSection(toolboxConfig); + } + } + + // 1, 2, 260, 1 + private static void RecategorizePageTemplates() + { + var pageManager = PageManager.GetManager(); + var layoutManager = new LayoutFileManager(); + + var customPageTemplates = pageManager.GetTemplates().Where(pt => pt.Category == SiteInitializer.CustomTemplatesCategoryId).ToArray(); + foreach (var customPageTemplate in customPageTemplates) + { + var titleTokens = customPageTemplate.Title.ToString().Split('.'); + if (titleTokens.Length > 1 && (new PackageManager()).PackageExists(titleTokens[0])) + { + customPageTemplate.Category = layoutManager.GetOrCreateTemplateCategoryId(titleTokens[0]); + } + } + + pageManager.SaveChanges(); + } + + // 1, 2, 270, 1 + private static void UpdatePageTemplates() + { + var pageManager = PageManager.GetManager(); + var layoutFileManager = new LayoutFileManager(); + + var defaultPageTemplates = pageManager.GetTemplates().Where(pt => LayoutFileManager.DefaultTemplateNames.Contains(pt.Name)).ToArray(); + foreach (var defaultPageTemplate in defaultPageTemplates) + { + // Renaming template title + var titleParts = defaultPageTemplate.Title.ToString().Split('.'); + if (titleParts.Length > 1) + { + defaultPageTemplate.Title = titleParts[1]; + } + + // Adding icon to title + layoutFileManager.AttachImageToTemplate(defaultPageTemplate, pageManager, "default"); + } + + pageManager.SaveChanges(); + } + + // 1, 2, 280, 2 + private static void CreateDefaultTemplates() + { + var layoutManager = new LayoutFileManager(); + + var pageManager = PageManager.GetManager(); + var defaultPageTemplates = pageManager.GetTemplates().Where(pt => LayoutFileManager.DefaultTemplateNames.Contains(pt.Name)); + foreach (var template in defaultPageTemplates) + { + if (string.Equals(LayoutFileManager.BootstrapDefaultTemplateName, template.Name, StringComparison.OrdinalIgnoreCase)) + layoutManager.CreateDefaultTemplates("Bootstrap", "default"); + else if (string.Equals(LayoutFileManager.FoundationDefaultTemplateName, template.Name, StringComparison.OrdinalIgnoreCase)) + layoutManager.CreateDefaultTemplates("Foundation", "default"); + else if (string.Equals(LayoutFileManager.SemanticUIDefaultTemplateName, template.Name, StringComparison.OrdinalIgnoreCase)) + layoutManager.CreateDefaultTemplates("SemanticUI", "default"); + } + } + + private static void UpdateDefaultTemplateImages() + { + var librariesManager = LibrariesManager.GetManager("SystemLibrariesProvider"); + if (librariesManager != null) + { + var suppressSecurityChecks = librariesManager.Provider.SuppressSecurityChecks; + try + { + librariesManager.Provider.SuppressSecurityChecks = true; + LayoutFileManager.UpdateDefaultTemplateImages(librariesManager); + } + finally + { + librariesManager.Provider.SuppressSecurityChecks = suppressSecurityChecks; + } + } + } + + // 1, 3, 320, 0 + private static void UpdateGridWidgetsToolbox() + { + FrontendModuleUpgrader.TransferGridWidgetSectionToDefault("BootstrapGrids"); + FrontendModuleUpgrader.TransferGridWidgetSectionToDefault("FoundationGrids"); + FrontendModuleUpgrader.TransferGridWidgetSectionToDefault("SemanticUIGrids"); + } + + private static void TransferGridWidgetSectionToDefault(string sectionName) + { + var layoutConfig = Config.Get().Toolboxes["PageLayouts"]; + var section = layoutConfig.Sections.FirstOrDefault(e => e.Name == sectionName); + if (section != null) + { + var registrator = new GridWidgetRegistrator(); + foreach (var tool in section.Tools) + { + if (tool.LayoutTemplate.IsNullOrEmpty()) + continue; + + registrator.RegisterToolboxItem(System.Web.VirtualPathUtility.GetFileName(tool.LayoutTemplate)); + } + + var configurationManager = ConfigManager.GetManager(); + using (new ElevatedConfigModeRegion()) + { + var toolboxesConfig = configurationManager.GetSection(); + var pageControls = toolboxesConfig.Toolboxes["PageLayouts"]; + + var sectionToDelete = pageControls.Sections.FirstOrDefault(e => e.Name == sectionName); + if (sectionToDelete != null && sectionToDelete.Source == ConfigSource.Database) + pageControls.Sections.Remove(sectionToDelete); + + configurationManager.SaveSection(toolboxesConfig); + } + } + } + + // 1, 3, 320, 0 + private static void UpdateGridWidgetPaths() + { + const int BATCH = 200; + + var pathPairs = new Dictionary() + { + { "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-11+5.html", "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-8+4.html" }, + { "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-12+4.html", "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-9+3.html" }, + { "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-5+11.html", "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+8.html" }, + { "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+12.html", "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+9.html" }, + { "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-five-cols.html", "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-2+3+2+3+2.html" }, + { "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-four-cols.html", "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+3+3+3.html" }, + { "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-one-col.html", "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-12.html" }, + { "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-three-cols.html", "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+4+4.html" }, + { "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-two-cols.html", "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-6+6.html" } + }; + + var pageManager = PageManager.GetManager(); + var oldPaths = pathPairs.Keys.ToArray(); + + var layoutControlIds = pageManager.GetControls().Where(c => c.IsLayoutControl).Select(c => c.Id).ToArray(); + var currentControl = 0; + while (currentControl < layoutControlIds.Length) + { + var batchArray = layoutControlIds.Skip(currentControl).Take(BATCH).ToArray(); + + var propertiesToUpdate = pageManager.GetProperties() + .Where(p => batchArray.Contains(p.Control.Id)) + .Where(p => oldPaths.Contains(p.Value)) + .ToArray(); + + foreach (var property in propertiesToUpdate) + property.Value = pathPairs[property.Value]; + + if (propertiesToUpdate.Length > 0) + pageManager.SaveChanges(); + + currentControl += BATCH; + } + } + + // 1, 7, 600, 0 + private static void UpgradeLimitCountProperty(SiteInitializer initializer) + { + var pageMan = initializer.PageManager; + string[] controllersList = + { + "Telerik.Sitefinity.Frontend.Blogs.Mvc.Controllers.BlogController", + "Telerik.Sitefinity.Frontend.Blogs.Mvc.Controllers.BlogPostController", + "Telerik.Sitefinity.Frontend.News.Mvc.Controllers.NewsController", + "Telerik.Sitefinity.Frontend.Events.Mvc.Controllers.EventController", + "Telerik.Sitefinity.Frontend.Media.Mvc.Controllers.ImageGalleryController", + "Telerik.Sitefinity.Frontend.Media.Mvc.Controllers.VideoGalleryController", + "Telerik.Sitefinity.Frontend.Media.Mvc.Controllers.DocumentsListController", + "Telerik.Sitefinity.Frontend.DynamicContent.Mvc.Controllers.DynamicContentController", + "Telerik.Sitefinity.Frontend.Identity.Mvc.Controllers.UsersListController", + "Telerik.Sitefinity.Frontend.Search.Mvc.Controllers.SearchResultsController" + }; + + foreach (var controller in controllersList) + { + var controlIds = pageMan.GetProperties() + .Where(x => x.Name == "ControllerName" && x.Value == controller) + .Select(x => x.Control.Id).ToList(); + + foreach (var controlId in controlIds) + { + var settingids = pageMan.GetProperties().Where(x => x.Name == "Settings" && x.Control.Id == controlId).Select(x => x.Id).ToList(); + foreach (var settingId in settingids) + { + var models = pageMan.GetProperties().Where(x => x.Name == "Model" && x.ParentProperty.Id == settingId).ToList(); + foreach (var model in models) + { + var itemsPerPage = pageMan.GetProperties().Where(x => x.Name == "ItemsPerPage" && x.ParentProperty.Id == model.Id).FirstOrDefault(); + if (itemsPerPage != null) + { + var limitCount = pageMan.GetProperties().Where(x => x.Name == "LimitCount" && x.ParentProperty.Id == model.Id).FirstOrDefault(); + if (limitCount == null) + { + limitCount = pageMan.CreateProperty(); + pageMan.CopyProperty(itemsPerPage, limitCount); + limitCount.Name = "LimitCount"; + limitCount.Language = itemsPerPage.Language; + limitCount.ParentProperty = model; + } + } + } + } + } + } + } + + // 14.1 + private static void CreateBootstrap5Templates() + { + var layoutManager = new LayoutFileManager(); + + layoutManager.CreateDefaultTemplates("Bootstrap5", "default"); + } + } +} diff --git a/Telerik.Sitefinity.Frontend/FrontendService.cs b/Telerik.Sitefinity.Frontend/FrontendService.cs index 1b87a65c5..884156233 100644 --- a/Telerik.Sitefinity.Frontend/FrontendService.cs +++ b/Telerik.Sitefinity.Frontend/FrontendService.cs @@ -1,12 +1,4 @@ using System; -using Telerik.Sitefinity.Abstractions; -using Telerik.Sitefinity.Data; -using Telerik.Sitefinity.Frontend.Designers; -using Telerik.Sitefinity.Frontend.FilesMonitoring; -using Telerik.Sitefinity.Frontend.GridSystem; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts; -using Telerik.Sitefinity.Frontend.Resources; using Telerik.Sitefinity.Services; namespace Telerik.Sitefinity.Frontend @@ -14,6 +6,7 @@ namespace Telerik.Sitefinity.Frontend /// /// A service that will be invoked by Sitefinity. /// + [Obsolete("Initialization logic is moved to FrontendModule. This class will be deleted.")] public class FrontendService : ServiceBase { /// @@ -27,46 +20,5 @@ public override Type[] Interfaces return null; } } - - /// - /// Initializes the service with specified settings. - /// - /// The settings. - public override void Initialize(ModuleSettings settings) - { - base.Initialize(settings); - - Bootstrapper.Initialized -= this.Bootstrapper_Initialized; - Bootstrapper.Initialized += this.Bootstrapper_Initialized; - } - - /// - /// Handles the Initialized event of the Bootstrapper. - /// - /// The source of the event. - /// The instance containing the event data. - protected virtual void Bootstrapper_Initialized(object sender, ExecutedEventArgs e) - { - if (e.CommandName == "Bootstrapped") - { - var resourcesInitializer = new ResourcesInitializer(); - resourcesInitializer.Initialize(); - - var fileMonitoringInitilizer = new FileMonitoringInitializer(); - fileMonitoringInitilizer.Initialize(); - - var controllerContainerInitializer = new ControllerContainerInitializer(); - controllerContainerInitializer.Initialize(); - - var layoutsInitializer = new LayoutInitializer(); - layoutsInitializer.Initialize(); - - var gridSystemInitializer = new GridSystemInitializer(); - gridSystemInitializer.Initialize(); - - var designerInitializer = new DesignerInitializer(); - designerInitializer.Initialize(); - } - } } } diff --git a/Telerik.Sitefinity.Frontend/GlobalSuppressions.cs b/Telerik.Sitefinity.Frontend/GlobalSuppressions.cs index 42ce14b7f..eec0e2562 100644 Binary files a/Telerik.Sitefinity.Frontend/GlobalSuppressions.cs and b/Telerik.Sitefinity.Frontend/GlobalSuppressions.cs differ diff --git a/Telerik.Sitefinity.Frontend/GridSystem/GridControl.cs b/Telerik.Sitefinity.Frontend/GridSystem/GridControl.cs index dd4872547..03cb18e0b 100644 --- a/Telerik.Sitefinity.Frontend/GridSystem/GridControl.cs +++ b/Telerik.Sitefinity.Frontend/GridSystem/GridControl.cs @@ -1,16 +1,21 @@ -using System; -using System.IO; -using System.Linq; -using System.Text; -using System.Web.Hosting; -using System.Web.UI; -using Telerik.Sitefinity.Configuration; -using Telerik.Sitefinity.Localization; -using Telerik.Sitefinity.Modules.Newsletters; -using Telerik.Sitefinity.Utilities.HtmlParsing; -using Telerik.Sitefinity.Utilities.TypeConverters; -using Telerik.Sitefinity.Web; -using Telerik.Sitefinity.Web.Configuration; +using System; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Web.Hosting; +using System.Web.UI; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure; +using Telerik.Sitefinity.Frontend.Mvc.StringResources; +using Telerik.Sitefinity.Localization; +using Telerik.Sitefinity.Modules.Newsletters; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Utilities.HtmlParsing; +using Telerik.Sitefinity.Utilities.TypeConverters; +using Telerik.Sitefinity.Web; +using Telerik.Sitefinity.Web.Configuration; using Telerik.Sitefinity.Web.UI; namespace Telerik.Sitefinity.Frontend.GridSystem @@ -18,6 +23,7 @@ namespace Telerik.Sitefinity.Frontend.GridSystem /// /// The LayoutControl comprises the basic building block of Sitefinity layouts. GridControl adds the ability to use pure HTML templates. /// + [RequiresEmbeddedWebResource("Telerik.Sitefinity.Resources.Themes.LayoutsBasics.css", "Telerik.Sitefinity.Resources.Reference")] public class GridControl : LayoutControl { /// @@ -25,6 +31,12 @@ public class GridControl : LayoutControl /// protected override ITemplate GetTemplate() { + if (SystemManager.GetModule("Feather") == null) + { + var markup = this.ProcessLayoutString(Res.Get().GridDoesNotWork, ensureSfColsWrapper: true); + return ControlUtilities.GetTemplate(null, markup.GetHashCode().ToString(CultureInfo.InvariantCulture), null, markup); + } + var layout = this.Layout; bool isVirtualPath = layout.StartsWith("~/", StringComparison.Ordinal); bool isHtmlTemplate = layout.EndsWith(".html", StringComparison.OrdinalIgnoreCase) || layout.EndsWith(".htm", StringComparison.Ordinal); @@ -45,7 +57,6 @@ protected virtual string ProcessLayoutString(string targetTemplate, bool ensureS parser.AutoExtractBetweenTagsOnly = false; parser.CompressWhiteSpaceBeforeTag = false; parser.KeepRawHTML = true; - bool hasSfCols = false; var output = new StringBuilder(); HtmlChunk chunk; while ((chunk = parser.ParseNext()) != null) @@ -57,9 +68,7 @@ protected virtual string ProcessLayoutString(string targetTemplate, bool ensureS if (cssClass != null) { var classes = cssClass.Split(new char[] { ' ' }); - var chunkHasSfCols = classes.Contains("sf_cols", StringComparer.Ordinal); - hasSfCols = hasSfCols || chunkHasSfCols; - if (chunkHasSfCols || + if (classes.Contains("sf_cols", StringComparer.Ordinal) || classes.Contains("sf_colsIn", StringComparer.Ordinal) || classes.Contains("sf_colsOut", StringComparer.Ordinal)) { @@ -72,7 +81,7 @@ protected virtual string ProcessLayoutString(string targetTemplate, bool ensureS output.Append(modified ? chunk.GenerateHtml() : chunk.Html); } - if (!hasSfCols && ensureSfColsWrapper) + if (ensureSfColsWrapper) { return "
" + output.ToString() + "
"; } @@ -93,8 +102,8 @@ protected virtual ITemplate GetTemplate(bool isVirtualPath, bool isHtmlTemplate, if (isVirtualPath && isHtmlTemplate) { if (!HostingEnvironment.VirtualPathProvider.FileExists(layout)) - { - throw new ArgumentException(Res.Get("CannotFindTemplate", layout)); + { + throw new ArgumentException(Res.Get("CannotFindTemplateMvcForm", layout)); } using (var reader = new StreamReader(HostingEnvironment.VirtualPathProvider.GetFile(layout).Open())) @@ -119,10 +128,10 @@ protected virtual ITemplate GetTemplate(bool isVirtualPath, bool isHtmlTemplate, } // Add sf_cols wrapper for back end pages and email campaigns. - var currentNode = SiteMapBase.GetActualCurrentNode(); - var rootNode = currentNode != null ? currentNode.RootNode as PageSiteNode : null; - var ensureSfColsWrapper = this.IsBackend() || rootNode == null || rootNode.Id == NewslettersModule.standardCampaignRootNodeId || - System.Web.HttpContext.Current.Items[SiteMapBase.CurrentNodeKey] == null; + var ensureSfColsWrapper = (this.IsBackend() && !SystemManager.IsPreviewMode) + || SiteMapBase.GetActualCurrentNode()?.RootNodeId == NewslettersModule.standardCampaignRootNodeId + || System.Web.HttpContext.Current.Items[SiteMapBase.CurrentNodeKey] == null; + layout = this.ProcessLayoutString(layout, ensureSfColsWrapper); return ControlUtilities.GetTemplate(null, layout.GetHashCode().ToString(System.Globalization.CultureInfo.InvariantCulture), null, layout); diff --git a/Telerik.Sitefinity.Frontend/GridSystem/GridControlTemplates.rar b/Telerik.Sitefinity.Frontend/GridSystem/GridControlTemplates.rar deleted file mode 100644 index bdd03e5ac..000000000 Binary files a/Telerik.Sitefinity.Frontend/GridSystem/GridControlTemplates.rar and /dev/null differ diff --git a/Telerik.Sitefinity.Frontend/GridSystem/GridControlToolboxFilter.cs b/Telerik.Sitefinity.Frontend/GridSystem/GridControlToolboxFilter.cs new file mode 100644 index 000000000..ce019848b --- /dev/null +++ b/Telerik.Sitefinity.Frontend/GridSystem/GridControlToolboxFilter.cs @@ -0,0 +1,115 @@ +using System; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.DesignerToolbox; +using Telerik.Sitefinity.Frontend.Mvc.Helpers; +using Telerik.Sitefinity.Modules.Newsletters; +using Telerik.Sitefinity.Modules.Newsletters.Configuration; +using Telerik.Sitefinity.Modules.Newsletters.Web; +using Telerik.Sitefinity.Newsletters.Model; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Utilities.TypeConverters; +using Telerik.Sitefinity.Web.UI; + +namespace Telerik.Sitefinity.Frontend.GridSystem +{ + /// + /// Determines which layout controls should be visible in the toolbox of the . + /// + internal class GridControlToolboxFilter : IToolboxFilter + { + /// + /// Initializes a new instance of the class. + /// + /// Function that returns the Framework for the current context. + public GridControlToolboxFilter(Func frameworkExtractor) + { + this.frameworkExtractor = frameworkExtractor; + } + + /// + /// Determines whether a toolbox section should be visible in the . + /// + /// The section in question. + /// The filter context passed externally. + /// true if it should be visible. + public bool IsSectionVisible(IToolboxSection section, IToolboxFilterContext context) + { + if (section != null && context != null && section.Name == GridWidgetRegistrator.GridSectionName && section.Title == GridWidgetRegistrator.GridSectionTitle) + return SystemManager.GetModule("Feather") != null && context.ContainerId == "LayoutToolboxContainer"; + + return true; + } + + /// + /// Determines whether a tool (a.k.a toolbox item) should be visible in the . + /// + /// The tool in question. + /// true if it should be visible. + public bool IsToolVisible(IToolboxItem tool) + { + if (tool == null) + return true; + + var currentFramework = this.frameworkExtractor(); + + // Pages: Everything works for Hybrid mode. No need to reflect on the specific item. + // Newsletters: Always run in Hybrid mode. Message body type needs check. + if (currentFramework == PageTemplateFramework.Hybrid) + { + var currentHttpContext = SystemManager.CurrentHttpContext; + + if (NewslettersHelper.IsMvcNewsletter()) + { + currentFramework = PageTemplateFramework.Mvc; + } + else + { + return true; + } + } + + if (!tool.ControlType.IsNullOrEmpty()) + { + var controlType = TypeResolutionService.ResolveType(tool.ControlType, throwOnError: false); + if (controlType == null) + return true; + + var isLayoutControl = typeof(LayoutControl).IsAssignableFrom(controlType); + var isGridControl = typeof(GridControl).IsAssignableFrom(controlType); + + if (currentFramework == PageTemplateFramework.WebForms && isGridControl) + return false; + + if (currentFramework == PageTemplateFramework.Mvc && isLayoutControl && !isGridControl) + return false; + } + + return true; + } + + private bool IsNewslettersModuleEnabled + { + get + { + if (this.isNewslettersModuleEnabled == null) + { + try + { + Config.Get(); + this.isNewslettersModuleEnabled = true; + } + catch (Exception) + { + this.isNewslettersModuleEnabled = false; + } + } + + return this.isNewslettersModuleEnabled.Value; + } + } + + private bool? isNewslettersModuleEnabled; + private readonly Func frameworkExtractor; + } +} diff --git a/Telerik.Sitefinity.Frontend/GridSystem/GridSystemInitializer.cs b/Telerik.Sitefinity.Frontend/GridSystem/GridSystemInitializer.cs deleted file mode 100644 index ca3f2aad9..000000000 --- a/Telerik.Sitefinity.Frontend/GridSystem/GridSystemInitializer.cs +++ /dev/null @@ -1,118 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using Telerik.Sitefinity.Configuration; -using Telerik.Sitefinity.Modules.Pages.Configuration; - -namespace Telerik.Sitefinity.Frontend.GridSystem -{ - /// - /// This class contains logic for registering and initializing the grid controls. - /// - public class GridSystemInitializer - { - /// - /// Registers the grid controls. - /// - public virtual void Initialize() - { - var configManager = ConfigManager.GetManager(); - using (new ElevatedConfigModeRegion()) - { - var toolboxConfig = configManager.GetSection(); - var htmlLayoutsSection = this.GetOrCreateToolBoxSection(toolboxConfig); - - var baseTemplatePath = string.Format( - System.Globalization.CultureInfo.InvariantCulture, - GridSystemInitializer.GridFolderPathStringTemplate, - FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(FrontendService).Assembly)); - - var layoutControls = this.CreateLayoutControlsData(baseTemplatePath); - - foreach (var layoutControl in layoutControls) - { - this.AddLayoutControl(htmlLayoutsSection.Tools, layoutControl); - } - - configManager.SaveSection(toolboxConfig); - } - } - - /// - /// Gets existing or create a tool box section for the grid controls. - /// - /// The toolbox configuration. - /// - protected virtual ToolboxSection GetOrCreateToolBoxSection(ToolboxesConfig toolboxConfig) - { - var layoutsToolbox = toolboxConfig.Toolboxes["PageLayouts"]; - - var htmlLayoutsSection = layoutsToolbox.Sections.FirstOrDefault(s => s.Name == "HtmlLayouts"); - if (htmlLayoutsSection == null) - { - htmlLayoutsSection = new ToolboxSection(layoutsToolbox.Sections); - htmlLayoutsSection.Name = "HtmlLayouts"; - - /// TODO: Set resource class id and use resource keys for Title and Description. - htmlLayoutsSection.Title = "Bootstrap grid widgets"; - - layoutsToolbox.Sections.Add(htmlLayoutsSection); - } - - return htmlLayoutsSection; - } - - /// - /// Creates the layout controls data. - /// - /// The base template path. - /// - protected virtual List CreateLayoutControlsData(string baseTemplatePath) - { - var layoutControls = new List() - { - new GridControlData() { Name = "Col1", Title = "12", LayoutTemplatePath = baseTemplatePath + "grid-12.html", CssClass = "sfL100" }, - new GridControlData() { Name = "Col2T1", Title = "3 + 9", LayoutTemplatePath = baseTemplatePath + "grid-3+9.html", CssClass = "sfL25_75" }, - new GridControlData() { Name = "Col2T2", Title = "4 + 8", LayoutTemplatePath = baseTemplatePath + "grid-4+8.html", CssClass = "sfL33_67" }, - new GridControlData() { Name = "Col2T3", Title = "6 + 6", LayoutTemplatePath = baseTemplatePath + "grid-6+6.html", CssClass = "sfL50_50" }, - new GridControlData() { Name = "Col2T4", Title = "8 + 4", LayoutTemplatePath = baseTemplatePath + "grid-8+4.html", CssClass = "sfL67_33" }, - new GridControlData() { Name = "Col2T5", Title = "9 + 3", LayoutTemplatePath = baseTemplatePath + "grid-9+3.html", CssClass = "sfL75_25" }, - new GridControlData() { Name = "Col3T1", Title = "4 + 4 + 4", LayoutTemplatePath = baseTemplatePath + "grid-4+4+4.html", CssClass = "sfL33_34_33" }, - new GridControlData() { Name = "Col3T2", Title = "3 + 6 + 3", LayoutTemplatePath = baseTemplatePath + "grid-3+6+3.html", CssClass = "sfL25_50_25" }, - new GridControlData() { Name = "Col4T1", Title = "3 + 3 + 3 + 3", LayoutTemplatePath = baseTemplatePath + "grid-3+3+3+3.html", CssClass = "sfL25_25_25_25" }, - new GridControlData() { Name = "Col5T1", Title = "2 + 3 + 2 + 3 + 2", LayoutTemplatePath = baseTemplatePath + "grid-2+3+2+3+2.html", CssClass = "sfL20_20_20_20_20" } - }; - - return layoutControls; - } - - /// - /// Adds the layout control. - /// - /// The parent. - /// The data. - protected virtual void AddLayoutControl(ConfigElementList parent, GridControlData data) - { - if (data == null) - throw new ArgumentNullException("data"); - - var control = parent.FirstOrDefault(t => t.Name == data.Name); - - if (control == null) - { - control = new ToolboxItem(parent); - control.ControlType = typeof(GridControl).AssemblyQualifiedName; - control.Name = data.Name; - control.Title = data.Title; - control.LayoutTemplate = data.LayoutTemplatePath; - control.CssClass = data.CssClass; - parent.Add(control); - } - } - - /// - /// The grid folder path string template - /// - public const string GridFolderPathStringTemplate = "~/{0}GridSystem/Templates/"; - } -} diff --git a/Telerik.Sitefinity.Frontend/GridSystem/GridWidgetRegistrator.cs b/Telerik.Sitefinity.Frontend/GridSystem/GridWidgetRegistrator.cs new file mode 100644 index 000000000..c39967fff --- /dev/null +++ b/Telerik.Sitefinity.Frontend/GridSystem/GridWidgetRegistrator.cs @@ -0,0 +1,275 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Modules.Pages.Configuration; +using Telerik.Sitefinity.Pages.Model; + +namespace Telerik.Sitefinity.Frontend.GridSystem +{ + /// + /// This class register the grid template files in the PageLayout section of the toolbox. + /// + internal class GridWidgetRegistrator + { + #region Public methods + + /// + /// Registers the grid widget in toolbox. + /// + /// Name of the file. + /// Old name of the file. + public void RegisterToolboxItem(string fileName, string oldFileName = "") + { + ConfigManager configManager = null; + var toolboxConfig = Config.Get(); + var layoutsToolbox = toolboxConfig.Toolboxes[ToolboxesConfig.LayoutsToolboxName]; + var htmlLayoutsSection = layoutsToolbox.Sections.FirstOrDefault(s => s.Name == GridWidgetRegistrator.GridSectionName); + if (htmlLayoutsSection == null) + { + configManager = ConfigManager.GetManager(); + toolboxConfig = configManager.GetSection(); + layoutsToolbox = toolboxConfig.Toolboxes[ToolboxesConfig.LayoutsToolboxName]; + htmlLayoutsSection = this.CreateToolBoxSection(layoutsToolbox, GridWidgetRegistrator.GridSectionName, GridWidgetRegistrator.GridSectionTitle); + } + + var layoutControl = this.CreateGridControlsData(fileName); + + string toolboxItemName; + if (oldFileName.IsNullOrEmpty()) + { + toolboxItemName = layoutControl.Name; + } + else + { + var oldFileNameWithoutExtension = this.GetFileNameWithoutExtension(oldFileName); + toolboxItemName = oldFileNameWithoutExtension; + } + + ToolboxItem toolboxItem = null; + if (configManager == null) + toolboxItem = htmlLayoutsSection.Tools.FirstOrDefault(t => t.Name == toolboxItemName); + + if (toolboxItem == null || (toolboxItem.Name != layoutControl.Name || toolboxItem.Title != layoutControl.Title || toolboxItem.LayoutTemplate != layoutControl.LayoutTemplatePath)) + { + if (configManager == null) + { + configManager = ConfigManager.GetManager(); + toolboxConfig = configManager.GetSection(); + layoutsToolbox = toolboxConfig.Toolboxes[ToolboxesConfig.LayoutsToolboxName]; + htmlLayoutsSection = layoutsToolbox.Sections.FirstOrDefault(s => s.Name == GridWidgetRegistrator.GridSectionName); + } + + this.AddOrRenameGridControl(htmlLayoutsSection, layoutControl, toolboxItemName); + } + + if (configManager != null) + { + using (new ElevatedConfigModeRegion()) + configManager.SaveSection(toolboxConfig); + } + } + + /// + /// Unregisters the toolbox item. + /// + /// Name of the content type. + public virtual void UnregisterToolboxItem(string fileName) + { + var configurationManager = ConfigManager.GetManager(); + var toolboxesConfig = configurationManager.GetSection(); + var pageControls = toolboxesConfig.Toolboxes["PageLayouts"]; + var sectionName = GridWidgetRegistrator.GridSectionName; + + var section = pageControls.Sections.Where(e => e.Name == sectionName).FirstOrDefault(); + if (section != null) + { + var fileNameWithoutExtension = this.GetFileNameWithoutExtension(fileName); + var itemToDelete = section.Tools.FirstOrDefault(e => e.Name == fileNameWithoutExtension); + + if (itemToDelete != null && itemToDelete.Source == ConfigSource.Database) + { + section.Tools.Remove(itemToDelete); + } + + if (!section.Tools.Any() && section.Source == ConfigSource.Database) + { + pageControls.Sections.Remove(section); + } + } + + configurationManager.SaveSection(toolboxesConfig); + } + + /// + /// Updates the control data. + /// + /// New name of the file. + /// Old name of the file. + public void UpdateControlData(string newFileName, string oldFileName) + { + var pageManger = PageManager.GetManager(); + + var baseTemplatePath = string.Format( + CultureInfo.InvariantCulture, + GridWidgetRegistrator.GridFolderPathStringTemplate, + FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(FrontendModule).Assembly)); + + var properties = pageManger.GetProperties().Where(prop => prop.Name == "Layout" && prop.Value == baseTemplatePath + oldFileName).ToList(); + var newCaption = this.GetFileNameWithoutExtension(newFileName); + foreach (var property in properties) + { + property.Value = baseTemplatePath + newFileName; + ((ControlData)property.Control).Caption = newCaption; + } + + pageManger.SaveChanges(); + } + + #endregion + + #region Protected methods + + /// + /// Gets existing or create a tool box section for the grid controls. + /// + /// The toolbox configuration. + /// Name of the section. + /// The section title. + /// The section. + protected virtual ToolboxSection CreateToolBoxSection(Toolbox toolbox, string sectionName, string sectionTitle) + { + var htmlLayoutsSection = new ToolboxSection(toolbox.Sections); + htmlLayoutsSection.Name = sectionName; + + /// TODO: Set resource class id and use resource keys for Title and Description. + htmlLayoutsSection.Title = sectionTitle; + + toolbox.Sections.Add(htmlLayoutsSection); + + return htmlLayoutsSection; + } + + /// + /// Adds or renames the grid control. + /// + /// The parent toolbox section. + /// The data. + /// Old name of the file. + /// data + protected virtual void AddOrRenameGridControl(ToolboxSection section, GridControlData data, string toolboxItemName = default(string)) + { + if (data == null) + throw new ArgumentNullException("data"); + + var tools = section.Tools; + + var control = tools.FirstOrDefault(t => t.Name == toolboxItemName); + + if (control == null) + { + control = new ToolboxItem(tools); + control.ControlType = typeof(GridControl).AssemblyQualifiedName; + control.CssClass = data.CssClass; + tools.Add(control); + } + + control.Name = data.Name; + control.Title = data.Title; + control.LayoutTemplate = data.LayoutTemplatePath; + } + + /// + /// Creates the grid controls data. + /// + /// Name of the file. + /// + protected GridControlData CreateGridControlsData(string fileName) + { + var baseTemplatePath = string.Format( + System.Globalization.CultureInfo.InvariantCulture, + GridWidgetRegistrator.GridFolderPathStringTemplate, + FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(FrontendModule).Assembly)); + + var fileNameWithoutExtension = this.GetFileNameWithoutExtension(fileName); + var cssClass = this.GetInferredCssClass(fileNameWithoutExtension); + + var layoutData = new GridControlData() + { + Name = fileNameWithoutExtension, + Title = fileNameWithoutExtension, + LayoutTemplatePath = baseTemplatePath + fileName, + CssClass = cssClass + }; + + return layoutData; + } + + #endregion + + #region Private methods + + /// + /// Gets the file name without extension. + /// + /// Name of the file. + /// + private string GetFileNameWithoutExtension(string fileName) + { + var extension = fileName.Split('.').LastOrDefault(); + var fileNameWithoutExtension = fileName.Substring(0, fileName.Length - (extension.Length + 1)); + + return fileNameWithoutExtension; + } + + private string GetInferredCssClass(string fileNameWithoutExtension) + { + if (this.cssClassMapping.ContainsKey(fileNameWithoutExtension)) + { + return this.cssClassMapping[fileNameWithoutExtension]; + } + else + { + return null; + } + } + + private readonly Dictionary cssClassMapping = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "grid-12", "sfL100" }, + { "grid-3+9", "sfL25_75" }, + { "grid-4+8", "sfL33_67" }, + { "grid-6+6", "sfL50_50" }, + { "grid-8+4", "sfL67_33" }, + { "grid-9+3", "sfL75_25" }, + { "grid-4+4+4", "sfL33_34_33" }, + { "grid-3+6+3", "sfL25_50_25" }, + { "grid-3+3+3+3", "sfL25_25_25_25" }, + { "grid-2+3+2+3+2", "sfL20_20_20_20_20" }, + { "container", "sfL100" } + }; + + #endregion + + #region Constants + + /// + /// The grid folder path string template + /// + public const string GridFolderPathStringTemplate = "~/{0}GridSystem/Templates/"; + + /// + /// The grid section name. + /// + public const string GridSectionName = "Grids"; + + /// + /// The grid section title. + /// + public const string GridSectionTitle = "Grid widgets"; + + #endregion + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/GridSystem/Templates/container.html b/Telerik.Sitefinity.Frontend/GridSystem/Templates/container.html new file mode 100644 index 000000000..5f1bc9d4d --- /dev/null +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/container.html @@ -0,0 +1,2 @@ +
+
diff --git a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-12.html b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-12.html index 0a4b55c21..daae99815 100644 --- a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-12.html +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-12.html @@ -1,6 +1,7 @@ -
-
-
+
+
+
+
\ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-2+3+2+3+2.html b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-2+3+2+3+2.html index a12358d5e..db3f65f78 100644 --- a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-2+3+2+3+2.html +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-2+3+2+3+2.html @@ -1,22 +1,27 @@ -
-
-
+
+
+
+
-
-
+
+
+
-
-
+
+
+
-
-
+
+
+
-
-
+
+
+
-
+
\ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+3+3+3.html b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+3+3+3.html index a6386f372..97e08843b 100644 --- a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+3+3+3.html +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+3+3+3.html @@ -1,18 +1,22 @@ -
-
-
+
+
+
+
-
-
+
+
+
-
-
+
+
+
-
-
+
+
+
-
+
\ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+6+3.html b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+6+3.html index 2ee40381e..a0d9f0538 100644 --- a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+6+3.html +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+6+3.html @@ -1,14 +1,17 @@ -
-
-
+
+
+
+
-
-
+
+
+
-
-
+
+
+
-
+
\ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+9.html b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+9.html index 2001037bb..7e9733a7b 100644 --- a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+9.html +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+9.html @@ -1,10 +1,12 @@ -
-
-
+
+
+
+
-
-
+
+
+
-
\ No newline at end of file +
diff --git a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+4+4.html b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+4+4.html index 50a1de3df..262d0bcce 100644 --- a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+4+4.html +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+4+4.html @@ -1,14 +1,17 @@ -
-
-
+
+
+
+
-
-
+
+
+
-
-
+
+
+
\ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+8.html b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+8.html index b1477e9ba..f4b2485f3 100644 --- a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+8.html +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+8.html @@ -1,10 +1,12 @@ -
-
-
+
+
+
+
-
-
+
+
+
-
+
\ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-6+6.html b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-6+6.html index fc544183d..d392b690b 100644 --- a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-6+6.html +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-6+6.html @@ -1,10 +1,11 @@ -
-
-
+
+
+
+
-
-
+
+
\ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-8+4.html b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-8+4.html index 916ce1cb2..5fa5e715b 100644 --- a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-8+4.html +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-8+4.html @@ -1,10 +1,12 @@ -
-
-
+
+
+
+
-
-
+
+
+
-
+
\ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-9+3.html b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-9+3.html index 1aed765ba..c43e44cc8 100644 --- a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-9+3.html +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-9+3.html @@ -1,10 +1,11 @@ -
-
-
+
+
+
+
-
-
+
+
\ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/IInitializer.cs b/Telerik.Sitefinity.Frontend/IInitializer.cs new file mode 100644 index 000000000..088066e9c --- /dev/null +++ b/Telerik.Sitefinity.Frontend/IInitializer.cs @@ -0,0 +1,18 @@ +namespace Telerik.Sitefinity.Frontend +{ + /// + /// Exposes methods for initializig and reverting the initialization (uninitializing). + /// + internal interface IInitializer + { + /// + /// Initializes this instance. + /// + void Initialize(); + + /// + /// Uninitializes this instance. + /// + void Uninitialize(); + } +} diff --git a/Telerik.Sitefinity.Frontend/InlineEditing/HtmlProcessor.cs b/Telerik.Sitefinity.Frontend/InlineEditing/HtmlProcessor.cs index 21407ba96..02c42dec8 100644 --- a/Telerik.Sitefinity.Frontend/InlineEditing/HtmlProcessor.cs +++ b/Telerik.Sitefinity.Frontend/InlineEditing/HtmlProcessor.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Web.Mvc; using Telerik.Sitefinity.Frontend.InlineEditing.Attributes; +using Telerik.Sitefinity.Services; namespace Telerik.Sitefinity.Frontend.InlineEditing { @@ -11,6 +12,23 @@ namespace Telerik.Sitefinity.Frontend.InlineEditing ///
public class HtmlProcessor { + /// + /// Initializes a new instance of the class. + /// + public HtmlProcessor() + : this(SystemManager.IsInlineEditingMode) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// Value indicating whether HTML should be generated for inline editing. + public HtmlProcessor(bool isInlineEditing) + { + this.isInlineEditingMode = isInlineEditing; + } + /// /// Creates a region which has the required by the InlineEditing attributes. /// @@ -21,17 +39,24 @@ public class HtmlProcessor /// public virtual HtmlRegion CreateInlineEditingRegion(TextWriter writer, string providerName, string type, Guid id) { - string htmlTagType = "div"; - var tagBuilder = new TagBuilder(htmlTagType); - tagBuilder.Attributes.Add("data-sf-provider", providerName); - tagBuilder.Attributes.Add("data-sf-type", type); + if (this.isInlineEditingMode) + { + string htmlTagType = "div"; + var tagBuilder = new TagBuilder(htmlTagType); + tagBuilder.Attributes.Add("data-sf-provider", providerName); + tagBuilder.Attributes.Add("data-sf-type", type); - if (id != Guid.Empty) - tagBuilder.Attributes.Add("data-sf-id", id.ToString()); + if (id != Guid.Empty) + tagBuilder.Attributes.Add("data-sf-id", id.ToString()); - writer.Write(tagBuilder.ToString(TagRenderMode.StartTag)); + writer.Write(tagBuilder.ToString(TagRenderMode.StartTag)); - return new HtmlRegion(writer, htmlTagType); + return new HtmlRegion(writer, htmlTagType); + } + else + { + return new HtmlRegion(writer, string.Empty); + } } /// @@ -51,7 +76,7 @@ public virtual string GetStringContent(object model, string propName) var fieldInfoAttr = propattr.OfType().FirstOrDefault(); - if (fieldInfoAttr == null) + if (fieldInfoAttr == null || !this.isInlineEditingMode) { htmlString = propValue.ToString(); } @@ -63,6 +88,8 @@ public virtual string GetStringContent(object model, string propName) return htmlString; } + private bool isInlineEditingMode; + public const string InlineEditingHtmlWrapper = "
{2}
"; } } diff --git a/Telerik.Sitefinity.Frontend/InterfaceMappings.cs b/Telerik.Sitefinity.Frontend/InterfaceMappings.cs index db125b637..147979f5c 100644 --- a/Telerik.Sitefinity.Frontend/InterfaceMappings.cs +++ b/Telerik.Sitefinity.Frontend/InterfaceMappings.cs @@ -11,6 +11,8 @@ public class InterfaceMappings : NinjectModule public override void Load() { Bind().To(); + Bind().To(); + Bind().To(); } } } diff --git a/Telerik.Sitefinity.Frontend/Modules/Comments/ReviewNotificationStrategy.cs b/Telerik.Sitefinity.Frontend/Modules/Comments/ReviewNotificationStrategy.cs new file mode 100644 index 000000000..8c537930a --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Modules/Comments/ReviewNotificationStrategy.cs @@ -0,0 +1,58 @@ +using System; +using System.Linq; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Services.Comments; +using Telerik.Sitefinity.Services.Comments.Impl.Notifications; +using Telerik.Sitefinity.Services.Comments.Notifications; +using Telerik.Sitefinity.Services.Notifications; + +namespace Telerik.Sitefinity.Frontend.Modules.Comments +{ + /// + /// Notification strategy that is responsible for notifications for objects.. + /// + internal class ReviewNotificationStrategy : CommentNotificationsStrategy, ICommentNotificationsStrategy + { + /// + /// Gets the message template unique identifier for the specified event. + /// + /// The event. + protected override IMessageTemplateRequest GetMessageTemplate(ICommentEvent @event) + { + if (@event == null || @event.Item == null) + return null; + + IMessageTemplateRequest messageTemplate; + IComment comment = @event.Item; + ICommentService cs = SystemManager.GetCommentsService(); + IThread thread = cs.GetThread(comment.ThreadKey); + + if (this.IsReviewThread(thread)) + { + messageTemplate = this.GetNewReviewMessageTemplate(); + } + else + { + messageTemplate = this.GetNewCommentMessageTemplate(); + } + + return messageTemplate; + } + + private bool IsReviewThread(IThread thread) + { + var isReview = false; + + if (thread.Behavior.IsNullOrEmpty()) + { + isReview = thread.Key.EndsWith("_review", StringComparison.Ordinal); + } + else + { + isReview = thread.Behavior == "review"; + } + + return isReview; + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/Scripts/MvcControlTemplateEditor.js b/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/Scripts/MvcControlTemplateEditor.js new file mode 100644 index 000000000..a167d157b --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/Scripts/MvcControlTemplateEditor.js @@ -0,0 +1,90 @@ +Type.registerNamespace("Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.UI"); + +Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.UI.MvcControlTemplateEditor = function(element){ + Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.UI.MvcControlTemplateEditor.initializeBase(this, [element]); + + this._containerToHide = {}; + this._mvcTypes = null; + this._elementIdsToBeHiddenIfMvc = null; +}; + +Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.UI.MvcControlTemplateEditor.prototype = { + + initialize: function () { + Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.UI.MvcControlTemplateEditor.callBaseMethod(this, "initialize"); + + this._containerToHide = this.getInsertSectionContainer(); + this._containerToHide.hide(); + }, + + dispose: function () { + Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.UI.MvcControlTemplateEditor.callBaseMethod(this, "dispose"); + }, + + _valueChangedHandler: function (sender, args) { + + if (!this._isMvcController(sender.target.value)) { + this._dataBindPropertiesItemsList(this._commonPropertiesItemsList); + this._toggleVisibilityOfElements(true); + } else { + this._toggleVisibilityOfElements(false); + } + + this._setModuleTitle(); + this._bindFields(); + }, + // called when data binding was successful + _dataBindSuccess: function (sender, result) { + Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.UI.MvcControlTemplateEditor.callBaseMethod(this, "_dataBindSuccess", [sender, result]); + + if (sender._isMvcController(result.Item.ControlType)) { + sender._toggleVisibilityOfElements(false); + } else { + sender._toggleVisibilityOfElements(true); + } + }, + + _isMvcController: function (item) { + var len = item.indexOf("-"); + + if (len > -1) { + var mvcControllerType = item.substring(0, len); + var mvcControllerTypesArray = JSON.parse(this.get_mvcTypes()); + + for (var i = 0; i < mvcControllerTypesArray.length; i++) + if (mvcControllerTypesArray[i] == mvcControllerType) + return true; + } + + return false; + }, + + _toggleVisibilityOfElements: function(visible){ + var elements = JSON.parse(this.get_elementIdsToBeHiddenIfMvc()); + + for (var i = 0; i < elements.length; i++) { + var uiElement = jQuery('#' + elements[i]); + uiElement.toggle(visible); + } + + this._containerToHide.toggle(visible); + }, + + get_mvcTypes: function () { + return this._mvcTypes; + }, + + set_mvcTypes: function (value) { + this._mvcTypes = value; + }, + + get_elementIdsToBeHiddenIfMvc: function () { + return this._elementIdsToBeHiddenIfMvc; + }, + + set_elementIdsToBeHiddenIfMvc: function (value) { + this._elementIdsToBeHiddenIfMvc = value; + } +} + +Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.UI.MvcControlTemplateEditor.registerClass("Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.UI.MvcControlTemplateEditor", Telerik.Sitefinity.Modules.ControlTemplates.Web.UI.ControlTemplateEditor); \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/UI/MvcControlTemplateEditor.cs b/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/UI/MvcControlTemplateEditor.cs new file mode 100644 index 000000000..ab0b5c5b3 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/UI/MvcControlTemplateEditor.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Web.Script.Serialization; +using System.Web.UI; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; +using Telerik.Sitefinity.Modules.ControlTemplates.Web.UI; +using Telerik.Sitefinity.Web.UI; + +namespace Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.UI +{ + /// + /// Override the original control template editor for Mvc based widgets + /// + internal class MvcControlTemplateEditor : ControlTemplateEditor + { + /// + /// Initializes a new instance of the class. + /// + public MvcControlTemplateEditor() : base() + { + } + + /// + public override string ClientComponentType + { + get + { + return typeof(MvcControlTemplateEditor).FullName; + } + } + + /// + public override IEnumerable GetScriptReferences() + { + var scripts = new List(base.GetScriptReferences()); + + scripts.Add(new ScriptReference(MvcControlTemplateEditor.MvcControlTemplateEditorScript, typeof(MvcControlTemplateEditor).Assembly.FullName)); + + return scripts; + } + + /// + /// Gets Mvc controllers fullnames for current Templatable Controls. + /// + /// List of . + public override IEnumerable GetScriptDescriptors() + { + var descriptor = (ScriptComponentDescriptor)base.GetScriptDescriptors().Last(); + + var mvcTypesFullNames = Telerik.Sitefinity.Modules.ControlTemplates.ControlTemplates.GetTemplatableControls() + .Where(c => c.Value != null && c.Value.DataItemType != null) + .Where(c => FrontendManager.ControllerFactory.IsController(c.Value.DataItemType)) + .Select(c => c.Value.DataItemType.FullName); + + descriptor.AddProperty("mvcTypes", new JavaScriptSerializer().Serialize(mvcTypesFullNames)); + + descriptor.AddProperty("elementIdsToBeHiddenIfMvc", new JavaScriptSerializer().Serialize(this.GetRestoreButtonsClientIds())); + + return new ScriptDescriptor[] { descriptor }; + } + + /// + /// Gets the restore buttons client ids. + /// + private List GetRestoreButtonsClientIds() + { + var returnResult = new List(); + + var topButton = BottomCommandBar.Commands.OfType() + .SingleOrDefault(x => x.CommandName == "restoreTemplate"); + + if (topButton != null) + returnResult.Add(topButton.ButtonClientId); + + var bottomButton = TopCommandBar.Commands.OfType() + .SingleOrDefault(x => x.CommandName == "restoreTemplate"); + + if (bottomButton != null) + returnResult.Add(bottomButton.ButtonClientId); + + return returnResult; + } + + internal const string MvcControlTemplateEditorScript = "Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.Scripts.MvcControlTemplateEditor.js"; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Controllers/CompositePrecompiledMvcEngineWrapper.cs b/Telerik.Sitefinity.Frontend/Mvc/Controllers/CompositePrecompiledMvcEngineWrapper.cs new file mode 100644 index 000000000..6432268f4 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Controllers/CompositePrecompiledMvcEngineWrapper.cs @@ -0,0 +1,247 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Security.Cryptography; +using System.Web.Caching; +using System.Web.Hosting; +using System.Web.Mvc; +using RazorGenerator.Mvc; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Configuration; + +namespace Telerik.Sitefinity.Frontend.Mvc.Controllers +{ + /// + /// View engine that serves precompiled views from several assemblies. + /// + internal class CompositePrecompiledMvcEngineWrapper : CompositePrecompiledMvcEngine + { + /// + /// Initializes a new instance of the class. + /// + /// The view assemblies. + public CompositePrecompiledMvcEngineWrapper(params PrecompiledViewAssemblyWrapper[] viewAssemblies) + : this(viewAssemblies, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The view assemblies. + /// The view page activator. + public CompositePrecompiledMvcEngineWrapper(IEnumerable viewAssemblies, IViewPageActivator viewPageActivator) + : this(viewAssemblies, viewPageActivator, string.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The view assemblies. + /// The view page activator. + /// Name of the package. + public CompositePrecompiledMvcEngineWrapper(IEnumerable viewAssemblies, IViewPageActivator viewPageActivator, string packageName) + : base(viewAssemblies.Select(a => a.PrecompiledViewAssembly), viewPageActivator) + { + this.precompiledAssemblies = viewAssemblies.ToArray(); + this.packageName = packageName; + } + + /// + /// Gets the name of the package. + /// + /// + /// The name of the package. + /// + public string PackageName + { + get + { + return this.packageName; + } + } + + /// + /// Creates a new instance that is a clone of this one. + /// + /// The new instance. + public CompositePrecompiledMvcEngineWrapper Clone() + { + return new CompositePrecompiledMvcEngineWrapper(this.precompiledAssemblies, null, this.PackageName); + } + + /// + /// Computes the hash of the data in the given stream in the expected format for the precompiled assemblies to compare resources. + /// + /// The stream. + /// Base64 string of the MD5 hash of the data in the stream. + internal static string ComputeHash(Stream stream) + { + using (var algorithm = SHA256.Create()) + { + return Convert.ToBase64String(algorithm.ComputeHash(stream)); + } + } + + internal IEnumerable GetViews(IEnumerable viewLocations) + { + var views = new List(); + if (Config.Get().DisablePrecompilation) + return views; + + foreach (var viewLocation in viewLocations) + { + foreach (var asm in this.precompiledAssemblies) + { + var precompiledViews = asm.GetViews(viewLocation); + if (precompiledViews != null) + { + views.AddRange(precompiledViews); + } + } + } + + return views; + } + + /// + /// Files the exists. + /// + /// The controller context. + /// The virtual path. + /// + protected override bool FileExists(ControllerContext controllerContext, string virtualPath) + { + return !Config.Get().DisablePrecompilation && base.FileExists(controllerContext, virtualPath) && (Config.Get().AlwaysUsePrecompiledVersion || this.ShouldServe(controllerContext, virtualPath)); + } + + /// + /// Creates the specified view by using the controller context, path of the view, and path of the master view. + /// + /// The controller context. + /// The path of the view. + /// The path of the master view. + /// + /// A reference to the view. + /// + protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) + { + this.LogPrecompiledViewUsage(controllerContext, viewPath); + return base.CreateView(controllerContext, viewPath, masterPath); + } + + /// + /// Creates the specified partial view by using the specified controller context. + /// + /// The controller context. + /// The partial path for the new partial view. + /// + /// A reference to the partial view. + /// + protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) + { + this.LogPrecompiledViewUsage(controllerContext, partialPath); + return base.CreatePartialView(controllerContext, partialPath); + } + + private void LogPrecompiledViewUsage(ControllerContext controllerContext, string viewPath) + { + if (Config.Get().LogPrecompiledViewUsage && controllerContext != null && controllerContext.Controller != null && controllerContext.RouteData != null) + { + var controllerName = controllerContext.Controller.GetType().Name; + var actionName = controllerContext.RouteData.Values["action"]; + var message = string.Format("Precompiled view used for controller: \"{0}\", action: \"{1}\", ViewPath: {2}", controllerName, actionName, viewPath); + Log.Write(message, TraceEventType.Information); + } + } + + // If for any of the location we find newer version of the file outside the precompiled assebly we add "servePrecompiled" flag in the RotueData. + // This way we ensure that view with bigger prority will be served instead of the first view found from the precompiled view engine. + // See #299642 + private bool ShouldServe(ControllerContext controllerContext, string virtualPath) + { + if (controllerContext.RouteData.Values.ContainsKey("servePrecompiled") && controllerContext.RouteData.Values["servePrecompiled"].ToString() == "false") + return false; + + string precompiledFileHash = null; + foreach (var asm in this.precompiledAssemblies) + { + precompiledFileHash = asm.GetFileHash(virtualPath); + if (precompiledFileHash != null) + break; + } + + if (precompiledFileHash == null) + return true; + + string virtualResourceHash = null; + if (precompiledFileHash != null) + { + virtualResourceHash = this.VirtualResourceHash(virtualPath); + } + + var shouldServe = virtualResourceHash == null || virtualResourceHash == precompiledFileHash; + + if (!shouldServe) + { + controllerContext.RouteData.Values.Add("servePrecompiled", "false"); + } + + return shouldServe; + } + + private string VirtualResourceHash(string virtualPath) + { + CompositePrecompiledMvcEngineWrapper.HashCacheRecord hashRecord; + if (CompositePrecompiledMvcEngineWrapper.HashCache.ContainsKey(virtualPath)) + { + hashRecord = CompositePrecompiledMvcEngineWrapper.HashCache[virtualPath]; + if (hashRecord.Dependency == null || !hashRecord.Dependency.HasChanged) + return hashRecord.Hash; + } + + lock (CompositePrecompiledMvcEngineWrapper.HashCache) + { + if (HostingEnvironment.VirtualPathProvider.FileExists(virtualPath)) + { + using (var stream = HostingEnvironment.VirtualPathProvider.GetFile(virtualPath).Open()) + { + hashRecord = new CompositePrecompiledMvcEngineWrapper.HashCacheRecord() + { + Hash = CompositePrecompiledMvcEngineWrapper.ComputeHash(stream), + Dependency = HostingEnvironment.VirtualPathProvider.GetCacheDependency(virtualPath, new object[0], DateTime.UtcNow) + }; + } + } + else + { + hashRecord = new CompositePrecompiledMvcEngineWrapper.HashCacheRecord() + { + Hash = null, + Dependency = null + }; + } + + CompositePrecompiledMvcEngineWrapper.HashCache[virtualPath] = hashRecord; + } + + return hashRecord.Hash; + } + + private class HashCacheRecord + { + public string Hash { get; set; } + + public CacheDependency Dependency { get; set; } + } + + private static readonly ConcurrentDictionary HashCache = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + + private readonly PrecompiledViewAssemblyWrapper[] precompiledAssemblies; + private readonly string packageName; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Controllers/ContentPagerController.cs b/Telerik.Sitefinity.Frontend/Mvc/Controllers/ContentPagerController.cs index eb01e3adc..c3941a4e4 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Controllers/ContentPagerController.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Controllers/ContentPagerController.cs @@ -1,15 +1,20 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using System.Reflection; using System.Web.Mvc; using Telerik.Sitefinity.Frontend.Mvc.Helpers.ViewModels; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes; +using Telerik.Sitefinity.Frontend.Mvc.StringResources; +using Telerik.Sitefinity.Web; +using Telerik.Sitefinity.Web.UI; namespace Telerik.Sitefinity.Frontend.Mvc.Controllers { /// /// This class represents controller for pager widget. /// + [Localization(typeof(ContentPagerResources))] + [ControllerMetadata(IsTemplatableControl = false)] public class ContentPagerController : Controller { /// @@ -18,12 +23,112 @@ public class ContentPagerController : Controller /// The current page. /// The total pages count. /// The template of the URL used for redirecting. + /// The display count of the pages. /// - public PartialViewResult Index(int currentPage, int totalPagesCount, string redirectUrlTemplate) + [OutputCache(Duration = 1)] + public PartialViewResult Index(int currentPage, int totalPagesCount, string redirectUrlTemplate, int displayCount = 10) { - var model = new PagerViewModel(currentPage, totalPagesCount, redirectUrlTemplate); + var model = new PagerViewModel(currentPage, totalPagesCount, redirectUrlTemplate, displayCount); + + // Build the pager + int startIndex = 1; + if (model.CurrentPage > model.DisplayCount) + { + if (model.CurrentPage <= 0) + model.CurrentPage = 1; + + startIndex = ((int)Math.Floor((double)(model.CurrentPage - 1) / model.DisplayCount) * model.DisplayCount) + 1; + } + + int endIndex = Math.Min(model.TotalPagesCount, (startIndex + model.DisplayCount) - 1); + + // Check to see if we need a Previous Button Node + if (startIndex > model.DisplayCount) + { + model.PreviousNode = new Pager.PagerNumericItem(Math.Max(startIndex - 1, 1)); + } + else + { + model.PreviousNode = null; + } + + for (int i = startIndex; i <= endIndex; i++) + { + var text = string.Format(model.RedirectUrlTemplate, i); + Pager.PagerNumericItem pagerNumericItem = new Pager.PagerNumericItem(i, text); + model.PagerNodes.Add(pagerNumericItem); + } + + // Check to see if we need a Next Button Node + if (endIndex < model.TotalPagesCount) + { + model.NextNode = new Pager.PagerNumericItem(endIndex + 1); + } + else + { + model.NextNode = null; + } + + this.TryStorePaginationUrls(model); return this.PartialView("Pager", model); } + + internal static object GetPaginationUrls(string nextUrl, string previousUrl) + { + var paginationUrlsType = Type.GetType("Telerik.Sitefinity.ContentLocations.PaginationUrls, Telerik.Sitefinity"); + var instance = Activator.CreateInstance(paginationUrlsType, nonPublic: true); + paginationUrlsType.GetProperty("PreviousUrl").SetValue(instance, previousUrl); + paginationUrlsType.GetProperty("NextUrl").SetValue(instance, nextUrl); + + return instance; + } + + internal static MethodInfo GetTryStorePaginationUrlsMethod() + { + var canonicalUrlExtensions = Type.GetType("Telerik.Sitefinity.ContentLocations.CanonicalUrlPageExtensions, Telerik.Sitefinity"); + return canonicalUrlExtensions.GetMethod("TryStorePaginationUrls", BindingFlags.Static | BindingFlags.NonPublic); + } + + private static string PageNodeUrl(Pager.PagerNumericItem node, string template) + { + if (node == null) + return null; + else + return RouteHelper.ResolveUrl(string.Format(template, node.PageNumber), UrlResolveOptions.Absolute); + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "paginationUrls")] + private void TryStorePaginationUrls(PagerViewModel model) + { + string nextUrl; + var highlightedIndex = model.CurrentPage % model.DisplayCount; + if (highlightedIndex == 0) + { + highlightedIndex = model.DisplayCount; + } + + if (model.CurrentPage > 0 && model.CurrentPage < model.TotalPagesCount) + if (highlightedIndex == model.DisplayCount) + nextUrl = ContentPagerController.PageNodeUrl(model.NextNode, model.RedirectUrlTemplate); + else + nextUrl = ContentPagerController.PageNodeUrl(model.PagerNodes[highlightedIndex], model.RedirectUrlTemplate); + else + nextUrl = null; + + string previousUrl; + if (model.CurrentPage > 1 && model.CurrentPage <= model.TotalPagesCount) + if (highlightedIndex > 1) + previousUrl = ContentPagerController.PageNodeUrl(model.PagerNodes[highlightedIndex - 2], model.RedirectUrlTemplate); + else + previousUrl = ContentPagerController.PageNodeUrl(model.PreviousNode, model.RedirectUrlTemplate); + else + previousUrl = null; + + var paginationUrls = ContentPagerController.GetPaginationUrls(nextUrl, previousUrl); + + var page = this.HttpContext.Handler.GetPageHandler(); + ContentPagerController.GetTryStorePaginationUrlsMethod().Invoke(null, new object[] { page, paginationUrls }); + } } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Controllers/DesignerController.cs b/Telerik.Sitefinity.Frontend/Mvc/Controllers/DesignerController.cs index e5ecdf35e..67be1f5a7 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Controllers/DesignerController.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Controllers/DesignerController.cs @@ -1,10 +1,18 @@ -using System; -using System.Collections.Generic; -using System.Web.Mvc; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes; -using Telerik.Sitefinity.Frontend.Mvc.Models; -using Telerik.Sitefinity.Frontend.Mvc.StringResources; +using System; +using System.Collections.Generic; +using System.Web; +using System.Web.Mvc; +using System.Web.Routing; +using System.Web.UI; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes; +using Telerik.Sitefinity.Frontend.Mvc.Models; +using Telerik.Sitefinity.Frontend.Mvc.StringResources; +using Telerik.Sitefinity.Modules; +using Telerik.Sitefinity.Modules.Forms; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Services; namespace Telerik.Sitefinity.Frontend.Mvc.Controllers { @@ -13,19 +21,28 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Controllers /// [Localization(typeof(DesignerResources))] [RequestBackendUserAuthentication] + [ControllerMetadataAttribute(IsTemplatableControl = false)] public class DesignerController : Controller - { + { /// /// Returns the designer view which handles the property editing for a particular widget. /// If there is custom designer for the particular widget it will be retrieved, otherwise it will fallback to the default designer. /// The default designer is located under . /// /// The name of the widget. - public virtual ActionResult Master(string widgetName) - { + /// The name of the widget dynamic module (if any). Default value is null. + public virtual ActionResult Master(string widgetName, string moduleName = null) + { + this.GetHttpContext().Items[SystemManager.IsBackendRequestKey] = true; + + var controlId = this.Request != null ? this.Request["controlId"] ?? Guid.Empty.ToString() : Guid.Empty.ToString(); + var mediaType = this.Request != null ? this.Request["mediaType"] ?? DesignMediaType.Page.ToString() : DesignMediaType.Page.ToString(); + this.ViewBag.ControlName = widgetName; + this.ViewBag.ControlId = controlId; + this.ViewBag.MediaType = mediaType; - var model = this.GetModel(widgetName); + var model = this.GetModel(widgetName, Guid.Parse(controlId), moduleName, (DesignMediaType)Enum.Parse(typeof(DesignMediaType), mediaType)); return this.View(DesignerController.DefaultView, model); } @@ -39,28 +56,107 @@ public virtual ActionResult Master(string widgetName) /// /// View cannot be found on the searched locations. public new virtual ActionResult View(string widgetName, string viewType) - { - var viewName = DesignerController.DesignerViewTemplate.Arrange(viewType); + { + this.GetHttpContext().Items[SystemManager.IsBackendRequestKey] = true; + + var viewName = DesignerController.DesignerViewTemplate.Arrange(viewType); + var mediaType = this.Request != null ? this.Request["mediaType"] ?? DesignMediaType.Page.ToString() : DesignMediaType.Page.ToString(); + var designMediaType = (DesignMediaType)Enum.Parse(typeof(DesignMediaType), mediaType); + + var model = this.GetViewModel(designMediaType); - return this.PartialView(viewName); + // Passing the DesignerModel to the view model + var controlIdParam = this.GetControlIdParam(); + if (controlIdParam.HasValue) + { + ViewBag.DesignerModel = this.GetModel(widgetName, controlIdParam.Value, designMediaType: designMediaType); + } + + return this.PartialView(viewName, model); + } + + /// + /// Gets the HTTP context. + /// + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] + protected virtual HttpContextBase GetHttpContext() + { + return this.HttpContext; } + private Guid? GetControlIdParam() + { + if (this.Request == null) + return null; + + var controlIdParam = this.Request["controlId"]; + if (controlIdParam == null) + return null; + + Guid controlIdParamAsGuid; + if (!Guid.TryParse(controlIdParam.ToString(), out controlIdParamAsGuid)) + return null; + + return controlIdParamAsGuid; + } + /// /// Gets the model of the designer. /// - private IDesignerModel GetModel(string widgetName) - { + private IDesignerModel GetModel(string widgetName, Guid controlId, string moduleName = null, DesignMediaType designMediaType = DesignMediaType.Page) + { + var viewFilesMappgings = new Dictionary(); + var constructorParameters = new Dictionary - { - { "views", this.GetPartialViews() }, - { "viewLocations", this.GetPartialViewLocations() }, - { "widgetName", widgetName }, - { "preselectedView", this.Request != null ? this.Request["view"] : null } - }; + { + { "views", this.GetPartialViews(ref viewFilesMappgings, moduleName) }, + { "viewLocations", this.GetPartialViewLocations() }, + { "widgetName", widgetName }, + { "controlId", controlId }, + { "preselectedView", this.Request != null ? this.Request["view"] : null }, + { "viewFilesMappings", viewFilesMappgings }, + { "mediaType", designMediaType } + }; return ControllerModelFactory.GetModel(typeof(DesignerController), constructorParameters); } + private Control GetViewModel(DesignMediaType designMediaType) + { + var controlIdParam = this.GetControlIdParam(); + + if (!controlIdParam.HasValue) + return null; + + var controlId = controlIdParam.Value; + var manager = this.GetControlManager(designMediaType); + var viewModel = manager.LoadControl(manager.GetControl(controlId)); + + var widgetProxy = viewModel as MvcWidgetProxy; + if (widgetProxy != null) + { + if (widgetProxy.Controller.RouteData == null) + widgetProxy.Controller.ControllerContext = new ControllerContext(new RequestContext(this.HttpContext, new RouteData()), widgetProxy.Controller); + + widgetProxy.Controller.RouteData.Values["controller"] = widgetProxy.WidgetName; + } + + return viewModel; + } + + private IControlManager GetControlManager(DesignMediaType designMediaType) + { + if (designMediaType == DesignMediaType.Form) + { + return FormsManager.GetManager(); + } + else + { + return PageManager.GetManager(); + } + } + private const string DefaultView = "Designer"; private const string DesignerViewTemplate = "DesignerView.{0}"; } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Controllers/GenericController.cs b/Telerik.Sitefinity.Frontend/Mvc/Controllers/GenericController.cs index ebda8af40..ea07d709c 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Controllers/GenericController.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Controllers/GenericController.cs @@ -1,9 +1,11 @@ using System.Web.Mvc; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes; namespace Telerik.Sitefinity.Frontend.Mvc.Controllers { // Just a generic controller for the view resolving purposes - public class GenericController : Controller + [ControllerMetadataAttribute(IsTemplatableControl = false)] + internal class GenericController : Controller { } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Controllers/GridDesignerController.cs b/Telerik.Sitefinity.Frontend/Mvc/Controllers/GridDesignerController.cs new file mode 100644 index 000000000..62d778a6c --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Controllers/GridDesignerController.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +using System.Web.Mvc; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes; +using Telerik.Sitefinity.Frontend.Mvc.Models; +using Telerik.Sitefinity.Frontend.Mvc.StringResources; +using Telerik.Sitefinity.Services; + +namespace Telerik.Sitefinity.Frontend.Mvc.Controllers +{ + /// + /// This class contains logic for resolving the views of the MVC designer of a grid. + /// + [Localization(typeof(GridDesignerResources))] + [RequestBackendUserAuthentication] + public class GridDesignerController : Controller + { + /// + /// Returns the designer view which handles the property editing for a particular grid. + /// If there is custom designer for the particular widget it will be retrieved, otherwise it will fallback to the default designer. + /// The default designer is located under . + /// + /// The name of the widget. + public virtual ActionResult Master(string widgetName) + { + this.GetHttpContext().Items[SystemManager.IsBackendRequestKey] = true; + + var controlId = this.Request != null ? this.Request["controlId"] ?? Guid.Empty.ToString() : Guid.Empty.ToString(); + var gridTitle = this.Request != null ? this.Request["gridTitle"] ?? Guid.Empty.ToString() : Guid.Empty.ToString(); + + var model = this.GetModel(gridTitle, controlId); + + return this.View(GridDesignerController.DefaultView, model); + } + + /// + /// Gets the HTTP context. + /// + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] + protected virtual HttpContextBase GetHttpContext() + { + return this.HttpContext; + } + + /// + /// Gets the model of the designer. + /// + private IGridDesignerModel GetModel(string gridTitle, string controlId) + { + var constructorParameters = new Dictionary + { + { "gridTitle", gridTitle }, + { "controlId", controlId } + }; + + return ControllerModelFactory.GetModel(typeof(GridDesignerController), constructorParameters); + } + + private const string DefaultView = "Designer"; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Controllers/PersonalizationDesignerController.cs b/Telerik.Sitefinity.Frontend/Mvc/Controllers/PersonalizationDesignerController.cs new file mode 100644 index 000000000..120318c3c --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Controllers/PersonalizationDesignerController.cs @@ -0,0 +1,60 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Web; +using System.Web.Mvc; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes; +using Telerik.Sitefinity.Frontend.Mvc.Models; +using Telerik.Sitefinity.Frontend.Mvc.StringResources; +using Telerik.Sitefinity.Localization; +using Telerik.Sitefinity.Services; + +namespace Telerik.Sitefinity.Frontend.Mvc.Controllers +{ + /// + /// This class contains logic for resolving the views of the MVC designer of a grid. + /// + [Localization(typeof(PersonalizationDesignerResources))] + [RequestBackendUserAuthentication] + public class PersonalizationDesignerController : Controller + { + /// + /// Returns the designer view which handles the property editing for a particular grid. + /// If there is custom designer for the particular widget it will be retrieved, otherwise it will fallback to the default designer. + /// The default designer is located under . + /// + public virtual ActionResult Master() + { + this.GetHttpContext().Items[SystemManager.IsBackendRequestKey] = true; + + var title = Res.Get().PersonalizationDialogCaption; + var model = this.GetModel(); + model.Title = title; + + return this.View(PersonalizationDesignerController.DefaultView, model); + } + + /// + /// Gets the HTTP context. + /// + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] + protected virtual HttpContextBase GetHttpContext() + { + return this.HttpContext; + } + + /// + /// Gets the model of the designer. + /// + private IPersonalizationDesignerModel GetModel() + { + return ControllerModelFactory.GetModel(typeof(PersonalizationDesignerController)); + } + + private const string DefaultView = "Personalization"; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Controllers/PrecompiledViewAssemblyWrapper.cs b/Telerik.Sitefinity.Frontend/Mvc/Controllers/PrecompiledViewAssemblyWrapper.cs new file mode 100644 index 000000000..522949152 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Controllers/PrecompiledViewAssemblyWrapper.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text.RegularExpressions; +using RazorGenerator.Mvc; + +namespace Telerik.Sitefinity.Frontend.Mvc.Controllers +{ + /// + /// This class wraps a PrecompiledViewAssembly to + /// + internal class PrecompiledViewAssemblyWrapper + { + /// + /// Initializes a new instance of the class. + /// + /// The assembly. + /// The package. + public PrecompiledViewAssemblyWrapper(Assembly assembly, string package) + { + this.assembly = assembly; + this.basePath = package == null ? "~/" + FrontendManager.VirtualPathBuilder.GetVirtualPath(assembly) : "~/" + FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(PrecompiledViewAssemblyWrapper)); + this.precompiledViewAssembly = new PrecompiledViewAssembly(assembly, this.basePath) + { + UsePhysicalViewsIfNewer = false + }; + + this.embeddedResourceHashes = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var name in this.assembly.GetManifestResourceNames()) + { + this.embeddedResourceHashes[name] = this.ComputeHashForResource(name); + } + } + + /// + /// Gets the precompiled view assembly. + /// + /// + /// The precompiled view assembly. + /// + public PrecompiledViewAssembly PrecompiledViewAssembly + { + get + { + return this.precompiledViewAssembly; + } + } + + /// + /// Gets the hash of the resource on the virtual path. + /// + /// The virtual path of the resource. + /// Hash of the resource. + public string GetFileHash(string virtualPath) + { + if (virtualPath.StartsWith(this.basePath, StringComparison.OrdinalIgnoreCase)) + { + var relativePath = virtualPath.Right(virtualPath.Length - this.basePath.Length); + var relativePathWithoutSpaces = Regex.Replace(relativePath, @"[ \-]", "_").Replace('/', '.'); + var resourcePathWithoutSpaces = this.assembly.GetName().Name + "." + relativePathWithoutSpaces; + var relativePathWithSpaces = Regex.Replace(relativePath, @"[\-]", "_").Replace('/', '.'); + var resourcePathWithSpaces = this.assembly.GetName().Name + "." + relativePathWithSpaces; + + if (this.embeddedResourceHashes.ContainsKey(resourcePathWithoutSpaces)) + { + return this.embeddedResourceHashes[resourcePathWithoutSpaces]; + } + else if (this.embeddedResourceHashes.ContainsKey(resourcePathWithSpaces)) + { + return this.embeddedResourceHashes[resourcePathWithSpaces]; + } + } + + return null; + } + + public IEnumerable GetViews(string virtualFolderPath) + { + if (virtualFolderPath.StartsWith(this.basePath, StringComparison.OrdinalIgnoreCase)) + { + var relativePath = virtualFolderPath.Right(virtualFolderPath.Length - this.basePath.Length); + var relativePathWithSpaces = Regex.Replace(relativePath, @"[\-]", "_").Replace('/', '.'); + var resourcePathWithSpaces = this.assembly.GetName().Name + "." + relativePathWithSpaces; + + var resources = this.embeddedResourceHashes.Keys + .Where(resourceKey => resourceKey.ToUpperInvariant().Contains(resourcePathWithSpaces.ToUpperInvariant())) + .Select(key => Path.GetFileNameWithoutExtension(Regex.Replace(key, resourcePathWithSpaces, string.Empty, RegexOptions.IgnoreCase))); + + return resources; + } + + return new List(); + } + + private string ComputeHashForResource(string resourceName) + { + using (var stream = this.assembly.GetManifestResourceStream(resourceName)) + { + return CompositePrecompiledMvcEngineWrapper.ComputeHash(stream); + } + } + + private readonly PrecompiledViewAssembly precompiledViewAssembly; + private readonly Assembly assembly; + private readonly string basePath; + private readonly Dictionary embeddedResourceHashes; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/AspHtmlHelperExtensions.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/AspHtmlHelperExtensions.cs new file mode 100644 index 000000000..6c74cd062 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/AspHtmlHelperExtensions.cs @@ -0,0 +1,144 @@ +// It is important to keep the namespace. This way these extensions take precedence over the default System.Web.Mvc.Html.PartialExtensions. +namespace ASP +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Text; + using System.Web.Mvc; + using Telerik.Sitefinity.Services; + + /// + /// extensions methods for rendering partial views. + /// + public static class PartialExtensions + { + /// + /// Renders the partial view with the specified name. + /// + /// The HTML helper. + /// Name of the partial view. + /// Rendered partial view. + public static System.Web.Mvc.MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName) + { + return PartialExtensions.Partial(htmlHelper, partialViewName, null, htmlHelper.ViewData); + } + + /// + /// Renders the partial view with the specified name. + /// + /// The HTML helper. + /// Name of the partial view. + /// The view data. + /// + /// Rendered partial view. + /// + public static System.Web.Mvc.MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData) + { + return PartialExtensions.Partial(htmlHelper, partialViewName, null, viewData); + } + + /// + /// Renders the partial view with the specified name. + /// + /// The HTML helper. + /// Name of the partial view. + /// The model. + /// + /// Rendered partial view. + /// + public static System.Web.Mvc.MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model) + { + return PartialExtensions.Partial(htmlHelper, partialViewName, model, htmlHelper.ViewData); + } + + /// + /// Renders the partial view with the specified name. + /// + /// The HTML helper. + /// Name of the partial view. + /// The model. + /// The view data. + /// + /// Rendered partial view. + /// + public static System.Web.Mvc.MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData) + { + using (var writer = new StringWriter(CultureInfo.CurrentCulture)) + { + PartialExtensions.RenderPartialInternal(htmlHelper, partialViewName, viewData, model, writer); + return MvcHtmlString.Create(writer.ToString()); + } + } + + /// Renders the specified partial view by using the specified HTML helper. + /// The HTML helper. + /// The name of the partial view + public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName) + { + PartialExtensions.RenderPartialInternal(htmlHelper, partialViewName, htmlHelper.ViewData, null, htmlHelper.ViewContext.Writer); + } + + /// Renders the specified partial view, replacing its ViewData property with the specified object. + /// The HTML helper. + /// The name of the partial view. + /// The view data. + public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData) + { + PartialExtensions.RenderPartialInternal(htmlHelper, partialViewName, viewData, null, htmlHelper.ViewContext.Writer); + } + + /// Renders the specified partial view, passing it a copy of the current object, but with the Model property set to the specified model. + /// The HTML helper. + /// The name of the partial view. + /// The model. + public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model) + { + PartialExtensions.RenderPartialInternal(htmlHelper, partialViewName, htmlHelper.ViewData, model, htmlHelper.ViewContext.Writer); + } + + /// Renders the specified partial view, replacing the partial view's ViewData property with the specified object and setting the Model property of the view data to the specified model. + /// The HTML helper. + /// The name of the partial view. + /// The model for the partial view. + /// The view data for the partial view. + public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData) + { + PartialExtensions.RenderPartialInternal(htmlHelper, partialViewName, viewData, model, htmlHelper.ViewContext.Writer); + } + + private static void RenderPartialInternal(HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData, object model, TextWriter writer) + { + ViewDataDictionary newViewData; + if (model == null) + { + newViewData = viewData == null ? new ViewDataDictionary(htmlHelper.ViewData) : new ViewDataDictionary(viewData); + } + else + { + newViewData = viewData == null ? new ViewDataDictionary(model) : new ViewDataDictionary(viewData) { Model = model }; + } + + var controller = htmlHelper.ViewContext.Controller as Controller; + var viewEngineCollection = controller != null ? controller.ViewEngineCollection : ViewEngines.Engines; + var newViewContext = new ViewContext(htmlHelper.ViewContext, htmlHelper.ViewContext.View, newViewData, htmlHelper.ViewContext.TempData, writer); + var result = viewEngineCollection.FindPartialView(newViewContext, partialViewName); + if (result.View != null) + { + result.View.Render(newViewContext, writer); + } + else + { + var locationsText = new StringBuilder(); + foreach (string location in result.SearchedLocations) + { + locationsText.AppendLine(); + locationsText.Append(location); + } + + throw new InvalidOperationException("The partial view '{0}' was not found or no view engine supports the searched locations. The following locations were searched: {1}".Arrange(partialViewName, locationsText)); + } + } + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/CommentsHelpers.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/CommentsHelpers.cs new file mode 100644 index 000000000..f3eacb5a7 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/CommentsHelpers.cs @@ -0,0 +1,226 @@ +using System; +using System.Linq; +using System.Web; +using System.Web.Mvc; +using System.Web.Mvc.Html; +using Telerik.Sitefinity.Data; +using Telerik.Sitefinity.DynamicModules.Builder; +using Telerik.Sitefinity.DynamicModules.Builder.Model; +using Telerik.Sitefinity.DynamicModules.Model; +using Telerik.Sitefinity.GenericContent.Model; +using Telerik.Sitefinity.Model; +using Telerik.Sitefinity.Modules.Comments; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Web.UI; + +namespace Telerik.Sitefinity.Frontend.Mvc.Helpers +{ + /// + /// Holds helpers related to Comments widget + /// + public static class CommentsHelpers + { + /// + /// Returns the CommentsCount widget if exist, else render error message + /// + /// The helper. + /// The navigate URL. + /// The commented item. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#")] + public static MvcHtmlString CommentsCount(this HtmlHelper helper, string navigateUrl, IDataItem item) + { + if (item == null) + return MvcHtmlString.Empty; + + var contentItem = item as Content; + bool? allowComments = contentItem != null ? contentItem.AllowComments : null; + + if (NewslettersHelper.IsNewsletter()) + { + allowComments = false; + } + + var threadKey = ControlUtilities.GetLocalizedKey(item.Id, null, CommentsBehaviorUtilities.GetLocalizedKeySuffix(item.GetType().FullName)); + var itemTypeFullName = item.GetType().FullName; + + return CommentsHelpers.CommentsCount(helper, navigateUrl, threadKey, itemTypeFullName, allowComments); + } + + /// + /// Returns the CommentsCount widget if exist, else render error message + /// + /// The HTML helper. + /// The navigate URL. + /// The thread key. + /// Type of the thread. + /// if not null this value will override the configuration for allowing comments. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#")] + public static MvcHtmlString CommentsCount(this HtmlHelper helper, string navigateUrl, string threadKey, string threadType, bool? allowComments = null) + { + if (SystemManager.GetModule("Comments") == null || string.IsNullOrEmpty(threadKey)) + return MvcHtmlString.Empty; + + if (string.IsNullOrEmpty(navigateUrl)) + { + navigateUrl = "#comments-" + threadKey; + } + + var controllerName = threadKey.EndsWith(ReviewsSuffix, StringComparison.Ordinal) ? CommentsHelpers.ReviewsControllerName : CommentsHelpers.CommentsControllerName; + + MvcHtmlString result; + try + { + result = helper.Action(CommentsHelpers.CountActionName, controllerName, new { NavigateUrl = navigateUrl, ThreadKey = threadKey, ThreadType = threadType, AllowComments = allowComments }); + } + catch (HttpException) + { + result = MvcHtmlString.Empty; + } + catch (NullReferenceException) + { + //// Telerik.Sitefinity.Mvc.SitefinityMvcRoute GetOrderedParameters() on line 116 controllerType.GetMethods() throws null reference exception (controllerType is null). + result = MvcHtmlString.Empty; + } + + return result; + } + + /// + /// Renders comments list. + /// + /// The helper. + /// The item. + public static MvcHtmlString CommentsList(this HtmlHelper helper, IDataItem item) + { + var title = CommentsHelpers.GetTitle(item); + return CommentsHelpers.GetCommentsList(helper, item, title); + } + + /// + /// Renders comments list. + /// + /// The helper. + /// The item. + /// The title. + public static MvcHtmlString CommentsList(this HtmlHelper helper, IDataItem item, string title) + { + return CommentsHelpers.GetCommentsList(helper, item, title); + } + + private static MvcHtmlString GetCommentsList(HtmlHelper helper, IDataItem item, string title) + { + if (SystemManager.GetModule("Comments") == null || item == null) + { + return MvcHtmlString.Empty; + } + + var itemTypeFullName = item.GetType().FullName; + var itemProviderName = item.GetProviderName(); + + var itemThreadKey = ControlUtilities.GetLocalizedKey(item.Id, null, CommentsBehaviorUtilities.GetLocalizedKeySuffix(itemTypeFullName)); + var itemGroupKey = ControlUtilities.GetUniqueProviderKey(GetDataSourceName(item), itemProviderName); + + var routeDictionary = new System.Web.Routing.RouteValueDictionary() + { + { "AllowComments", GetAllowComments(item) }, + { "ThreadKey", itemThreadKey }, + { "ThreadTitle", title }, + { "ThreadType", itemTypeFullName }, + { "GroupKey", itemGroupKey }, + { "DataSource", itemProviderName } + }; + + var controllerName = itemThreadKey.EndsWith(ReviewsSuffix, StringComparison.Ordinal) ? CommentsHelpers.ReviewsControllerName : CommentsHelpers.CommentsControllerName; + + MvcHtmlString result; + try + { + result = helper.Action(CommentsHelpers.IndexActionName, controllerName, routeDictionary); + } + catch (HttpException) + { + result = MvcHtmlString.Empty; + } + catch (NullReferenceException) + { + //// Telerik.Sitefinity.Mvc.SitefinityMvcRoute GetOrderedParameters() on line 116 controllerType.GetMethods() throws null reference exception (controllerType is null). + result = MvcHtmlString.Empty; + } + + return result; + } + + private static string GetDataSourceName(IDataItem item) + { + string dataSourceName = null; + + if (item != null && item is DynamicContent) + { + var itemType = item.GetType(); + + var dynamicContentType = ModuleBuilderManager.GetActiveTypes() + .FirstOrDefault(t => t.TypeNamespace == itemType.Namespace && t.TypeName == itemType.Name); + + if (dynamicContentType != null) + { + dataSourceName = dynamicContentType.ModuleName; + } + } + else if (item != null) + { + Type managerType; + if (ManagerBase.TryGetMappedManagerType(item.GetType(), out managerType)) + { + dataSourceName = managerType.FullName; + } + } + + return dataSourceName; + } + + private static string GetTitle(IDataItem item) + { + string title = null; + + if (item != null) + { + var hasTitleItem = item as IHasTitle; + if (hasTitleItem != null) + { + title = hasTitleItem.GetTitle(); + } + } + + return title; + } + + private static bool? GetAllowComments(IDataItem item) + { + bool? allowComments = null; + + if (item != null) + { + var contentItem = item as Content; + if (contentItem != null) + { + allowComments = contentItem.AllowComments; + } + } + + if (NewslettersHelper.IsNewsletter()) + { + allowComments = false; + } + + return allowComments; + } + + private const string ReviewsSuffix = "_review"; + + private const string CommentsControllerName = "Comments"; + private const string ReviewsControllerName = "Reviews"; + private const string IndexActionName = "Index"; + private const string CountActionName = "Count"; + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/ContentDataItemResolver.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ContentDataItemResolver.cs new file mode 100644 index 000000000..b99740b59 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ContentDataItemResolver.cs @@ -0,0 +1,289 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Web.Mvc; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.ContentLocations; +using Telerik.Sitefinity.Data; +using Telerik.Sitefinity.DynamicModules; +using Telerik.Sitefinity.DynamicModules.Model; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing; +using Telerik.Sitefinity.GenericContent.Model; +using Telerik.Sitefinity.Lifecycle; +using Telerik.Sitefinity.Model; +using Telerik.Sitefinity.Modules.GenericContent; +using Telerik.Sitefinity.Mvc.Proxy.Security; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Utilities.TypeConverters; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Helpers +{ + /// + /// The class contains helper methods related to resolving detail content items operations. + /// + public class ContentDataItemResolver + { + /// + /// Gets the detail content item. + /// + /// The controller. + /// Contains information about the route parameters. + public IDataItem GetItemByController(ControllerBase controller, string[] routeParams) + { + string redirectUrl = null; + IDataItem item = null; + + var url = RouteHelper.GetUrlParameterString(routeParams); + + var itemType = this.GetItemType(controller); + if (itemType != null) + { + var providerNames = this.GetProviderNames(controller, itemType); + foreach (var providerName in providerNames) + { + item = this.GetItemByUrl(url, itemType, providerName, out redirectUrl); + if (item != null) + { + return item; + } + } + } + + return item; + } + + /// + /// Gets the content item by URL. + /// + /// The URL. + /// The content type of the item. + /// The provider of the item + /// The redirect URL. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "3#"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")] + public IDataItem GetItemByUrl(string url, Type itemType, string provider, out string redirectUrl) + { + var manager = this.ResolveManager(itemType, provider); + if (manager == null) + { + redirectUrl = null; + return null; + } + + var itemIdFromQueryParam = (SystemManager.CurrentHttpContext.Request.ParamsGet("sf-itemId") ?? SystemManager.CurrentHttpContext.Items["sf-itemId"]) as string; + if (!itemIdFromQueryParam.IsNullOrEmpty()) + { + Guid itemIdGuid; + if (Guid.TryParse(itemIdFromQueryParam, out itemIdGuid)) + { + redirectUrl = null; + return manager.GetItem(itemType, itemIdGuid) as IDataItem; + } + } + + IDataItem item = null; + if (manager is IContentManager || manager is DynamicModuleManager) + { + try + { + item = this.GetItemFromUrl(manager, itemType, url, out redirectUrl); + } + catch (System.UnauthorizedAccessException e) + { + redirectUrl = null; + ItemAccessException access = new ItemAccessException(e.Message, e.InnerException); + access.Data["ItemType"] = itemType.Name; + + throw access; + } + + if (item != null) + { + var type = item.GetType(); + if (!type.Equals(itemType) && !(type.Module != null && type.Module.ScopeName == "OpenAccessDynamic" && type.BaseType != null && type.BaseType.Equals(itemType))) + { + item = null; + } + } + } + else + { + item = ((IUrlProvider)manager.Provider).GetItemFromUrl(itemType, url, out redirectUrl); + } + + var lifecycleItem = item as ILifecycleDataItem; + var lifecycleManager = manager as ILifecycleManager; + if (lifecycleItem != null && lifecycleManager != null) + { + ContentLifecycleStatus requestedStatus = ContentLocatableViewExtensions.GetRequestedItemStatus(); + if (lifecycleItem.Status != requestedStatus) + { + item = lifecycleManager.Lifecycle.GetLive(lifecycleItem); + } + + object requestedItem; + if (ContentLocatableViewExtensions.TryGetItemWithRequestedStatus(lifecycleItem, lifecycleManager, out requestedItem)) + { + item = requestedItem as IDataItem; + } + } + + return item; + } + + private IDataItem GetItemFromUrl(IManager manager, Type itemType, string url, out string redirectUrl) + { + IDataItem item = null; + var isPublished = !this.IsPreviewRequested() || this.ResolveRequestedItemStatus() == ContentLifecycleStatus.Live; + + if (manager is IContentManager) + { + var contentManager = manager as IContentManager; + item = contentManager.GetItemFromUrl(itemType, url, isPublished, out redirectUrl); + } + else + { + var dynamicManager = manager as DynamicModuleManager; + item = dynamicManager.Provider.GetItemFromUrl(itemType, url, isPublished, out redirectUrl); + } + + return item; + } + + /// + /// Gets the type of the content item for specified controller. + /// + /// The controller. + private Type GetItemType(ControllerBase controller) + { + var controllerType = controller.GetType(); + Type contentType = null; + var detailsAction = new ReflectedControllerDescriptor(controllerType).FindAction(controller.ControllerContext, DetailActionParamsMapper.DefaultActionName); + if (detailsAction != null) + { + var contentParam = detailsAction.GetParameters().FirstOrDefault(); + if (contentParam != null && contentParam.ParameterType.ImplementsInterface(typeof(IDataItem))) + { + if (typeof(DynamicContent) == contentParam.ParameterType) + { + var controllerName = this.GetControllerName(controller); + var dynamicContentType = controller.GetDynamicContentType(controllerName); + contentType = dynamicContentType != null ? TypeResolutionService.ResolveType(dynamicContentType.GetFullTypeName(), throwOnError: false) : null; + } + else + { + contentType = contentParam.ParameterType; + } + } + } + + return contentType; + } + + private string GetControllerName(ControllerBase controller) + { + var widgetName = (string)controller.ViewBag.WidgetName; + + if (!string.IsNullOrEmpty(widgetName)) + { + return widgetName; + } + + var controllerName = controller.GetType().Name.Replace("Controller", ""); + return controllerName; + } + + /// + /// This method returns the requested item status based on content location url parameters. + /// + /// Copied from IContentLocatableView in Sitefinity. Should use it instead when it goes public. + /// Requested item status. + private ContentLifecycleStatus ResolveRequestedItemStatus() + { + var itemStatusParam = SystemManager.CurrentHttpContext.Request.ParamsGet("sf-lc-status") ?? SystemManager.CurrentHttpContext.Items["sf-lc-status"]; + ContentLifecycleStatus status = ContentLifecycleStatus.Live; + if (itemStatusParam != null) + { + if (!Enum.TryParse(itemStatusParam as string, out status)) + status = ContentLifecycleStatus.Live; + } + + return status; + } + + /// + /// Determines whether preview of the item is requested. + /// + /// Copied from IContentLocatableView in Sitefinity. Should use it instead when it goes public. + /// Whether preview is requested. + private bool IsPreviewRequested() + { + var actionParam = SystemManager.CurrentHttpContext.Request.ParamsGet("sf-content-action"); + bool isPreview = actionParam != null && actionParam == "preview"; + return isPreview; + } + + /// + /// Resolves the manager. + /// + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + private IManager ResolveManager(Type itemType, string providerName) + { + IManager manager; + + try + { + ManagerBase.TryGetMappedManager(itemType, providerName, out manager); + } + catch (Exception ex) + { + Log.Write(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Exception occurred in the routing functionality, details: {0}", ex)); + manager = null; + } + + return manager; + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + private IEnumerable GetProviderNames(ControllerBase controller, Type contentType) + { + var providerNameProperty = controller.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).FirstOrDefault(p => p.Name == "ProviderName" && p.PropertyType == typeof(string)); + + if (providerNameProperty != null) + { + return new string[1] { providerNameProperty.GetValue(controller, null) as string }; + } + else + { + IManager manager; + + try + { + ManagerBase.TryGetMappedManager(contentType, string.Empty, out manager); + } + catch (Exception ex) + { + Log.Write(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Exception occurred in the routing functionality, details: {0}", ex)); + manager = null; + } + + if (manager != null) + { + IList providers = manager.GetContextProviders().Select(p => p.Name).ToList(); + + if (!providers.Contains(manager.Provider.Name)) + providers.Add(manager.Provider.Name); + + return providers; + } + else + { + return new string[0]; + } + } + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/ControllerHelper.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ControllerHelper.cs new file mode 100644 index 000000000..09880e752 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ControllerHelper.cs @@ -0,0 +1,277 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Web; +using System.Web.Mvc; +using System.Web.Routing; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Mvc.Proxy; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Security.Claims; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Helpers +{ + /// + /// This class contains helpers for working with controller related operations. + /// + public static class ControllerHelper + { + /// + /// Load controller model + /// + /// The widget id + /// The culture + /// Controller model + public static object LoadControllerModel(Guid widgetId, CultureInfo culture) + { + return LoadControllerModel(widgetId, culture, new Guid()); + } + + /// + /// Load controller model + /// + /// The widget id + /// The culture + /// The page id + /// Controller model + public static object LoadControllerModel(Guid widgetId, CultureInfo culture, Guid pageId) + { + if (widgetId == null || widgetId == Guid.Empty) + { + return null; + } + + var pageManager = PageManager.GetManager(); + ObjectData objectData = null; + + if (pageId != Guid.Empty) + { + objectData = GetOverridingControlForPage(widgetId, pageId); + } + + if (objectData == null) + { + objectData = pageManager.GetControls().SingleOrDefault(p => p.Id == widgetId); + } + + if (objectData is PageDraftControl && ClaimsManager.IsBackendUser() == false) + { + return null; + } + + object model = null; + + if (objectData != null) + { + var mvcProxy = pageManager.LoadControl(objectData, culture) as MvcControllerProxy; + if (mvcProxy != null) + { + var controller = mvcProxy.Controller; + var controllerType = controller.GetType(); + var modelProperty = controllerType.GetProperty(Model); + if (modelProperty != null) + { + model = modelProperty.GetValue(controller); + } + } + } + + return model; + } + + /// + /// Get controller widget id + /// + /// Widget Id + public static Guid GetWidgetId(Controller controller) + { + if (controller == null) + { + throw new ArgumentNullException("controller"); + } + + var pageManager = PageManager.GetManager(); + var viewBagControlId = controller.ViewData[ControllerKey]; + if (viewBagControlId == null) + return Guid.Empty; + + var widgetId = Guid.Empty; + string controlId = (string)viewBagControlId; + + // templates + if (controller.HttpContext.Items[IsTemplate] != null && (bool)controller.HttpContext.Items[IsTemplate] == true) + { + widgetId = GetTemplateWidgetId(pageManager, controller, controlId); + } + else + { + widgetId = GetPageWidgetId(pageManager, controlId); + } + + return widgetId; + } + + private static Guid GetTemplateWidgetId(PageManager pageManager, Controller controller, string controlId) + { + // check if action is after save or cancel in template + if (controller.HttpContext.Items[FormControlId] != null) + return (Guid)controller.HttpContext.Items[FormControlId]; + + var templateId = GetTemplateIdKey(controller.ControllerContext.HttpContext); + var versionId = GetVersionNumberKey(controller.ControllerContext.HttpContext); + + if (templateId != null && versionId != null) + { + var template = pageManager.GetTemplate(new Guid(templateId)); + if (template != null) + { + var versionManager = Telerik.Sitefinity.Versioning.VersionManager.GetManager(); + TemplateDraft draft = new TemplateDraft(); + versionManager.GetSpecificVersionByChangeId(draft, new Guid(versionId)); + + var control = GetControl(draft.Controls, controlId); + if (control != null) + return control.OriginalControlId; + } + } + + // check if loaded in template + var templateData = controller.HttpContext.Items[TemplateDraftProxy] as TemplateDraftProxy; + if (templateData != null) + { + var template = pageManager.GetTemplate(templateData.ParentItemId); + if (template != null) + { + if (SystemManager.IsDesignMode || SystemManager.IsPreviewMode) + { + var control = GetControl(template.Drafts.FirstOrDefault(p => p.IsTempDraft).Controls, controlId); + if (control != null) + return control.Id; + } + else + { + var control = GetControl(template.Controls, controlId); + if (control != null) + return control.Id; + } + } + } + + return Guid.Empty; + } + + private static Guid GetPageWidgetId(PageManager pageManager, string controlId) + { + // pages + var pageId = SiteMapBase.GetCurrentNode().PageId; + var page = pageManager.GetPageData(pageId); + + if (page.Template != null) + { + var templateControl = GetControl(page.Template.Controls, controlId); + if (templateControl != null) + return templateControl.Id; + } + + if (SystemManager.IsDesignMode || SystemManager.IsPreviewMode) + { + var pageDraft = page.Drafts.FirstOrDefault(p => p.IsTempDraft); + + // Draft, if page is created page template is null, only draft is available + if (page.Template == null && pageDraft.TemplateId != Guid.Empty) + { + var template = pageManager.GetTemplate(pageDraft.TemplateId); + if (template != null) + { + var templateControl = GetControl(template.Controls, controlId); + if (templateControl != null) + return templateControl.Id; + } + } + + var control = GetControl(pageDraft.Controls, controlId); + if (control != null) + return control.Id; + } + else + { + var control = GetControl(page.Controls, controlId); + if (control != null) + return control.Id; + } + + return Guid.Empty; + } + + private static ControlData GetOverridingControlForPage(Guid controlId, Guid pageId) + { + var pageManager = PageManager.GetManager(); + ControlData overridingControl = pageManager.GetControls().Where(c => c.Page.Id == pageId && (c.Id == controlId || c.BaseControlId == controlId)).FirstOrDefault(); + + if (overridingControl == null) + overridingControl = pageManager.GetControls().Where(c => c.Page.Id == pageId && (c.Id == controlId || c.BaseControlId == controlId)).FirstOrDefault(); + + if (overridingControl == null) + { + var pageDraft = pageManager.GetDrafts().Where(a => a.Id == pageId).FirstOrDefault(); + if (pageDraft != null) + { + var iter = pageManager.GetTemplates().Where(c => c.Id == pageDraft.TemplateId).FirstOrDefault(); + + while (iter != null) + { + overridingControl = pageManager.GetControls().Where(c => c.Page.Id == iter.Id && (c.Id == controlId || c.BaseControlId == controlId)).FirstOrDefault(); + if (overridingControl != null) + break; + iter = iter.ParentTemplate; + } + } + } + + return overridingControl; + } + + private static ControlData GetControl(IEnumerable controls, string controlId) + { + return controls.FirstOrDefault(p => p.Properties.FirstOrDefault(t => t.Name == IDParameter && controlId.EndsWith(t.Value)) != null); + } + + private static string GetTemplateIdKey(HttpContextBase context) + { + var requestContext = context.Items[RouteHandler.RequestContextKey] as RequestContext ?? context.Request.RequestContext; + if (requestContext.RouteData.Values.ContainsKey(ItemId)) + { + return requestContext.RouteData.Values[ItemId] as string; + } + else + { + return null; + } + } + + private static string GetVersionNumberKey(HttpContextBase context) + { + var requestContext = context.Items[RouteHandler.RequestContextKey] as RequestContext ?? context.Request.RequestContext; + if (requestContext.RouteData.Values.ContainsKey(VersionNumber)) + { + return requestContext.RouteData.Values[VersionNumber] as string; + } + else + { + return null; + } + } + + private const string TemplateDraftProxy = "TemplateDraftProxy"; + private const string IsTemplate = "IsTemplate"; + private const string FormControlId = "FormControlId"; + private const string ControllerKey = "sf_cntrl_id"; + private const string VersionNumber = "VersionNumber"; + private const string ItemId = "itemId"; + private const string IDParameter = "ID"; + private const string Model = "Model"; + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/CustomFieldsHelpers.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/CustomFieldsHelpers.cs new file mode 100644 index 000000000..6026587cd --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/CustomFieldsHelpers.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Web.Mvc; +using System.Web.Script.Serialization; +using Telerik.Sitefinity.Frontend.Mvc.Helpers.ViewModels; +using Telerik.Sitefinity.Taxonomies; +using Telerik.Sitefinity.Taxonomies.Model; + +namespace Telerik.Sitefinity.Frontend.Mvc.Helpers +{ + /// + /// This class contains helpers for working with custom fields. + /// + public static class CustomFieldsHelpers + { + /// + /// Gets the custom taxonomy fields. + /// + /// Type of the content. + /// + public static string GetTaxonomyFields(Type contentType) + { + var properties = OrganizerBase.GetPropertiesForType(contentType); + var taxonomyViewModelProperties = properties.Select(p => new CustomTaxonomyViewModel() + { + Id = p.TaxonomyId, + Name = p.Name, + TaxonomyType = p.TaxonomyType, + Title = CustomFieldsHelpers.GetClassificationPluralTitle(p.TaxonomyId, string.Empty) + }); + + var serialzier = new JavaScriptSerializer(); + var serialziedProperties = serialzier.Serialize(taxonomyViewModelProperties); + + return serialziedProperties; + } + + /// + /// Gets the classification plural title. + /// + /// The taxa identifier. + /// Name of the provider. + /// + public static string GetClassificationPluralTitle(Guid taxaId, string providerName) + { + var taxonomyManager = TaxonomyManager.GetManager(providerName); + var taxa = taxonomyManager.GetTaxonomy(taxaId); + + return taxa.Title; + } + + /// + /// Gets the classification taxon name. + /// + /// The taxa identifier. + /// Name of the provider. + /// + public static string GetClassificationTaxonName(Guid taxaId, string providerName) + { + var taxonomyManager = TaxonomyManager.GetManager(providerName); + var taxa = taxonomyManager.GetTaxonomy(taxaId); + + return taxa.TaxonName; + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/HtmlHelperExtensions.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/HtmlHelperExtensions.cs index ba7193ee8..6bcf78465 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/HtmlHelperExtensions.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/HtmlHelperExtensions.cs @@ -1,106 +1,117 @@ -// It is important to keep the namespace. This way these extensions take precedence over the default System.Web.Mvc.Html.PartialExtensions. -namespace ASP -{ - using System; - using System.Globalization; - using System.IO; - using System.Text; - using System.Web.Mvc; - - /// - /// extensions methods for rendering partial views. - /// - public static class PartialExtensions - { - /// - /// Renders the partial view with the specified name. - /// - /// The HTML helper. - /// Name of the partial view. - /// Rendered partial view. - public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName) - { - return PartialExtensions.Partial(htmlHelper, partialViewName, null, htmlHelper.ViewData); - } - - /// - /// Renders the partial view with the specified name. - /// - /// The HTML helper. - /// Name of the partial view. - /// The view data. - /// - /// Rendered partial view. - /// - public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData) - { - return PartialExtensions.Partial(htmlHelper, partialViewName, null, viewData); - } - - /// - /// Renders the partial view with the specified name. - /// - /// The HTML helper. - /// Name of the partial view. - /// The model. - /// - /// Rendered partial view. - /// - public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model) - { - return PartialExtensions.Partial(htmlHelper, partialViewName, model, htmlHelper.ViewData); - } - - /// - /// Renders the partial view with the specified name. - /// - /// The HTML helper. - /// Name of the partial view. - /// The model. - /// The view data. - /// - /// Rendered partial view. - /// - public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData) - { - using (var writer = new StringWriter(CultureInfo.CurrentCulture)) - { - PartialExtensions.RenderPartial(htmlHelper, partialViewName, viewData, model, writer); - return MvcHtmlString.Create(writer.ToString()); - } - } - - private static void RenderPartial(HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData, object model, TextWriter writer) - { - ViewDataDictionary newViewData; - if (model == null) - { - newViewData = viewData == null ? new ViewDataDictionary(htmlHelper.ViewData) : new ViewDataDictionary(viewData); - } - else - { - newViewData = viewData == null ? new ViewDataDictionary(model) : new ViewDataDictionary(viewData) { Model = model }; - } - - var controller = htmlHelper.ViewContext.Controller as Controller; - var viewEngineCollection = controller != null ? controller.ViewEngineCollection : ViewEngines.Engines; - var newViewContext = new ViewContext(htmlHelper.ViewContext, htmlHelper.ViewContext.View, newViewData, htmlHelper.ViewContext.TempData, writer); - var result = viewEngineCollection.FindPartialView(newViewContext, partialViewName); - if (result.View != null) - { - result.View.Render(newViewContext, writer); - } - else - { - var locationsText = new StringBuilder(); - foreach (string location in result.SearchedLocations) - { - locationsText.AppendLine(); - locationsText.Append(location); - } - - throw new InvalidOperationException("The partial view '{0}' was not found or no view engine supports the searched locations. The following locations were searched: {1}".Arrange(partialViewName, locationsText)); - } - } - } +namespace Telerik.Sitefinity.Frontend.Mvc.Helpers +{ + using System.Collections.Generic; + using System.Web.Mvc; + using Sitefinity.Security.Sanitizers; + using Telerik.Sitefinity.Abstractions; + using Telerik.Sitefinity.Frontend.Mvc.Infrastructure; + using Telerik.Sitefinity.Mvc.Rendering; + using Telerik.Sitefinity.Security.CSRF; + using Telerik.Sitefinity.Services; + using Telerik.Sitefinity.Utilities.TypeConverters; + using Telerik.Sitefinity.Web.UI; + + /// + /// Helper method for HTML markup generation. + /// + public static class HtmlHelperExtensions + { + /// + /// Gets a unique element id with the given prefix. + /// + /// The HTML helper. + /// The prefix of the identifier. + /// Unique Id for an HTML element. + public static MvcHtmlString UniqueId(this HtmlHelper htmlHelper, string prefix) + { + if (!htmlHelper.ViewData.ContainsKey(HtmlHelperExtensions.ElementIdsKey)) + { + htmlHelper.ViewData.Add(HtmlHelperExtensions.ElementIdsKey, new Dictionary()); + } + + var keysDictionary = (IDictionary)htmlHelper.ViewData[HtmlHelperExtensions.ElementIdsKey]; + if (!keysDictionary.ContainsKey(prefix)) + { + if (!SystemManager.CurrentHttpContext.Items.Contains(HtmlHelperExtensions.IdCountersKey)) + { + SystemManager.CurrentHttpContext.Items[HtmlHelperExtensions.IdCountersKey] = new Dictionary(); + } + + var counters = (IDictionary)SystemManager.CurrentHttpContext.Items[HtmlHelperExtensions.IdCountersKey]; + if (!counters.ContainsKey(prefix)) + { + counters[prefix] = 0; + } + + var counter = counters[prefix] + 1; + counters[prefix] = counter; + keysDictionary[prefix] = prefix + "-" + counter.ToString(); + } + + var uniqueId = keysDictionary[prefix]; + return MvcHtmlString.Create(uniqueId); + } + + /// + /// Sanitizes html string using the registered . This method should be used when you want to handle text that is supposed to be HTML, but comes from untrusted source. + /// + /// The HTML helper which this method is extending. + /// The HTML string to be sanitized. + /// + public static MvcHtmlString HtmlSanitize(this HtmlHelper htmlHelper, string html) + { + var sanitizedHtml = ControlUtilities.Sanitize(html); + + return MvcHtmlString.Create(sanitizedHtml); + } + + /// + /// Sanitizes url string using the registered . It will also attribute encode the string. + /// + /// The HTML helper which this method is extending. + /// The url string to be sanitized. + /// + public static MvcHtmlString UrlSanitize(this HtmlHelper htmlHelper, string url) + { + var sanitizedUrl = ControlUtilities.SanitizeUrl(url); + + return MvcHtmlString.Create(sanitizedUrl); + } + + /// + /// Adds an antiforgery markup and scripts to the view. + /// + /// The HTML helper which this method is extending. + /// The path to the token retrieval script. + /// + public static MvcHtmlString AddSitefinityAntiforgeryToken(this HtmlHelper htmlHelper, string retrievalScriptPath = null) + { + var antiForgery = ObjectFactory.IsTypeRegistered() ? ObjectFactory.Resolve() : null; + var antiForgeryEnabled = antiForgery != null && antiForgery.Enabled; + if (antiForgeryEnabled) + { + if (retrievalScriptPath == null) + { + var page = htmlHelper.ViewContext.HttpContext.Handler.GetPageHandler() ?? new PageProxy(null); + retrievalScriptPath = page.ClientScript.GetWebResourceUrl(TypeResolutionService.ResolveType("Telerik.Sitefinity.WebSecurity.WebSecurityModule"), + "Telerik.Sitefinity.WebSecurity.CSRF.TokenRetrieval.js"); + } + + htmlHelper.Script(retrievalScriptPath, "bottom", false); + var result = + $@" + +"; + + return MvcHtmlString.Create(result); + } + else + { + return MvcHtmlString.Empty; + } + } + + private const string ElementIdsKey = "sf-element-ids"; + private const string IdCountersKey = "sf-element-id-counters"; + } } \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/HyperLinkHelpers.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/HyperLinkHelpers.cs new file mode 100644 index 000000000..f715d3919 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/HyperLinkHelpers.cs @@ -0,0 +1,269 @@ +using System; +using System.Web; +using System.Linq; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Data.Linq.Dynamic; +using Telerik.Sitefinity.Frontend.Mvc.Models; +using Telerik.Sitefinity.Model; +using Telerik.Sitefinity.Modules.Libraries; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Multisite; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Taxonomies.Model; +using Telerik.Sitefinity.Web; +using Telerik.Sitefinity.Web.DataResolving; +using Telerik.Sitefinity.Web.UrlEvaluation; +using System.Runtime.CompilerServices; +using ServiceStack; + +namespace Telerik.Sitefinity.Frontend.Mvc.Helpers +{ + /// + /// Helper class that provides utility methods for resolving urls to a content pages. + /// + public static class HyperLinkHelpers + { + /// + /// Returns an absolute URL to a content item's details page. + /// + /// The item. + /// The details page id. + /// The absolute url of the details page. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")] + public static string GetDetailPageUrl(IDataItem item, Guid detailsPageId) + { + string url = DataResolver.Resolve(item, "URL", null, detailsPageId.ToString()); + return UrlPath.ResolveUrl(url, true); + } + + /// + /// Gets the detail page URL for master/detail widgets. + /// + /// The item. + /// The details page identifier. + /// if set to true [open in same page]. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")] + public static string GetDetailPageUrl(ItemViewModel item, Guid detailsPageId, bool openInSamePage) + { + string url; + if (openInSamePage) + { + var appRelativeUrl = DataResolver.Resolve(item.DataItem, "URL"); + url = UrlPath.ResolveUrl(appRelativeUrl, true); + } + else + { + url = HyperLinkHelpers.GetDetailPageUrl(item.DataItem, detailsPageId); + } + + return url; + } + + /// + /// Gets the detail page URL for master/detail widgets. + /// + /// The item. + /// The details page identifier. + /// if set to true [open in same page]. + /// Index of the item in collection. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")] + public static string GetDetailPageUrl(ItemViewModel item, Guid detailsPageId, bool openInSamePage, int itemIndex) + { + string url; + if (openInSamePage) + { + var appRelativeUrl = DataResolver.Resolve(item.DataItem, "URL"); + appRelativeUrl = appRelativeUrl + "?itemIndex=" + itemIndex; + url = UrlPath.ResolveUrl(appRelativeUrl, true); + } + else + { + url = HyperLinkHelpers.GetDetailPageUrl(item.DataItem, detailsPageId) + "?itemIndex=" + itemIndex; + } + + return url; + } + + /// + /// Gets the full detail page URL for master/detail widgets. + /// + /// The item. + /// The details page identifier. + /// if set to true [open in same page]. + /// The URL key prefix. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")] + public static string GetDetailPageUrl(ItemViewModel item, Guid detailsPageId, bool openInSamePage, string urlKeyPrefix) + { + string url; + if (openInSamePage) + { + url = DataResolver.Resolve(item.DataItem, "URL", urlKeyPrefix); + } + else + { + url = DataResolver.Resolve(item.DataItem, "URL", null, detailsPageId.ToString()); + } + + url = RemoveDoubleSlash(url); + + return UrlPath.ResolveUrl(url, true); + } + + /// + /// Gets the full detail page URL for master/detail widgets. + /// + /// The item. + /// The details page identifier. + /// if set to true [open in same page]. + /// The URL key prefix. + /// Index of the item. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")] + public static string GetDetailPageUrl(ItemViewModel item, Guid detailsPageId, bool openInSamePage, string urlKeyPrefix, int itemIndex) + { + string url; + if (openInSamePage) + { + url = DataResolver.Resolve(item.DataItem, "URL", urlKeyPrefix); + } + else + { + url = DataResolver.Resolve(item.DataItem, "URL", null, detailsPageId.ToString()); + } + + url = url + "?itemIndex=" + itemIndex; + url = RemoveDoubleSlash(url); + + return UrlPath.ResolveUrl(url, true); + } + + /// + /// Gets the full page URL. + /// + /// The page identifier. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")] + public static string GetFullPageUrl(Guid pageId) + { + if (pageId != Guid.Empty) + { + var siteMap = SitefinitySiteMap.GetCurrentProvider(); + + SiteMapNode node; + var sitefinitySiteMap = siteMap as SiteMapBase; + if (sitefinitySiteMap != null) + { + node = sitefinitySiteMap.FindSiteMapNodeFromKey(pageId.ToString(), false); + } + else + { + node = siteMap.FindSiteMapNodeFromKey(pageId.ToString()); + } + + if (node != null) + { + return UrlPath.ResolveUrl(node.Url, true); + } + else + { + // try to redirect to a page from a different site + var redirectPageNode = PageManager.GetManager().GetPageNode(pageId); + if (SystemManager.CurrentContext.CurrentSite.SiteMapRootNodeId != redirectPageNode.RootNodeId) + { + using (SiteRegion.FromSiteMapRoot(redirectPageNode.RootNodeId, SiteContextResolutionTypes.ByParam)) + { + if (sitefinitySiteMap != null) + { + node = sitefinitySiteMap.FindSiteMapNodeFromKey(pageId.ToString(), false); + } + else + { + node = siteMap.FindSiteMapNodeFromKey(pageId.ToString()); + } + + if (node != null) + { + return UrlPath.ResolveUrl(node.Url, true); + } + } + } + } + } + + return null; + } + + /// + /// Builds the query string parameters for filtering by taxon. + /// + /// The taxon. + /// The URL key prefix. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#")] + public static string BuildTaxonQueryStringParams(ITaxon taxon, string urlKeyPrefix) + { + var evaluator = new TaxonomyEvaluator(); + var taxonBuildOptions = TaxonBuildOptions.None; + string taxonRelativeUrl = null; + + if (taxon.Taxonomy is HierarchicalTaxonomy) + { + taxonBuildOptions = TaxonBuildOptions.Hierarchical; + taxonRelativeUrl = (taxon as HierarchicalTaxon).FullUrl; + } + else if (taxon.Taxonomy is FlatTaxonomy) + { + taxonBuildOptions = TaxonBuildOptions.Flat; + taxonRelativeUrl = taxon.UrlName.Value; + } + + var taxonQueryStringParams = evaluator.BuildUrl(taxon.Taxonomy.Name, taxonRelativeUrl, taxon.Taxonomy.Name, taxonBuildOptions, UrlEvaluationMode.QueryString, urlKeyPrefix); + return taxonQueryStringParams; + } + + /// + /// Retrieves the thumbnail url for the video + /// + /// The librarires manager + /// The video id + /// + public static string GetVideoThumbnailUrl(LibrariesManager librariesManager, Guid videoId) + { + try + { + var video = librariesManager.GetVideo(videoId); + + return video.ResolveThumbnailUrl(); + } + catch (UnauthorizedAccessException ex) + { + Exceptions.HandleException(ex, ExceptionPolicyName.IgnoreExceptions); + + return string.Empty; + } + } + + private static string RemoveDoubleSlash(string url) + { + // If the url is absolute we should not replace first // with /. Ex: http://domain... + Uri result = null; + if (Uri.TryCreate(url, UriKind.Absolute, out result)) + { + UriBuilder builder = new UriBuilder(url); + builder.Path = builder.Path.Replace("//", "/"); + + url = builder.Uri.ToString(); + } + else + { + url = url.Replace("//", "/"); + } + + return url; + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/InlineEditingHtmlHelpers.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/InlineEditingHtmlHelpers.cs index e1acfb57f..73aace273 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/InlineEditingHtmlHelpers.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/InlineEditingHtmlHelpers.cs @@ -1,6 +1,12 @@ using System; +using System.Web; using System.Web.Mvc; +using System.Web.UI; +using Telerik.Sitefinity.Data; using Telerik.Sitefinity.Frontend.InlineEditing; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Utilities.TypeConverters; +using Telerik.Sitefinity.Web; namespace Telerik.Sitefinity.Frontend.Mvc.Helpers { @@ -16,7 +22,7 @@ public static class InlineEditingHtmlHelpers /// The object which contains the property. /// Name of the property. /// - public static System.Web.Mvc.MvcHtmlString TextField(this HtmlHelper helper, object model, string propName) + public static IHtmlString TextField(this HtmlHelper helper, object model, string propName) { var htmlProcessor = new HtmlProcessor(); var htmlString = htmlProcessor.GetStringContent(model, propName); @@ -31,13 +37,22 @@ public static System.Web.Mvc.MvcHtmlString TextField(this HtmlHelper helper, obj /// The property value. /// Type of the field. /// Html required for enabling inline editing. - public static System.Web.Mvc.MvcHtmlString TextField(this HtmlHelper helper, string propName, string propValue, string fieldType) + public static IHtmlString TextField(this HtmlHelper helper, string propName, string propValue, string fieldType) { - var htmlString = string.Format(HtmlProcessor.InlineEditingHtmlWrapper, propName, fieldType, propValue); - + string htmlString; + + if (!SystemManager.IsInlineEditingMode) + { + htmlString = propValue; + } + else + { + htmlString = string.Format(HtmlProcessor.InlineEditingHtmlWrapper, propName, fieldType, propValue); + } + return new System.Web.Mvc.MvcHtmlString(htmlString); } - + /// /// HTML helper which adds an InlineEditing region. This should be added once at the top of the page, and the whole region will support InlineEditing. /// @@ -49,16 +64,124 @@ public static System.Web.Mvc.MvcHtmlString TextField(this HtmlHelper helper, str public static HtmlRegion InlineEditingRegion( this HtmlHelper htmlHelper, string providerName, - string type, + string type, Guid id) { var htmlProcessor = new HtmlProcessor(); - return htmlProcessor.CreateInlineEditingRegion( htmlHelper.ViewContext.Writer, - providerName, - type, + providerName, + type, id); } + + /// + /// Renders InlineEditing attributes required for the Inline editing feature. + /// + /// Name of the provider. + /// The type. + /// The identifier. + /// The inline editing attributes. + public static IHtmlString InlineEditingAttributes(this HtmlHelper htmlHelper, string providerName, string type, Guid id) + { + if (!SystemManager.IsInlineEditingMode) + return htmlHelper.Raw(string.Empty); + + if (string.IsNullOrEmpty(providerName)) + { + providerName = GetProviderName(type); + } + + var providerNameEncoded = providerName != null ? htmlHelper.Encode(providerName) : providerName; + var typeEncoded = htmlHelper.Encode(type); + + if (id == Guid.Empty) + return htmlHelper.Raw("data-sf-provider='{0}' data-sf-type='{1}'".Arrange(providerNameEncoded, typeEncoded)); + else + return htmlHelper.Raw("data-sf-provider='{0}' data-sf-type='{1}' data-sf-id='{2}'".Arrange(providerNameEncoded, typeEncoded, id.ToString("D"))); + } + + /// + /// Renders InlineEditing attributes for fields required for the Inline editing feature. + /// + /// The HTML helper. + /// Name of the field. + /// Type of the field. + /// + public static IHtmlString InlineEditingFieldAttributes(this HtmlHelper htmlHelper, string fieldName, string fieldType) + { + if (htmlHelper == null) + throw new ArgumentNullException("htmlHelper"); + + if (fieldName == null) + throw new ArgumentNullException("fieldName"); + + if (fieldType == null) + throw new ArgumentNullException("fieldType"); + + if (!SystemManager.IsInlineEditingMode) + return htmlHelper.Raw(string.Empty); + + var fieldNameEncoded = htmlHelper.Encode(fieldName); + var fieldTypeEncoded = htmlHelper.Encode(fieldType); + + return htmlHelper.Raw("data-sf-field='{0}' data-sf-ftype='{1}'".Arrange(fieldNameEncoded, fieldTypeEncoded)); + } + + /// + /// Returns if the inline editing section should be rendered. + /// + /// The HTML helper. + /// + public static bool ShouldRenderInlineEditing(this HtmlHelper htmlHelper) + { + var shouldRender = false; + + if (!SitefinityContext.IsBackend && ControlExtensions.InlineEditingIsEnabled() && !SystemManager.CurrentHttpContext.Request.IsAjaxRequest()) + { + const string SiteMapNodeKey = "ServedPageNode"; + + if (HttpContext.Current != null && HttpContext.Current.Items != null && HttpContext.Current.Items.Contains(SiteMapNodeKey)) + { + var pageSiteNode = HttpContext.Current.Items[SiteMapNodeKey] as PageSiteNode; + if (pageSiteNode != null) + { + var firstPageDataNode = RouteHelper.GetFirstPageDataNode(pageSiteNode, true); + if (firstPageDataNode != null && firstPageDataNode.Framework == Pages.Model.PageTemplateFramework.Mvc) + { + shouldRender = true; + } + } + } + } + + return shouldRender; + } + + private static string GetProviderName(string type) + { + string providerName = null; + + if (type != null) + { + var itemType = TypeResolutionService.ResolveType(type); + if (itemType != null) + { + Type managerType; + ManagerBase.TryGetMappedManagerType(itemType, out managerType); + if (managerType != null) + { + var currentSite = SystemManager.CurrentContext.CurrentSite; + var provider = currentSite.GetDefaultProvider(managerType.FullName); + if (provider != null) + { + providerName = provider.ProviderName; + } + } + } + } + + return providerName; + } } } \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/LayoutsHelpers.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/LayoutsHelpers.cs index 56d9b31dc..cf8cd2dd9 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/LayoutsHelpers.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/LayoutsHelpers.cs @@ -1,5 +1,8 @@ using System; using System.Web.Mvc; +using System.Web.UI; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts; namespace Telerik.Sitefinity.Frontend.Mvc.Helpers { @@ -14,11 +17,53 @@ public static class LayoutsHelpers /// The helper. /// Name of the container. /// - public static MvcHtmlString SfPlaceHolder(this HtmlHelper helper, string containerName = "Body") + public static System.Web.Mvc.MvcHtmlString SfPlaceHolder(this HtmlHelper helper, string containerName = LayoutsHelpers.PlaceHolderDefaultName) { - var htmlString = string.Format(System.Globalization.CultureInfo.InvariantCulture, "
", containerName); + var htmlString = LayoutsHelpers.ContentPlaceHolderMarkup(containerName); - return new MvcHtmlString(htmlString); + return new System.Web.Mvc.MvcHtmlString(htmlString); } + + /// + /// Html helper which renders all script tags. + /// + /// The helper. + /// The name of the section. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "helper")] + public static System.Web.Mvc.MvcHtmlString Section(this HtmlHelper helper, string name) + { + if (helper.ViewContext.HttpContext != null) + { + SectionRenderer.MarkAvailability(helper.ViewContext.HttpContext.Handler.GetPageHandler(), name); + } + + return new System.Web.Mvc.MvcHtmlString(LayoutsHelpers.SectionHtml.Arrange(name)); + } + + /// + /// Gets the ASPX markup of a content place holder. + /// + /// Name of the place holder. + /// + internal static string ContentPlaceHolderMarkup(string placeHolderName = LayoutsHelpers.PlaceHolderDefaultName) + { + return string.Format(System.Globalization.CultureInfo.InvariantCulture, "", placeHolderName); + } + + /// + /// The section tag name. + /// + internal const string SectionTag = "FeatherSection"; + + /// + /// The section HTML markup. + /// + internal const string SectionHtml = "<" + LayoutsHelpers.SectionTag + " name=\"{0}\">"; + + /// + /// The content place holder default name. + /// + private const string PlaceHolderDefaultName = "Body"; } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/LocalizationHelpers.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/LocalizationHelpers.cs index 81a52a6a1..4d01f43c1 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/LocalizationHelpers.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/LocalizationHelpers.cs @@ -23,6 +23,24 @@ public static string Resource(this HtmlHelper helper, string key, bool fallbackT return LocalizationHelpers.Resource(controller, helper.ViewContext.RouteData, key, fallbackToKey); } + /// + /// Get the resource string with the specified key from the resource files. + /// + /// The helper. + /// The key + /// The class to search in + public static string Resource(this HtmlHelper helper, string key, string className) + { + string result; + + if (Res.TryGet(className, key, out result)) + { + return result; + } + + return "#ResourceNotFound: {0}, {1}#".Arrange(className, key); + } + /// /// Get the label with the specified key from the resource files. /// @@ -45,7 +63,7 @@ public static string Label(this ViewPage page, string key) var controller = LocalizationHelpers.GetController(page); var resClass = LocalizationHelpers.FindResourceStringClassType(controller.GetType()); return Res.Get(resClass, key, System.Globalization.CultureInfo.InvariantCulture); - } + } /// /// Get the label with the specified key from the resource files. @@ -65,7 +83,7 @@ private static string Resource(ControllerBase controller, RouteData routeData, s { var widgetResClass = LocalizationHelpers.FindResourceStringClassType(widget); string res; - if (widgetResClass != null && Res.TryGet(widgetResClass.Name, key, out res)) + if (widgetResClass != null && Res.TryGet(widgetResClass.Name, key, null, out res)) { return res; } @@ -73,7 +91,7 @@ private static string Resource(ControllerBase controller, RouteData routeData, s } string result; - if (Res.TryGet(resClass.Name, key, out result)) + if (Res.TryGet(resClass.Name, key, null, out result)) { return result; } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/NewslettersHelper.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/NewslettersHelper.cs new file mode 100644 index 000000000..8947cb693 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/NewslettersHelper.cs @@ -0,0 +1,47 @@ +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.Modules.Newsletters; +using Telerik.Sitefinity.Modules.Newsletters.Configuration; +using Telerik.Sitefinity.Modules.Newsletters.Web; +using Telerik.Sitefinity.Newsletters.Model; +using Telerik.Sitefinity.Services; + +namespace Telerik.Sitefinity.Frontend.Mvc.Helpers +{ + /// + /// Helper methods for email campaigns. + /// + public static class NewslettersHelper + { + /// + /// Indicates whether the current request is for newsletter. + /// + /// True if the current request is for newsletter. + public static bool IsNewsletter() + { + var httpContext = SystemManager.CurrentHttpContext; + + var newsLetterItem = httpContext.Items.Contains(NewslettersModule.IsNewsletter) ? (bool)httpContext.Items[NewslettersModule.IsNewsletter] : false; + + var isNewsletter = newsLetterItem + || (httpContext.Request.UrlReferrer != null && httpContext.Request.UrlReferrer.AbsolutePath.ToLower().Contains("/sitefinity/sfnwslttrs/")) + || (httpContext.Request.Url != null && httpContext.Request.Url.AbsolutePath.ToLower().Contains("/sitefinity/sfnwslttrs/")); + + return isNewsletter; + } + + /// + /// Indicates whether the current request is for pure mvc newsletter. + /// + /// True if the current request is for mvc newsletter. + internal static bool IsMvcNewsletter() + { + var currentHttpContext = SystemManager.CurrentHttpContext; + + return SystemManager.GetApplicationModule(NewslettersModule.ModuleName) != null + && !Config.Get().AllowHybridWidgets + && currentHttpContext != null + && currentHttpContext.Items.Contains(NewslettersRouteHandler.NewslettersMessageBodyType) + && (MessageBodyType)currentHttpContext.Items[NewslettersRouteHandler.NewslettersMessageBodyType] == MessageBodyType.InternalMvcPage; + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/PagingHelpers.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/PagingHelpers.cs new file mode 100644 index 000000000..89f2ccfd9 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/PagingHelpers.cs @@ -0,0 +1,72 @@ +using System; +using System.Web; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Helpers +{ + /// + /// Helper methods for widget paging. + /// + public static class PagingHelpers + { + /// + /// Generate url template that suports paging. + /// + /// Target controller. + /// Base url for paging. + /// Query parameter sufix. + /// Url suffix. + public static string GeneratePagingTemplate(this ContentBaseController controller, string pageUrl, string urlKeyPrefix) + { + if (urlKeyPrefix.IsNullOrWhitespace()) + { + return string.Concat(pageUrl, UrlHelpers.GetRedirectPagingUrl(), SystemManager.CurrentHttpContext.Request.QueryString.ToQueryString(true)); + } + + var key = string.Format(KeyFormat, urlKeyPrefix); + var queryParams = HttpUtility.ParseQueryString(SystemManager.CurrentHttpContext.Request.Url.Query); + queryParams[key] = "{0}"; + + var queryParamsRaw = HttpUtility.UrlDecode(queryParams.ToQueryString(true)); + return string.Concat(SystemManager.CurrentHttpContext.Request.Url.LocalPath, queryParamsRaw); + } + + /// + /// Check query params and update page if applicable. + /// + /// Target controller. + /// The page. + /// Prefix of page query parameter. + public static void UpdatePageFromQuery(this ContentBaseController controller, ref int? page, string urlKeyPrefix) + { + if (urlKeyPrefix.IsNullOrWhitespace()) return; + + var key = string.Format(KeyFormat, urlKeyPrefix); + var pageString = SystemManager.CurrentHttpContext.Request.QueryStringGet(key); + + int queryPage; + if (!int.TryParse(pageString, out queryPage)) + { + queryPage = 1; + } + page = queryPage; + } + + /// + /// Extract a valid page number. + /// + /// Target controller. + /// Nullable page number. + /// One (1) if page is null or less than one, otherwise page value. + public static int ExtractValidPage(this ContentBaseController controller, int? page) + { + if (!page.HasValue || page.Value < 1) return 1; + + return page.Value; + } + + private const string KeyFormat = "{0}page"; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/ResourceHelper.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ResourceHelper.cs index c5f859abc..8008231e8 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/ResourceHelper.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ResourceHelper.cs @@ -1,191 +1,979 @@ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Reflection; -using System.Text; -using System.Web; -using System.Web.Mvc; -using System.Web.UI; -using Telerik.Sitefinity.Configuration; -using Telerik.Sitefinity.Frontend.Resources; -using Telerik.Sitefinity.Modules.Pages; -using Telerik.Sitefinity.Modules.Pages.Configuration; -using Telerik.Sitefinity.Utilities.TypeConverters; -using Telerik.Sitefinity.Web.Configuration; - -namespace Telerik.Sitefinity.Frontend.Mvc.Helpers -{ - /// - /// This class contains helper methods for registering client resources. - /// - public static class ResourceHelper - { - /// - /// Registers JavaScript reference and ensures that it loads maximum once for a page. - /// - /// - /// This method uses directly the resource from the . - /// In case you want to use embedded scripts from Sitefinity check . - /// - /// The path to the JavaScript file. - /// OPTIONAL: Indicates whether to throw an exception if the JavaScript is already registered. By default the value is set to false. - /// MvcHtmlString - public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath, bool throwException = false) - { - var context = helper.ViewContext.HttpContext; - - return ResourceHelper.RegisterResource(context, scriptPath, scriptPath, throwException); - } - - /// - /// Registers JavaScript reference and ensures that it loads maximum once for a page. - /// - /// - /// This helper references the same resource existing in Sitefinity. - /// - /// The helper. - /// The script reference. - /// if set to true throw exception. - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] - public static MvcHtmlString Script(this HtmlHelper helper, ScriptRef scriptReference, bool throwException = false) - { - if (ResourceHelper.TryConfigureScriptManager(scriptReference)) - return MvcHtmlString.Empty; - - var resourceKey = scriptReference.ToString(); - var context = helper.ViewContext.HttpContext; - var resourceUrl = ResourceHelper.GetWebResourceUrl(scriptReference); - - if (string.IsNullOrEmpty(resourceUrl)) - throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Script reference for {0} is not found.", resourceKey)); - - return ResourceHelper.RegisterResource(context, resourceKey, resourceUrl, throwException); - } - - /// - /// Tries the configure script manager. - /// - /// The script reference. - /// - private static bool TryConfigureScriptManager(ScriptRef scriptReference) - { - var page = HttpContext.Current.Handler as Page; - ScriptManager scriptManager = null; - - if (page != null) - { - scriptManager = PageManager.ConfigureScriptManager(page, scriptReference, false); - } - - if (scriptManager == null) - return false; - else - return true; - } - - /// - /// Gets the web resource URL. - /// - /// The script reference. - /// - private static string GetWebResourceUrl(ScriptRef scriptReference) - { - var config = Config.Get().ScriptManager; - var scriptConfig = config.ScriptReferences[scriptReference.ToString()]; - string resourceUrl = string.Empty; - - if (config.EnableCdn || (scriptConfig.EnableCdn.HasValue && scriptConfig.EnableCdn.Value)) - { - resourceUrl = scriptConfig.Path; - } - else - { - var page = HttpContext.Current.Handler as Page; - - if (page != null) - { - resourceUrl = page.ClientScript.GetWebResourceUrl( - TypeResolutionService.ResolveType("Telerik.Sitefinity.Resources.Reference"), - scriptConfig.Name); - } - } - - return resourceUrl; - } - - /// - /// Registers the resource. - /// - /// The context. - /// The script key. - /// The script path. - /// if set to true throws exception. - /// - private static MvcHtmlString RegisterResource(HttpContextBase context, string scriptKey, string scriptPath, bool throwException) - { - var attributes = new KeyValuePair[2]; - attributes[0] = new KeyValuePair("src", scriptPath); - attributes[1] = new KeyValuePair("type", "text/javascript"); - - var register = new ResourceRegister(ResourceHelper.JsRegisterName, context); - - return ResourceHelper.RegisterResource(register, scriptKey, throwException, tagName: "script", attribbutes: attributes); - } - - /// - /// Registers resource reference. - /// - /// The register. - /// The resource key. - /// if set to true [throw exception]. - /// Name of the tag. - /// The attribbutes. - /// - private static MvcHtmlString RegisterResource(ResourceRegister register, string resourceKey, bool throwException, string tagName, KeyValuePair[] attribbutes) - { - string output; - MvcHtmlString result; - - if (throwException) - { - register.RegisterResource(resourceKey); - output = ResourceHelper.GenerateTag(tagName, attribbutes); - result = new MvcHtmlString(output); - } - else if (register.TryRegisterResource(resourceKey)) - { - output = ResourceHelper.GenerateTag(tagName, attribbutes); - result = new MvcHtmlString(output); - } - else - { - result = MvcHtmlString.Empty; - } - - return result; - } - - /// - /// Creates a string representation of a tag. - /// - /// The type of the HTML tag that would be generated for every registered resource. - /// The attributes associated with the tag. - /// The string representation of a tag. - private static string GenerateTag(string tagName, params KeyValuePair[] attribbutes) - { - var tag = new TagBuilder(tagName); - - if (attribbutes != null) - { - foreach (var attr in attribbutes) - tag.Attributes[attr.Key] = attr.Value; - } - - return tag.ToString(); - } - - private const string JsRegisterName = "JsRegister"; - } +using System; +using System.Globalization; +using System.Linq; +using System.Text; +using System.Web; +using System.Web.Configuration; +using System.Web.Mvc; +using System.Web.UI; +using System.Collections.Generic; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Abstractions.VirtualPath; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts; +using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Modules.Pages.Configuration; +using Telerik.Sitefinity.Mvc.Rendering; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Utilities.TypeConverters; + +namespace Telerik.Sitefinity.Frontend.Mvc.Helpers +{ + /// + /// This class contains helper methods for registering client resources. + /// + public static class ResourceHelper + { + /// + /// Gets a value indicating whether section name of the scripts should be rendered. + /// This value is used client side for placing scripts tag within personalized widgets. + /// + /// + /// true if section name of the scripts should be rendered; otherwise, false. + /// + internal static bool RenderScriptSection + { + get + { + return SystemManager.CurrentHttpContext != null && + SystemManager.CurrentHttpContext.Items.Contains("RenderScriptSection") && + (bool)SystemManager.CurrentHttpContext.Items["RenderScriptSection"]; + } + } + + /// + /// Gets a value indicating whether the site is in debug mode acording to the web.config + /// + /// + /// true if the site is in debug mode; otherwise, false. + /// + internal static bool IsDebugMode + { + get + { + if (ResourceHelper.isDebugMode.HasValue) + return ResourceHelper.isDebugMode.Value; + + CompilationSection compilationSection = (CompilationSection)System.Configuration.ConfigurationManager.GetSection(@"system.web/compilation"); + + return compilationSection.Debug; + } + set + { + ResourceHelper.isDebugMode = value; + } + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// The helper. + /// The path to the JavaScript file. + /// Indicates whether to use script manager(if exists) when register JavaScript reference. + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + /// + /// This method uses directly the resource from the . + /// In case you want to use embedded scripts from Sitefinity check . + /// + public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath, bool tryUseScriptManager) + { + return ResourceHelper.Script(helper, scriptPath, null, false, tryUseScriptManager); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// The helper. + /// The path to the JavaScript file. + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + /// + /// This method uses directly the resource from the . + /// In case you want to use embedded scripts from Sitefinity check . + /// + public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath) + { + return ResourceHelper.Script(helper, scriptPath, null, false, true); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// The helper. + /// The path to the JavaScript file. + /// The path to the JavaScript file. + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + /// + /// This method uses directly the resource from the . + /// In case you want to use embedded scripts from Sitefinity check . + /// + public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath, List> attributes) + { + return ResourceHelper.Script(helper, scriptPath, null, false, true, attributes); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// The helper. + /// The path to the JavaScript file. + /// The name of the section that will render this script. If null it will render on the same place of the page + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + /// + /// This method uses directly the resource from the . + /// In case you want to use embedded scripts from Sitefinity check . + /// + public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath, string sectionName) + { + return ResourceHelper.Script(helper, scriptPath, sectionName, true); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// The helper. + /// The path to the JavaScript file. + /// The name of the section that will render this script. If null it will render on the same place of the page + /// Indicates whether to throw an exception if the specified section does not exist. + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + /// + /// This method uses directly the resource from the . + /// In case you want to use embedded scripts from Sitefinity check . + /// + public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath, string sectionName, bool throwException) + { + return ResourceHelper.Script(helper, scriptPath, sectionName, throwException, true); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// The helper. + /// The path to the JavaScript file. + /// The name of the section that will render this script. If null it will render on the same place of the page + /// Indicates whether to throw an exception if the specified section does not exist. + /// The path to the JavaScript file. + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + /// + /// This method uses directly the resource from the . + /// In case you want to use embedded scripts from Sitefinity check . + /// + public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath, string sectionName, bool throwException, List> attributes) + { + return ResourceHelper.Script(helper, scriptPath, sectionName, throwException, true, attributes); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// The helper. + /// The path to the JavaScript file. + /// The name of the section that will render this script. If null it will render on the same place of the page + /// Indicates whether to throw an exception if the specified section does not exist. + /// Indicates whether to use script manager(if exists) when register JavaScript reference. + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + /// + /// This method uses directly the resource from the . + /// In case you want to use embedded scripts from Sitefinity check . + /// + public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath, string sectionName, bool throwException, bool tryUseScriptManager) + { + if (tryUseScriptManager && ResourceHelper.TryConfigureScriptManager(scriptPath, helper.ViewContext.HttpContext.CurrentHandler)) + return MvcHtmlString.Empty; + + return ResourceHelper.RegisterResource(helper.ViewContext.HttpContext, scriptPath, ResourceType.Js, sectionName, throwException, null); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// The helper. + /// The path to the JavaScript file. + /// The name of the section that will render this script. If null it will render on the same place of the page + /// Indicates whether to throw an exception if the specified section does not exist. + /// Indicates whether to use script manager(if exists) when register JavaScript reference. + /// A list of attribute key value pairs to be added to the script + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + /// + /// This method uses directly the resource from the . + /// In case you want to use embedded scripts from Sitefinity check . + /// + public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath, string sectionName, bool throwException, bool tryUseScriptManager, List> attributes) + { + if (tryUseScriptManager && ResourceHelper.TryConfigureScriptManager(scriptPath, helper.ViewContext.HttpContext.CurrentHandler)) + return MvcHtmlString.Empty; + + return ResourceHelper.RegisterResource(helper.ViewContext.HttpContext, scriptPath, ResourceType.Js, sectionName, throwException, attributes); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// + /// This helper references the same resource existing in Sitefinity. + /// + /// The helper. + /// The script reference. + /// Indicates whether to use script manager(if exists) when register JavaScript reference. + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + public static MvcHtmlString Script(this HtmlHelper helper, ScriptRef scriptReference, bool tryUseScriptManager) + { + return ResourceHelper.Script(helper, scriptReference, null, false, tryUseScriptManager); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// + /// This helper references the same resource existing in Sitefinity. + /// + /// The helper. + /// The script reference. + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + public static MvcHtmlString Script(this HtmlHelper helper, ScriptRef scriptReference) + { + return ResourceHelper.Script(helper, scriptReference, null, false, true); + } + + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// + /// This helper references the same resource existing in Sitefinity. + /// + /// The helper. + /// The script reference. + /// The path to the JavaScript file. + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + public static MvcHtmlString Script(this HtmlHelper helper, ScriptRef scriptReference, List> attributes) + { + return ResourceHelper.Script(helper, scriptReference, null, false, true, attributes); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// + /// This helper references the same resource existing in Sitefinity. + /// + /// The helper. + /// The script reference. + /// The name of the section that will render this script. If null it will render on the same place of the page + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + public static MvcHtmlString Script(this HtmlHelper helper, ScriptRef scriptReference, string sectionName) + { + return ResourceHelper.Script(helper, scriptReference, sectionName, true); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// + /// This helper references the same resource existing in Sitefinity. + /// + /// The helper. + /// The script reference. + /// The name of the section that will render this script. If null it will render on the same place of the page + /// The path to the JavaScript file. + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + public static MvcHtmlString Script(this HtmlHelper helper, ScriptRef scriptReference, string sectionName, List> attributes) + { + return ResourceHelper.Script(helper, scriptReference, sectionName, true, true, attributes); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// + /// This helper references the same resource existing in Sitefinity. + /// + /// The helper. + /// The script reference. + /// The name of the section that will render this script. If null it will render on the same place of the page + /// Indicates whether to throw an exception if the specified section does not exist. + /// Indicates whether to use script manager (if exists) when register JavaScript reference. + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + public static MvcHtmlString Script(this HtmlHelper helper, ScriptRef scriptReference, string sectionName, bool throwException, bool tryUseScriptManager) + { + if (tryUseScriptManager && ResourceHelper.TryConfigureScriptManager(scriptReference, helper.ViewContext.HttpContext.CurrentHandler)) + return System.Web.Mvc.MvcHtmlString.Empty; + + var references = PageManager.GetScriptReferences(scriptReference).Select(r => new MvcScriptReference(r)); + + StringBuilder outputMarkup = new StringBuilder(); + + foreach (var script in references) + { + var resourceUrl = script.GetResourceUrl(); + outputMarkup.Append(ResourceHelper.RegisterResource(helper.ViewContext.HttpContext, resourceUrl, ResourceType.Js, sectionName, throwException, null)); + } + + return MvcHtmlString.Create(outputMarkup.ToString()); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// + /// This helper references the same resource existing in Sitefinity. + /// + /// The helper. + /// The script reference. + /// The name of the section that will render this script. If null it will render on the same place of the page + /// Indicates whether to throw an exception if the specified section does not exist. + /// Indicates whether to use script manager (if exists) when register JavaScript reference. + /// A list of attribute key value pairs to be added to the script + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + public static MvcHtmlString Script(this HtmlHelper helper, ScriptRef scriptReference, string sectionName, bool throwException, bool tryUseScriptManager, List> attributes) + { + if (tryUseScriptManager && ResourceHelper.TryConfigureScriptManager(scriptReference, helper.ViewContext.HttpContext.CurrentHandler)) + return System.Web.Mvc.MvcHtmlString.Empty; + + var references = PageManager.GetScriptReferences(scriptReference).Select(r => new MvcScriptReference(r)); + + StringBuilder outputMarkup = new StringBuilder(); + + foreach (var script in references) + { + var resourceUrl = script.GetResourceUrl(); + outputMarkup.Append(ResourceHelper.RegisterResource(helper.ViewContext.HttpContext, resourceUrl, ResourceType.Js, sectionName, throwException, attributes)); + } + + return MvcHtmlString.Create(outputMarkup.ToString()); + } + + /// + /// Registers JavaScript reference and ensures that it loads maximum once for a page. + /// + /// + /// This helper references the same resource existing in Sitefinity. + /// + /// The helper. + /// The script reference. + /// The name of the section that will render this script. If null it will render on the same place of the page + /// Indicates whether to throw an exception if the specified section does not exist. + /// A list of attribute key value pairs to be added to the script + /// If it is used the script will always be loaded on the top section of the page. + /// + /// MvcHtmlString + /// + public static MvcHtmlString Script(this HtmlHelper helper, ScriptRef scriptReference, string sectionName, bool throwException) + { + return ResourceHelper.Script(helper, scriptReference, sectionName, throwException, true); + } + + /// + /// Registers style sheet reference and ensures that it loads maximum once for a page. + /// + /// The helper. + /// The path to the CSS file. + /// + /// MvcHtmlString + /// + public static MvcHtmlString StyleSheet(this HtmlHelper helper, string resourcePath) + { + return ResourceHelper.StyleSheet(helper, resourcePath, null, false); + } + + /// + /// Registers style sheet reference and ensures that it loads maximum once for a page. + /// + /// The helper. + /// The path to the CSS file. + /// A list of attribute key value pairs to be added to the stylesheet + /// + /// MvcHtmlString + /// + public static MvcHtmlString StyleSheet(this HtmlHelper helper, string resourcePath, List> attributes) + { + return ResourceHelper.StyleSheet(helper, resourcePath, null, false, attributes); + } + + /// + /// Registers style sheet reference and ensures that it loads maximum once for a page. + /// + /// The helper. + /// The path to the CSS file. + /// The name of the section that will render this script. If null it will render on the same place of the page + /// + /// MvcHtmlString + /// + public static MvcHtmlString StyleSheet(this HtmlHelper helper, string resourcePath, string sectionName) + { + return ResourceHelper.StyleSheet(helper, resourcePath, sectionName, true); + } + + /// + /// Registers style sheet reference and ensures that it loads maximum once for a page. + /// + /// The helper. + /// The path to the CSS file. + /// The name of the section that will render this script. If null it will render on the same place of the page + /// Indicates whether to throw an exception if the specified section does not exist. + /// + /// MvcHtmlString + /// + public static MvcHtmlString StyleSheet(this HtmlHelper helper, string resourcePath, string sectionName, bool throwException) + { + return ResourceHelper.RegisterResource(helper.ViewContext.HttpContext, resourcePath, ResourceType.Css, sectionName, throwException, null); + } + + /// + /// Registers style sheet reference and ensures that it loads maximum once for a page. + /// + /// The helper. + /// The path to the CSS file. + /// The name of the section that will render this script. If null it will render on the same place of the page + /// Indicates whether to throw an exception if the specified section does not exist. + /// A list of attribute key value pairs to be added to the stylesheet + /// + /// MvcHtmlString + /// + public static MvcHtmlString StyleSheet(this HtmlHelper helper, string resourcePath, string sectionName, bool throwException, List> attributes) + { + return ResourceHelper.RegisterResource(helper.ViewContext.HttpContext, resourcePath, ResourceType.Css, sectionName, throwException, attributes); + } + + /// + /// Adds script references required by the Sitefinity's QueryBuilder component. + /// + /// The helper. + /// + /// MvcHtmlString + /// + public static MvcHtmlString QueryBuilderScriptReferences(this HtmlHelper helper) + { + var result = new StringBuilder(); + var urlHelper = new UrlHelper(helper.ViewContext.HttpContext.Request.RequestContext); + result.Append(ResourceHelper.Script(helper, urlHelper.EmbeddedResource("Telerik.Sitefinity.Web.UI.QueryBuilder", "Telerik.Sitefinity.Web.UI.QueryBuilder.Scripts.QueryData.js")).ToHtmlString()); + result.Append(ResourceHelper.Script(helper, urlHelper.EmbeddedResource("Telerik.Sitefinity.Web.UI.QueryBuilder", "Telerik.Sitefinity.Web.UI.QueryBuilder.Scripts.QueryDataItem.js")).ToHtmlString()); + result.Append(ResourceHelper.Script(helper, urlHelper.EmbeddedResource("Telerik.Sitefinity.Web.UI.QueryBuilder", "Telerik.Sitefinity.Web.UI.QueryBuilder.Scripts.QueryItem.js")).ToHtmlString()); + result.Append(ResourceHelper.Script(helper, urlHelper.EmbeddedResource("Telerik.Sitefinity.Web.UI.QueryBuilder", "Telerik.Sitefinity.Web.UI.QueryBuilder.Scripts.QueryGroup.js")).ToHtmlString()); + result.Append(ResourceHelper.Script(helper, urlHelper.EmbeddedResource("Telerik.Sitefinity.Web.UI.QueryBuilder", "Telerik.Sitefinity.Web.UI.QueryBuilder.Scripts.QueryBuilder.js")).ToHtmlString()); + + return MvcHtmlString.Create(result.ToString()); + } + + /// + /// Adds script references required by the Sitefinity's CodeMirror component. + /// + /// The helper. + /// + /// MvcHtmlString + /// + public static MvcHtmlString CodeMirrorScriptReferences(this HtmlHelper helper) + { + var result = new StringBuilder(); + var urlHelper = new UrlHelper(helper.ViewContext.HttpContext.Request.RequestContext); + result.Append(ResourceHelper.StyleSheet(helper, urlHelper.EmbeddedResource(typeof(Telerik.Sitefinity.Resources.Reference).FullName, "Telerik.Sitefinity.Resources.Scripts.CodeMirror.codemirror.css")).ToHtmlString()); + result.Append(ResourceHelper.StyleSheet(helper, urlHelper.EmbeddedResource(typeof(Telerik.Sitefinity.Resources.Reference).FullName, "Telerik.Sitefinity.Resources.Scripts.CodeMirror.Theme.default.css")).ToHtmlString()); + result.Append(ResourceHelper.Script(helper, urlHelper.EmbeddedResource(typeof(Telerik.Sitefinity.Resources.Reference).FullName, "Telerik.Sitefinity.Resources.Scripts.CodeMirror.codemirror.js")).ToHtmlString()); + result.Append(ResourceHelper.Script(helper, urlHelper.EmbeddedResource(typeof(Telerik.Sitefinity.Resources.Reference).FullName, "Telerik.Sitefinity.Resources.Scripts.CodeMirror.Mode.htmlmixed.js")).ToHtmlString()); + result.Append(ResourceHelper.Script(helper, urlHelper.EmbeddedResource(typeof(Telerik.Sitefinity.Resources.Reference).FullName, "Telerik.Sitefinity.Resources.Scripts.CodeMirror.Mode.xml.js")).ToHtmlString()); + result.Append(ResourceHelper.Script(helper, urlHelper.EmbeddedResource(typeof(Telerik.Sitefinity.Resources.Reference).FullName, "Telerik.Sitefinity.Resources.Scripts.CodeMirror.Mode.css.js")).ToHtmlString()); + result.Append(ResourceHelper.Script(helper, urlHelper.EmbeddedResource(typeof(Telerik.Sitefinity.Resources.Reference).FullName, "Telerik.Sitefinity.Resources.Scripts.CodeMirror.Mode.javascript.js")).ToHtmlString()); + + return MvcHtmlString.Create(result.ToString()); + } + + /// + /// Adds script references for Js Beautify library. + /// + /// The helper. + /// + /// MvcHtmlString + /// + public static MvcHtmlString JsBeautifierScriptReference(this HtmlHelper helper) + { + var result = new StringBuilder(); + var urlHelper = new UrlHelper(helper.ViewContext.HttpContext.Request.RequestContext); + result.Append(ResourceHelper.Script(helper, urlHelper.EmbeddedResource("Telerik.Sitefinity.Frontend.Startup", "Telerik.Sitefinity.Frontend.Mvc.Scripts.JSBeautifier.beautify-html.js")).ToHtmlString()); + return MvcHtmlString.Create(result.ToString()); + } + + /// + /// Renders the lang attribute. + /// + /// The helper. + /// + public static MvcHtmlString RenderLangAttribute(this HtmlHelper helper) + { + return RenderLangAttribute(helper, Telerik.Sitefinity.Services.SystemManager.CurrentContext.Culture.Name); + } + + /// + /// Renders the lang attribute. + /// + /// The helper. + /// The culture. + /// + public static MvcHtmlString RenderLangAttribute(this HtmlHelper helper, string culture) + { + string attributeString = helper.FormatValue(HttpUtility.HtmlAttributeEncode(culture), "lang=\"{0}\""); + + return new MvcHtmlString(attributeString); + } + + /// + /// Renders the dir attribute when language is right to left. + /// + /// The helper. + /// + public static MvcHtmlString RenderDirAttribute(this HtmlHelper helper) + { + return RenderDirAttribute(helper, Telerik.Sitefinity.Services.SystemManager.CurrentContext.Culture.Name); + } + + /// + /// Renders the dir attribute when language is right to left. + /// + /// The helper. + /// The culture. + /// + public static MvcHtmlString RenderDirAttribute(this HtmlHelper helper, string culture) + { + var isRtl = (Array.Find(rtlLanguages, s => culture.ToString().StartsWith(s)) != null) || culture.ToString().ToLower().Contains("arab"); + string attributeString = isRtl && (!SystemManager.IsDesignMode || SystemManager.IsPreviewMode) ? "dir=\"rtl\"" : ""; + + return new MvcHtmlString(attributeString); + } + + /// + /// Gets the web resource URL. + /// + /// The script reference. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")] + public static string GetWebResourceUrl(ScriptRef scriptReference) + { + var config = Config.Get().ScriptManager; + var scriptConfig = config.ScriptReferences[scriptReference.ToString()]; + string resourceUrl = string.Empty; + + if (config.EnableCdn || (scriptConfig.EnableCdn.HasValue && scriptConfig.EnableCdn.Value)) + { + resourceUrl = scriptConfig.Path; + } + else + { + var page = HttpContext.Current.Handler.GetPageHandler() ?? new PageProxy(null); + + resourceUrl = page.ClientScript.GetWebResourceUrl( + TypeResolutionService.ResolveType("Telerik.Sitefinity.Resources.Reference"), + scriptConfig.Name); + } + + return resourceUrl; + } + + /// + /// Places the script before the end of the body. + /// + /// The page. + /// The script. + public static void PlaceScriptBeforeBodyEnd(this Page page, string script) + { + /* There is a literal control in the FrontendMVC.aspx which is used as a mark where scripts should be placed.*/ + int insertAt = page.Controls.Count - 1; + MasterPage master = null; + bool hasLiteral = false; + for (int i = page.Controls.Count - 1; i >= 0; i--) + { + if (page.Controls[i] is LiteralControl) + { + insertAt = i; + hasLiteral = true; + break; + } + else if (page.Controls[i] is MasterPage) + { + master = page.Controls[i] as MasterPage; + break; + } + } + + if (master != null) + { + for (int i = master.Controls.Count - 1; i >= 0; i--) + { + if (master.Controls[i] is LiteralControl) + { + insertAt = i; + hasLiteral = true; + break; + } + } + } + + if (hasLiteral) + { + if (master != null) + { + master.Controls.AddAt(insertAt, new LiteralControl(script)); + } + else + { + if (page.Form != null) + { + page.Form.Controls.Add(new LiteralControl(script)); + } + else + { + page.Controls.AddAt(insertAt, new LiteralControl(script)); + } + } + } + else + { + if (page.Form != null) + { + page.Form.Controls.Add(new LiteralControl(script)); + } + else + { + page.Controls.Add(new LiteralControl(script)); + } + } + } + + /// + /// Renders all scripts. + /// + /// The context. + /// The section name. + /// + internal static string RenderAllScripts(HttpContextBase context, string sectionName) + { + var scriptRegister = new ResourceRegister(ResourceHelper.JsRegisterName, context); + var scriptMarkup = ResourceHelper.BuildHtmlResourcesMarkup(scriptRegister, sectionName, ResourceType.Js); + + return scriptMarkup; + } + + /// + /// Renders all stylesheets. + /// + /// The context. + /// The section name. + /// + internal static string RenderAllStylesheets(HttpContextBase context, string sectionName) + { + var stylesheetRegister = new ResourceRegister(ResourceHelper.CssRegisterName, context); + var stylesheetMarkup = ResourceHelper.BuildHtmlResourcesMarkup(stylesheetRegister, sectionName, ResourceType.Css); + + return stylesheetMarkup; + } + + private static MvcHtmlString RegisterResource(HttpContextBase httpContext, string resourcePath, ResourceType resourceType, string sectionName, bool throwException, List> attributes = null) + { + throwException = throwException && httpContext.CurrentHandler != null; + + var registerName = string.Empty; + if (resourceType == ResourceType.Js) + registerName = ResourceHelper.JsRegisterName; + else if (resourceType == ResourceType.Css) + registerName = ResourceHelper.CssRegisterName; + + var register = new ResourceRegister(registerName, httpContext); + + MvcHtmlString result = MvcHtmlString.Empty; + + if (!string.IsNullOrWhiteSpace(sectionName)) + { + var pageHandler = httpContext.Handler.GetPageHandler(); + if (pageHandler != null && pageHandler.Master is MvcMasterPage) + { + if (!throwException && !SectionRenderer.IsAvailable(pageHandler, sectionName)) + sectionName = null; + } + else + { + if (!SectionRenderer.IsAvailable(pageHandler, sectionName)) + sectionName = null; + } + } + else + { + sectionName = null; + } + + // No section name renders the script inline if it hasn't been rendered + if (sectionName == null || + ResourceHelper.RenderScriptSection) + { + if (!register.IsRegistered(resourcePath)) + { + result = MvcHtmlString.Create(ResourceHelper.BuildSingleResourceMarkup(resourcePath, resourceType, sectionName, attributes)); + } + } + + // Register the resource even if it had to be rendered inline (avoid repetitions). + register.Register(resourcePath, sectionName, throwException, attributes); + + return result; + } + + /// + /// Tries the configure script manager. + /// + /// The script reference. + /// The httpHandler. + /// + private static bool TryConfigureScriptManager(ScriptRef scriptReference, IHttpHandler httpHandler) + { + var page = ResourceHelper.GetTopMostPageFromHandler(httpHandler); + + if (page != null) + { + var scriptManager = PageManager.ConfigureScriptManager(page, scriptReference, false); + + if (scriptManager != null) + { + return true; + } + } + + return false; + } + + /// + /// Tries the configure script manager. + /// + /// The script reference. + /// The httpHandler. + /// + private static bool TryConfigureScriptManager(string scriptReference, IHttpHandler httpHandler) + { + var page = ResourceHelper.GetTopMostPageFromHandler(httpHandler); + + if (page != null) + { + var scriptManager = ScriptManager.GetCurrent(page); + + if (scriptManager != null) + { + var updatedScriptReference = GetResourceOrMinified(scriptReference); + scriptManager.Scripts.Add(new ScriptReference(updatedScriptReference)); + return true; + } + } + + return false; + } + + private static Page GetTopMostPageFromHandler(IHttpHandler httpHandler) + { + var page = httpHandler.GetPageHandler(); + + if (page != null) + { + var topMostPage = page; + + while (topMostPage.PreviousPage != null) + { + topMostPage = topMostPage.PreviousPage; + } + + return topMostPage; + } + + return null; + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "sectionName")] + private static string BuildHtmlResourcesMarkup(ResourceRegister resourceRegister, string sectionName, ResourceType resourceType) + { + StringBuilder output = new StringBuilder(); + + foreach (var resource in resourceRegister.GetResourceItemsForSection(sectionName)) + { + if (!resourceRegister.IsRendered(resource.ResourceKey)) + { + output.Append(ResourceHelper.BuildSingleResourceMarkup(resource.ResourceKey, resourceType, sectionName, resource.Attributes)); + resourceRegister.MarkAsRendered(resource.ResourceKey); + } + } + + return output.ToString(); + } + + private static string BuildSingleResourceMarkup(string resourceKey, ResourceType resourceType, string sectionName, List> attributes = null) + { + string result; + + if (resourceType == ResourceType.Js) + result = ResourceHelper.BuildScriptMarkup(resourceKey, sectionName, attributes); + else if (resourceType == ResourceType.Css) + result = ResourceHelper.BuildStyleSheetMarkup(resourceKey, attributes); + else + result = string.Empty; + + return result; + } + + private static string BuildScriptMarkup(string resourceKey, string sectionName, List> attributes) + { + var tag = new TagBuilder("script"); + + resourceKey = GetResourceOrMinified(resourceKey); + + tag.Attributes["src"] = resourceKey; + tag.Attributes["type"] = "text/javascript"; + + if (attributes != null) + { + foreach (var attr in attributes) + { + tag.Attributes[attr.Key] = attr.Value; + } + } + + if (ResourceHelper.RenderScriptSection && !string.IsNullOrWhiteSpace(sectionName)) + { + tag.Attributes["data-sf-section"] = sectionName; + } + + return tag.ToString(TagRenderMode.Normal); + } + + private static string GetResourceOrMinified(string resourceKey) + { + if (!ResourceHelper.IsDebugMode) + { + var extensionIndex = resourceKey.LastIndexOf(".js"); + if (extensionIndex > 0 && !resourceKey.Contains(".min.js")) + { + var minFilePath = resourceKey.Insert(extensionIndex, ".min"); + var minPathWithoutParams = resourceKey.Substring(0, extensionIndex) + ".min.js"; + + if (VirtualPathManager.FileExists(minPathWithoutParams) || VirtualPathManager.FileExists(minFilePath)) + { + resourceKey = minFilePath; + } + } + } + + return resourceKey; + } + + private static string BuildStyleSheetMarkup(string resourceKey, List> attributes) + { + var tag = new TagBuilder("link"); + + tag.Attributes["href"] = resourceKey; + tag.Attributes["rel"] = "stylesheet"; + tag.Attributes["type"] = "text/css"; + + if (attributes != null) + { + foreach (var attr in attributes) + { + tag.Attributes[attr.Key] = attr.Value; + } + } + + return tag.ToString(TagRenderMode.SelfClosing); + } + + internal const string JsRegisterName = "JsRegister"; + internal const string CssRegisterName = "CssRegister"; + + internal class MvcScriptReference : ScriptReference + { + public MvcScriptReference(ScriptReference reference) + { + if (reference == null) + throw new ArgumentNullException("reference"); + + this.Path = reference.Path; + this.Assembly = reference.Assembly; + this.Name = reference.Name; + } + + public string GetResourceUrl() + { + var scriptManager = new ScriptManager(); + + try + { + return this.GetUrl(scriptManager, zip: false); + } + catch (NullReferenceException ex) + { + ////This is because ScriptReference.ClientUrlResolver is null as the class in to initialize on the page. + if (this.IsGetUrlFromPathException(ex)) + { + return scriptManager.ResolveClientUrl(this.Path); + } + + throw; + } + } + + private bool IsGetUrlFromPathException(Exception ex) + { + return ex.TargetSite.Name == "GetUrlFromPath" && ex.TargetSite.DeclaringType.FullName == "System.Web.UI.ScriptReference"; + } + } + + /// + /// This enum represents supported resource types. + /// + internal enum ResourceType + { + Js, + Css + } + + private static bool? isDebugMode; + + private static string[] rtlLanguages = { "ar", "he", "fa", "ku", "ur", "dv", "ps", "ha", "ks", "yi" }; + } } \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/SettingsHelpers.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/SettingsHelpers.cs new file mode 100644 index 000000000..baa0b4271 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/SettingsHelpers.cs @@ -0,0 +1,67 @@ +using System.Linq; +using System.Web.Script.Serialization; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.Libraries.Model; +using Telerik.Sitefinity.Modules.Libraries.Configuration; +using Telerik.Sitefinity.Modules.Libraries.Images; +using Telerik.Sitefinity.Web.UI.ContentUI.Views.Backend.Detail.Definitions; +using Telerik.Sitefinity.Web.UI.Fields.Config; +using Telerik.Sitefinity.Web.UI.Fields.Definitions; + +namespace Telerik.Sitefinity.Frontend.Mvc.Helpers +{ + /// + /// This class contains helpers for working with widget settings. + /// + public static class SettingsHelpers + { + /// + /// Gets the media settings for specific media type + /// + /// Serialized media settings + public static string GetMediaSettings(string mediaType) + { + var libratiesConfig = Config.Get(); + object settings; + + switch (mediaType) + { + case "Image": + var singleImageUploadDefinition = libratiesConfig.ContentViewControls[ImagesDefinitions.BackendImagesDefinitionName]?.Views[ImagesDefinitions.SingleImageUploadDetailsView] as DetailFormViewDefinition; + var altTextRequired = (singleImageUploadDefinition?.Sections.First(s => s.Name == "MainSection")?.Fields.First(f => f.FieldName == nameof(Image.AlternativeText)) as TextFieldDefinition)?.Validation?.Required.GetValueOrDefault(); + + settings = new + { + AllowedExensionsSettings = libratiesConfig.Images.AllowedExensionsSettings, + EnableAllLanguagesSearch = libratiesConfig.EnableAllLanguagesSearch, + EnableSelectedFolderSearch = libratiesConfig.EnableSelectedFolderSearch, + AltTextRequired = altTextRequired + }; + break; + case "Video": + settings = new + { + AllowedExensionsSettings = libratiesConfig.Videos.AllowedExensionsSettings, + EnableAllLanguagesSearch = libratiesConfig.EnableAllLanguagesSearch, + EnableSelectedFolderSearch = libratiesConfig.EnableSelectedFolderSearch + }; + break; + case "Document": + settings = new + { + AllowedExensionsSettings = libratiesConfig.Documents.AllowedExensionsSettings, + EnableAllLanguagesSearch = libratiesConfig.EnableAllLanguagesSearch, + EnableSelectedFolderSearch = libratiesConfig.EnableSelectedFolderSearch, + AllowedExensions = libratiesConfig.Documents.AllowedExensions + }; + break; + default: + settings = null; + break; + } + + var serialzier = new JavaScriptSerializer(); + return serialzier.Serialize(settings); + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/SitefinityContext.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/SitefinityContext.cs index bfb793ed7..e1882aa57 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/SitefinityContext.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/SitefinityContext.cs @@ -1,4 +1,7 @@ using System; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Web; using System.Web.UI; using Telerik.Sitefinity.Frontend.Mvc.Helpers.ViewModels; using Telerik.Sitefinity.Modules.Pages; @@ -7,6 +10,7 @@ using Telerik.Sitefinity.Security.Model; using Telerik.Sitefinity.Services; using Telerik.Sitefinity.Web; +using Telerik.Sitefinity.Web.Events; namespace Telerik.Sitefinity.Frontend.Mvc.Helpers { @@ -65,9 +69,40 @@ public static ProfileViewModel Profile /// public static bool IsBackend { - get - { - return ControlExtensions.IsBackend(); + get + { + return ControlExtensions.IsBackend(); + } + } + + /// + /// Determines whether this method is invoked from Sitefinity's preview mode. + /// + public static bool IsPreviewMode + { + get + { + return SystemManager.IsPreviewMode; + } + } + + /// + /// Gets the frontend login URL for the current site as configured in the backend. + /// + /// + /// The frontend login URL. + /// + [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] + [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Login")] + public static string FrontendLoginUrl + { + get + { + var redirectStrategy = RedirectStrategyType.None; + var wrapper = new HttpContextWrapper(HttpContext.Current); + var pageUrl = RouteHelper.GetFrontEndLogin(wrapper, out redirectStrategy); + + return pageUrl; } } @@ -126,4 +161,4 @@ private static ProfileViewModel GetCurrentSitefinityUserProfile() #endregion } -} +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/SitefinityHelper.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/SitefinityHelper.cs new file mode 100644 index 000000000..bd05c3638 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/SitefinityHelper.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Web.Mvc; + +namespace Telerik.Sitefinity.Frontend.Mvc.Helpers +{ + /// + /// This class contains basic helper method used in Feather. + /// + public static class SitefinityHelper + { + /// + /// Wrapper helper for Sitefinity. + /// + /// The helper. + /// + public static HtmlHelper Sitefinity(this HtmlHelper helper) + { + return helper; + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/SocialShareHelpers.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/SocialShareHelpers.cs index a5fdac1ef..845919ff0 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/SocialShareHelpers.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/SocialShareHelpers.cs @@ -1,6 +1,6 @@ -using System.Web; +using System; +using System.Diagnostics.CodeAnalysis; using System.Web.Mvc; -using System.Web.Mvc.Html; namespace Telerik.Sitefinity.Frontend.Mvc.Helpers { @@ -10,22 +10,23 @@ public static class SocialShareHelpers /// Socials the share options. Redirect to the SocialShare control if exist else render error message /// /// The HTML helper. - public static System.Web.Mvc.MvcHtmlString SocialShareOptions(this HtmlHelper helper) + [Obsolete("Social sharing module has been removed. This helper will no longer work.")] + [SuppressMessage("Microsoft.Design", "CA1801:ReviewUnusedParameters")] + public static MvcHtmlString SocialShareOptions(this HtmlHelper helper) { - System.Web.Mvc.MvcHtmlString result; - try - { - result = helper.Action(ActionName, ControllerName); - } - catch (HttpException) - { - result = new System.Web.Mvc.MvcHtmlString("The SocialShare widget could not be found."); - } - - return result; + return null; } - private const string ActionName = "Index"; - private const string ControllerName = "SocialShare"; + /// + /// Socials the share options. Redirect to the SocialShare control if exist else render error message + /// + /// The HTML helper. + /// The data item which we will be sharing + [Obsolete("Social sharing module has been removed. This helper will no longer work.")] + [SuppressMessage("Microsoft.Design", "CA1801:ReviewUnusedParameters")] + public static MvcHtmlString SocialShareOptions(this HtmlHelper helper, Telerik.Sitefinity.Model.IHasTitle dataItem) + { + return null; + } } } \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/UrlHelpers.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/UrlHelpers.cs index 1c59f45c5..bea9444b9 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/UrlHelpers.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/UrlHelpers.cs @@ -1,89 +1,262 @@ -using System; -using System.Web; -using System.Web.Hosting; -using System.Web.Mvc; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure; -using Telerik.Sitefinity.Frontend.Resources; - -namespace Telerik.Sitefinity.Frontend.Mvc.Helpers -{ - /// - /// Extension methods for UrlHelper. - /// - public static class UrlHelpers - { - /// - /// Resolves URL based on the current widget. - /// - /// The URL helper. - /// The content path. - /// Resolved URL. - /// contentPath - /// - /// Could not resolve the given URL because RouteData of the current context is null. - /// or - /// Could not resolve the given URL because RouteData does not contain \controller\ key. - /// - public static string WidgetContent(this UrlHelper helper, string contentPath) - { - if (contentPath.IsNullOrEmpty()) - throw new ArgumentNullException("contentPath"); - - if (contentPath.StartsWith("~", StringComparison.Ordinal) || contentPath.StartsWith("/", StringComparison.Ordinal) || contentPath.Contains("://")) - return helper.Content(contentPath); - - if (helper.RequestContext.RouteData == null) - throw new InvalidOperationException("Could not resolve the given URL because RouteData of the current context is null."); - - var packagesManager = new PackageManager(); - var packageName = packagesManager.GetCurrentPackage(); - - var contentResolvedPath = string.Empty; - - // "widgetName" is a parameter in the route of the Designer. It allows us to have a special fallback logic - // where we first check for the requested resource in the widget assembly and then fallback to the current controller assembly. - object controllerName; - if (helper.RequestContext.RouteData.Values.TryGetValue("widgetName", out controllerName)) - contentResolvedPath = UrlHelpers.GetResourcePath((string)controllerName, contentPath, PackageManager.PackageUrlParameterName, packageName); - - if (string.IsNullOrEmpty(contentResolvedPath)) - { - if (helper.RequestContext.RouteData.Values.TryGetValue("controller", out controllerName)) - contentResolvedPath = UrlHelpers.GetResourcePath((string)controllerName, contentPath, PackageManager.PackageUrlParameterName, packageName); - else - throw new InvalidOperationException("Could not resolve the given URL because RouteData does not contain \"controller\" key."); - } - - if (string.IsNullOrEmpty(contentResolvedPath)) - { - var url = "~/" + FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(UrlHelpers).Assembly) + contentPath; - contentResolvedPath = UrlTransformations.AppendParam(url, PackageManager.PackageUrlParameterName, packageName); - } - - return helper.Content(contentResolvedPath); - } - - /// - /// Gets the resource path. - /// - /// Name of the controller. - /// The content path. - /// Name of the paramater. - /// Name of the package. - /// - private static string GetResourcePath(string controllerName, string contentPath, string paramaterName, string packageName) - { - var controllerType = FrontendManager.ControllerFactory.ResolveControllerType(controllerName); - var alternatePath = FrontendManager.VirtualPathBuilder.GetVirtualPath(controllerType); - var baseUrl = "~/" + alternatePath + contentPath; - - if (HostingEnvironment.VirtualPathProvider == null || HostingEnvironment.VirtualPathProvider.FileExists(baseUrl)) - { - alternatePath = UrlTransformations.AppendParam(baseUrl, paramaterName, packageName); - return alternatePath; - } - - return string.Empty; - } - } -} +using System; +using System.Linq; +using System.Text; +using System.Web.Hosting; +using System.Web.Mvc; +using Telerik.Sitefinity.Abstractions.VirtualPath; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing; +using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Mvc.Rendering; +using Telerik.Sitefinity.Taxonomies.Model; +using Telerik.Sitefinity.Utilities.TypeConverters; + +namespace Telerik.Sitefinity.Frontend.Mvc.Helpers +{ + /// + /// Extension methods for UrlHelper. + /// + public static class UrlHelpers + { + /// + /// Resolves URL based on the current widget. + /// + /// The URL helper. + /// The content path. + /// Resolved URL. + /// contentPath + /// + /// Could not resolve the given URL because RouteData of the current context is null. + /// or + /// Could not resolve the given URL because RouteData does not contain \controller\ key. + /// + public static string WidgetContent(this UrlHelper helper, string contentPath) + { + if (contentPath.IsNullOrEmpty()) + throw new ArgumentNullException("contentPath"); + + var packagesManager = new PackageManager(); + var packageName = packagesManager.GetCurrentPackage(); + + if (contentPath.StartsWith("~", StringComparison.Ordinal) || contentPath.StartsWith("/", StringComparison.Ordinal) || contentPath.Contains("://")) + { + var url = UrlTransformations.AppendParam(contentPath, PackageManager.PackageUrlParameterName, packageName); + url = UrlHelpers.AppendVersion(url); + return helper.Content(url); + } + + if (helper.RequestContext.RouteData == null) + throw new InvalidOperationException("Could not resolve the given URL because RouteData of the current context is null."); + + var contentResolvedPath = string.Empty; + object controllerName; + + // "widgetName" is a parameter in the route of the Designer. It allows us to have a special fallback logic + // where we first check for the requested resource in the widget assembly and then fallback to the current controller assembly. + if (helper.RequestContext.RouteData.Values.TryGetValue("widgetName", out controllerName)) + contentResolvedPath = UrlHelpers.GetResourcePath((string)controllerName, contentPath, PackageManager.PackageUrlParameterName, packageName); + + if (string.IsNullOrEmpty(contentResolvedPath)) + { + if (helper.RequestContext.RouteData.Values.TryGetValue("controller", out controllerName)) + contentResolvedPath = UrlHelpers.GetResourcePath((string)controllerName, contentPath, PackageManager.PackageUrlParameterName, packageName); + else + throw new InvalidOperationException("Could not resolve the given URL because RouteData does not contain \"controller\" key."); + } + + if (string.IsNullOrEmpty(contentResolvedPath)) + { + var url = "~/" + FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(UrlHelpers).Assembly) + contentPath; + contentResolvedPath = UrlTransformations.AppendParam(url, PackageManager.PackageUrlParameterName, packageName); + } + + contentResolvedPath = UrlHelpers.AppendVersion(contentResolvedPath); + + return helper.Content(contentResolvedPath); + } + + /// + /// Resolves URL based on the current widget. + /// + /// The helper. + /// The content path. + /// Name of the assembly. + /// + /// contentPath + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)")] + public static string WidgetContent(this UrlHelper helper, string contentPath, string assemblyName) + { + if (contentPath.IsNullOrEmpty()) + throw new ArgumentNullException("contentPath"); + + if (string.IsNullOrEmpty(assemblyName)) + return UrlHelpers.WidgetContent(helper, contentPath); + + var packagesManager = new PackageManager(); + var packageName = packagesManager.GetCurrentPackage(); + + if (contentPath.StartsWith("~", StringComparison.Ordinal) || contentPath.StartsWith("/", StringComparison.Ordinal) || contentPath.Contains("://")) + { + var url = UrlTransformations.AppendParam(contentPath, PackageManager.PackageUrlParameterName, packageName); + url = UrlHelpers.AppendVersion(url); + return helper.Content(url); + } + + var resourceUrl = string.Format("~/{0}/{1}", FrontendManager.VirtualPathBuilder.GetVirtualPath(assemblyName), contentPath); + var contentResolvedPath = UrlTransformations.AppendParam(resourceUrl, PackageManager.PackageUrlParameterName, packageName); + contentResolvedPath = UrlHelpers.AppendVersion(contentResolvedPath); + + return helper.Content(contentResolvedPath); + } + + /// + /// Gets the URL of an embedded resource. + /// + /// The helper. + /// A type from the assembly that embeds the resource. + /// The resource path. + /// The resource URL. + public static string EmbeddedResource(this UrlHelper helper, string type, string path) + { + var page = helper.RequestContext.HttpContext.Handler.GetPageHandler() ?? new PageProxy(null); + return page.ClientScript.GetWebResourceUrl(TypeResolutionService.ResolveType(type), path); + } + + /// + /// Gets the URL template used for the paging. + /// + /// The URL template. + public static string GetRedirectPagingUrl() + { + string redirectUrl; + if (UrlParamsMapperBase.UseNamedParametersRouting) + { + redirectUrl = "/" + FeatherActionInvoker.PagingNamedParameter + "/{0}"; + } + else + { + redirectUrl = "/{0}"; + } + + return redirectUrl; + } + + /// + /// Gets the URL template used for the paging when filtered by taxonomy. + /// + /// The URL template. + public static string GetRedirectPagingUrl(ITaxon taxonFilter) + { + string redirectUrl; + if (UrlParamsMapperBase.UseNamedParametersRouting) + { + redirectUrl = string.Format("/{0}/{1}/{2}", taxonFilter.Taxonomy.Name, taxonFilter.UrlName, FeatherActionInvoker.PagingNamedParameter) + "/{0}"; + } + else + { + redirectUrl = "/" + taxonFilter.UrlName + "/{0}"; + } + + return redirectUrl; + } + + /// + /// Gets the URL template used for the paging when filtered by taxonomy and url evaluation mode. + /// + /// The URL template. + public static string GetRedirectPagingUrl(ITaxon taxonFilter, string[] urlParams, string queryString) + { + bool addQueryString = !string.IsNullOrEmpty(queryString); + string redirectUrl; + if (UrlParamsMapperBase.UseNamedParametersRouting) + { + redirectUrl = string.Format("/{0}/{1}/{2}", taxonFilter.Taxonomy.Name, taxonFilter.UrlName, FeatherActionInvoker.PagingNamedParameter) + "/{0}"; + } + else + { + // 3 because we have the following structure /-in-tags/tags/tagName + if (urlParams != null && urlParams.Length >= 3) + { + if (taxonFilter is FlatTaxon) + { + redirectUrl = string.Format("/{0}/{1}/{2}", urlParams[0], urlParams[1], urlParams[2]); + } + else + { + if (urlParams[urlParams.Length - 1].Equals(taxonFilter.UrlName)) + { + // url is like /-in-category/categories/cat1/cat2 + string taxonFilterParams = string.Join("/", urlParams); + redirectUrl = "/" + taxonFilterParams; + } + else + { + // url is like /-in-category/categories/cat1/cat2/2 where '2' is the page so we want to exclude it from redirect url + string taxonFilterParams = string.Join("/", urlParams.Take(urlParams.Length - 1)); + redirectUrl = "/" + taxonFilterParams; + } + } + + // add /{0} at the very end for the page number + redirectUrl += "/{0}"; + } + else + { + addQueryString = false; + redirectUrl = "/{0}" + queryString; + } + } + + if (addQueryString) + { + redirectUrl += queryString; + } + + return redirectUrl; + } + + /// + /// Gets the resource path. + /// + /// Name of the controller. + /// The content path. + /// Name of the paramater. + /// Name of the package. + /// + private static string GetResourcePath(string controllerName, string contentPath, string paramaterName, string packageName) + { + var controllerType = FrontendManager.ControllerFactory.ResolveControllerType(controllerName); + if (controllerType != null) + { + var alternatePath = FrontendManager.VirtualPathBuilder.GetVirtualPath(controllerType); + var baseUrl = "~/" + alternatePath + contentPath; + + if (HostingEnvironment.VirtualPathProvider == null || HostingEnvironment.VirtualPathProvider.FileExists(baseUrl)) + { + alternatePath = UrlTransformations.AppendParam(baseUrl, paramaterName, packageName); + return alternatePath; + } + } + + return string.Empty; + } + + internal static string AppendVersion(string contentPath) + { + if (contentPath.EndsWith(".js") || contentPath.Contains(".js?")) + { + var hash = VirtualPathManager.GetFileHash(contentPath, null); + if (hash != null) + { + var bytes = Encoding.UTF8.GetBytes(hash); + var base64version = Convert.ToBase64String(bytes); + contentPath = UrlTransformations.AppendParam(contentPath, VersionQueryParam, base64version); + } + } + + return contentPath; + } + + private const string VersionQueryParam = "v"; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewModels/CustomTaxonomyViewModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewModels/CustomTaxonomyViewModel.cs new file mode 100644 index 000000000..55982a9fa --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewModels/CustomTaxonomyViewModel.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using Telerik.Sitefinity.Taxonomies.Model; + +namespace Telerik.Sitefinity.Frontend.Mvc.Helpers.ViewModels +{ + /// + /// This class represents the view model for the custom taxonomy fields. + /// + public class CustomTaxonomyViewModel + { + /// + /// Gets or sets the name of the custom field. + /// + /// + /// The name. + /// + public string Name { get; set; } + + /// + /// Gets or sets the title of the taxonomy. + /// + /// + /// The title. + /// + public string Title { get; set; } + + /// + /// Gets or sets the type of the taxonomy. + /// + /// + /// The type of the taxonomy. + /// + public TaxonomyType TaxonomyType { get; set; } + + /// + /// Gets or sets the identifier of the taxonomy. + /// + /// + /// The identifier. + /// + public Guid Id { get; set; } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewModels/PagerViewModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewModels/PagerViewModel.cs index 8980512f1..8ee4d93cf 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewModels/PagerViewModel.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewModels/PagerViewModel.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Text; +using Telerik.Sitefinity.Web.UI; namespace Telerik.Sitefinity.Frontend.Mvc.Helpers.ViewModels { @@ -17,10 +18,23 @@ public class PagerViewModel /// The total pages count. /// The redirect URL template. public PagerViewModel(int currentPage, int totalPagesCount, string redirectUrlTemplate) + : this(currentPage, totalPagesCount, redirectUrlTemplate, 10) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The current page. + /// The total pages count. + /// The redirect URL template. + /// The amount of page nodes to render + public PagerViewModel(int currentPage, int totalPagesCount, string redirectUrlTemplate, int displayCount) { this.CurrentPage = currentPage; this.TotalPagesCount = totalPagesCount; this.RedirectUrlTemplate = redirectUrlTemplate; + this.DisplayCount = displayCount; } /// @@ -39,6 +53,14 @@ public PagerViewModel(int currentPage, int totalPagesCount, string redirectUrlTe /// public int TotalPagesCount { get; set; } + /// + /// Gets or sets the total item count to render. + /// + /// + /// The total numbers that will render. + /// + public int DisplayCount { get; set; } + /// /// Gets or sets the redirect URL template. /// @@ -46,5 +68,40 @@ public PagerViewModel(int currentPage, int totalPagesCount, string redirectUrlTe /// The redirect URL template. /// public string RedirectUrlTemplate { get; set; } + + /// + /// Gets or sets the pager node + /// + /// + /// The amount of nodes to render + /// + public IList PagerNodes + { + get + { + if (this.pagerNodes == null) + this.pagerNodes = new List(); + + return this.pagerNodes; + } + } + + /// + /// Gets or sets the previous node + /// + /// + /// The previous page + /// + public Pager.PagerNumericItem PreviousNode { get; set; } + + /// + /// Gets or sets the next node + /// + /// + /// The next page + /// + public Pager.PagerNumericItem NextNode { get; set; } + + private IList pagerNodes; } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewSelectorHelpers.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewSelectorHelpers.cs index 8799792e2..3c50bcaab 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewSelectorHelpers.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewSelectorHelpers.cs @@ -28,10 +28,64 @@ public static IEnumerable GetViewNames(this HtmlHelper helper, string co throw new ArgumentException("Controller cannot be resolved."); } + if (controller.RouteData != null && controller.RouteData.Values["controller"] as string != null) + { + controller.RouteData.Values["controller"] = controllerName; + } var regex = new Regex(templateNamePattern, RegexOptions.IgnoreCase); var views = controller.GetViews().Where(view => Regex.IsMatch(view, templateNamePattern)).Select(view => regex.Match(view).Groups["viewName"].Value); return views; } + + /// + /// Gets a collection with the view names which match the given pattern. + /// + /// The helper. + /// The controller. + /// The template name pattern. + /// Names of the views that match provided pattern. + /// Controller cannot be resolved. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "helper")] + public static IEnumerable GetViewNames(this HtmlHelper helper, Controller controller, string templateNamePattern) + { + return ViewSelectorHelpers.GetViewNames(helper, controller, templateNamePattern, null); + } + + /// + /// Gets a collection with the view names which match the given pattern. + /// + /// The helper. + /// The controller. + /// The template name pattern. + /// The name of dynamic module. + /// Names of the views that match provided pattern. + /// Controller cannot be resolved. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "helper")] + public static IEnumerable GetViewNames(this HtmlHelper helper, Controller controller, string templateNamePattern, string moduleName) + { + if (controller == null) + { + throw new ArgumentNullException("controller"); + } + + var regex = new Regex(templateNamePattern, RegexOptions.IgnoreCase); + var views = controller.GetViews(null, moduleName).Where(view => Regex.IsMatch(view, templateNamePattern)).Select(view => regex.Match(view).Groups["viewName"].Value); + + return views; + } + + /// + /// Splits the camel case. + /// + /// The input. + /// + public static string SplitCamelCase(this string input) + { + var inputWithSpaces = Regex.Replace(input, "([A-Z])", " $1", RegexOptions.Compiled).Trim(); + var capitalizeOnlyFirstLater = inputWithSpaces.First().ToString().ToUpper() + inputWithSpaces.Substring(1).ToLower(); + + return capitalizeOnlyFirstLater; + } } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Attributes/EmailAddressAttribute.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Attributes/EmailAddressAttribute.cs new file mode 100644 index 000000000..3979f9a5e --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Attributes/EmailAddressAttribute.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text.RegularExpressions; +using System.Web.Mvc; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Attributes +{ + /// + /// This class represents and should be used when one needs to validate email property. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)] + public sealed class EmailAddressAttribute : ValidationAttribute, IClientValidatable + { + public string RegexPattern + { + get + { + return this.regexPattern ?? EmailAddressAttribute.DefaultRegexPattern; + } + + set + { + this.regexPattern = value; + } + } + + /// + public IEnumerable GetClientValidationRules(ModelMetadata metadata, ControllerContext context) + { + yield return new ModelClientValidationRule + { + ValidationType = "email", + ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()) + }; + } + + /// + public override bool IsValid(object value) + { + if (value != null) + { + var stringValue = value as string; + if (!string.IsNullOrEmpty(stringValue)) + { + var regex = new Regex(this.RegexPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase); + if (regex.Match(stringValue).Success) + { + return true; + } + } + } + + return false; + } + + /// + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + return this.IsValid(value) ? ValidationResult.Success : new ValidationResult(this.ErrorMessage); + } + + private const string DefaultRegexPattern = @"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$"; + private string regexPattern; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Attributes/RequiredIfExistAttribute.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Attributes/RequiredIfExistAttribute.cs new file mode 100644 index 000000000..9d3f48b4e --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Attributes/RequiredIfExistAttribute.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Reflection; +using System.Text; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Attributes +{ + /// + /// This class represents and should be used when one needs to validate property only if another property has value. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes")] + [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] + public class RequiredIfExistAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute + { + /// + /// Initializes a new instance of the class. + /// + public RequiredIfExistAttribute(string dependentPropertyName) + : base() + { + this.innerAttribute = new RequiredAttribute(); + this.dependentPropertyName = dependentPropertyName; + } + + /// + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + PropertyInfo dependentProperty = validationContext.ObjectInstance.GetType().GetProperty(this.dependentPropertyName); + + if (dependentProperty != null) + { + var dependentPropertyValue = dependentProperty.GetValue(validationContext.ObjectInstance, null); + + if (dependentPropertyValue != null) + { + if (!this.innerAttribute.IsValid(value)) + return new ValidationResult(this.ErrorMessage); + } + } + + return ValidationResult.Success; + } + + private string dependentPropertyName; + private RequiredAttribute innerAttribute; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Compilation/CompilationPerformanceRazorView.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Compilation/CompilationPerformanceRazorView.cs new file mode 100644 index 000000000..b94fcb6e1 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Compilation/CompilationPerformanceRazorView.cs @@ -0,0 +1,306 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Web; +using System.Web.Caching; +using System.Web.Compilation; +using System.Web.Hosting; +using System.Web.Mvc; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.DynamicModules.Builder; +using Telerik.Sitefinity.DynamicModules.Builder.Model; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; +using Telerik.Sitefinity.Frontend.Mvc.Models; +using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.HealthMonitoring; +using Telerik.Sitefinity.Modules.Forms; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Mvc.Store; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Compilation +{ + /// + /// This class represents a which allows measurement of its compilation performance. + /// + /// + internal class CompilationPerformanceRazorView : RazorView + { + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The controller context. + /// The view path. + /// The layout or master page. + /// A value that indicates whether view start files should be executed before the view. + /// The set of extensions that will be used when looking up view start files. + public CompilationPerformanceRazorView(ControllerContext controllerContext, string viewPath, string layoutPath, bool runViewStartPages, IEnumerable viewStartFileExtensions) : + this(controllerContext, viewPath, layoutPath, runViewStartPages, viewStartFileExtensions, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The controller context. + /// The view path. + /// The layout or master page. + /// A value that indicates whether view start files should be executed before the view. + /// The set of extensions that will be used when looking up view start files. + /// The view page activator. + public CompilationPerformanceRazorView(ControllerContext controllerContext, string viewPath, string layoutPath, bool runViewStartPages, IEnumerable viewStartFileExtensions, IViewPageActivator viewPageActivator) + : base(controllerContext, viewPath, layoutPath, runViewStartPages, viewStartFileExtensions, viewPageActivator) + { + this.controllerContext = controllerContext; + this.viewPageActivator = viewPageActivator; + } + + #endregion + + #region Public Methods + + /// + /// Renders the specified view context by using the specified the writer object. + /// + /// Information related to rendering a view, such as view data, temporary data, and form context. + /// The writer object. + public override void Render(ViewContext viewContext, TextWriter writer) + { + if (!this.ShouldMeasurePerformance(this.ViewPath) || !this.RenderWithPerformanceMeasurement(viewContext, writer)) + base.Render(viewContext, writer); + } + + #endregion + + #region Private Methods + + private bool RenderWithPerformanceMeasurement(ViewContext viewContext, TextWriter writer) + { + if (viewContext == null) + return false; + + var region = this.GetMethodPerformanceRegion(viewContext); + if (region == null) + return false; + + Type compiledType = null; + try + { + compiledType = System.Web.Compilation.BuildManager.GetCompiledType(this.ViewPath); + } + finally + { + region.Dispose(); + } + + if (compiledType == null) + return false; + + var obj = this.viewPageActivator.Create(this.controllerContext, compiledType); + if (obj == null) + return false; + + this.RenderView(viewContext, writer, obj); + + return true; + } + + private bool ShouldMeasurePerformance(string virtualPath) + { + if (virtualPath == null || HttpContext.Current == null) + return false; + + return HostingEnvironment.VirtualPathProvider.FileExists(virtualPath) && BuildManager.GetCachedBuildDependencySet(HttpContext.Current, virtualPath) == null; + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The type of the thrown exception is not of interest in this scenario. We are only interested in marking the start of the performance measurement as failed.")] + private IDisposable GetMethodPerformanceRegion(ViewContext viewContext) + { + if (SystemManager.HttpContextItems == null || !SystemManager.HttpContextItems.Contains(SiteMapBase.CurrentNodeKey) || !(SystemManager.HttpContextItems[SiteMapBase.CurrentNodeKey] is PageSiteNode)) + return null; + + var pageNode = (PageSiteNode)SystemManager.HttpContextItems[SiteMapBase.CurrentNodeKey]; + + try + { + int slashIndex = this.ViewPath.LastIndexOf('/'); + var fullViewName = this.ViewPath.Substring(slashIndex + 1); + + int hashIndex = fullViewName.IndexOf('#'); + var viewName = hashIndex < 0 ? fullViewName : fullViewName.Substring(0, hashIndex); + + var actionName = (string)viewContext.RequestContext.RouteData.Values["action"]; + var virtualPath = hashIndex < 0 ? this.ViewPath : this.ViewPath.Substring(0, slashIndex + hashIndex + 1); + var source = this.GetSource(this.ViewPath); + var packageManager = new PackageManager(); + var resourcePackage = packageManager.GetCurrentPackage(); + var controllerName = viewContext.Controller.GetType().FullName; + var widgetName = this.GetWidgetName(this.controllerContext); + if (this.ViewPath.StartsWith(CompilationPerformanceRazorView.FormsResolverPath, StringComparison.OrdinalIgnoreCase) && viewName.EndsWith(CompilationPerformanceRazorView.RazorViewSuffix, StringComparison.OrdinalIgnoreCase)) + { + Guid formId; + var formIdString = viewName.Left(viewName.Length - CompilationPerformanceRazorView.RazorViewSuffix.Length); + if (Guid.TryParse(formIdString, out formId)) + { + var form = FormsManager.GetManager().GetForms().FirstOrDefault(f => f.Id == formId); + if (form != null) + { + viewName = form.Title + " (" + formIdString + ")"; + } + } + } + + var isBackendRequest = bool.Parse(SystemManager.CurrentHttpContext.Items[SystemManager.IsBackendRequestKey].ToString()); + var rootNodeId = isBackendRequest ? SiteInitializer.BackendRootNodeId : SiteInitializer.CurrentFrontendRootNodeId; + var siteId = SystemManager.CurrentContext.CurrentSite.Id; + var machineName = Environment.MachineName; + + var key = string.Format("Compile view \"{0}\" of controller \"{1}\"", fullViewName, controllerName); + var data = new Dictionary() + { + { CompilationPerformanceRazorView.ViewNameKey, viewName }, + { CompilationPerformanceRazorView.PageIdKey, pageNode.PageId }, + { CompilationPerformanceRazorView.PageTitleKey, pageNode.Title }, + { CompilationPerformanceRazorView.ResourcePackageKey, resourcePackage ?? string.Empty }, + { CompilationPerformanceRazorView.ActionNameKey, actionName }, + { CompilationPerformanceRazorView.ControllerNameKey, controllerName }, + { CompilationPerformanceRazorView.WidgetNameKey, widgetName ?? string.Empty }, + { CompilationPerformanceRazorView.VirtualPathKey, this.ViewPath }, + { CompilationPerformanceRazorView.MachineNameKey, machineName }, + { CompilationPerformanceRazorView.SiteIdKey, siteId }, + { CompilationPerformanceRazorView.RootNodeIdKey, rootNodeId }, + { CompilationPerformanceRazorView.SourceKey, virtualPath }, + { CompilationPerformanceRazorView.ViewSourceKey, source } + }; + + return (IDisposable)Activator.CreateInstance(CompilationPerformanceRazorView.methodPerformanceRegionType, new object[] { key, CompilationPerformanceRazorView.ViewCompilationCategory, data }); + } + catch + { + return null; + } + } + + private string GetSource(string viewPath) + { + var cacheDep = HostingEnvironment.VirtualPathProvider.GetCacheDependency(viewPath, new object[0], DateTime.UtcNow); + + // We are looking for both public and non-public method GetFileDependencies because of differences in the .NET Framework versions + var getFileDependencies = typeof(CacheDependency).GetMethod("GetFileDependencies", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); + var getDependencyArray = typeof(AggregateCacheDependency).GetMethod("GetDependencyArray", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); + + while (cacheDep is AggregateCacheDependency) + { + var deps = getDependencyArray.Invoke(cacheDep, null) as CacheDependency[]; + if (deps == null || deps.Length == 0) + break; + + cacheDep = deps[deps.Length - 1]; + } + + if (cacheDep is Abstractions.VirtualPath.ControlPresentationCacheDependency) + { + var title = this.ExtractTemplateTitle((Abstractions.VirtualPath.ControlPresentationCacheDependency)cacheDep); + if (title != null) + { + return "Widget template: " + title + " (DB)"; + } + } + + var files = getFileDependencies.Invoke(cacheDep, null) as string[]; + if (files != null && files.Length > 0) + return files[files.Length - 1].Replace(HostingEnvironment.ApplicationPhysicalPath, "~\\"); + else + return viewPath; + } + + private string ExtractTemplateTitle(Abstractions.VirtualPath.ControlPresentationCacheDependency cacheDep) + { + var cacheDepId = cacheDep.GetUniqueID().Right(cacheDep.GetUniqueID().Length - cacheDep.UniquePrefix.Length - 1); + Guid id; + if (!Guid.TryParse(cacheDepId, out id)) + return null; + + var manager = PageManager.GetManager(); + string title; + using (new Data.ElevatedModeRegion(manager)) + { + title = manager.GetPresentationItem(id).Name; + } + + return title; + } + + private string GetWidgetName(ControllerContext context) + { + var controllerType = context.Controller.GetType(); + + // Check in controller store + var controllerInfo = ControllerStore.Controllers() + .FirstOrDefault(c => c.ControllerType == controllerType); + + if (controllerInfo != null && !controllerInfo.DefaultToolboxItemTitle.IsNullOrEmpty()) + return controllerInfo.DefaultToolboxItemTitle; + + // Check for dynamic type + var modelProperty = controllerType.GetProperty("Model"); + if (modelProperty != null) + { + var model = modelProperty.GetValue(context.Controller) as ContentModelBase; + if (model != null) + { + var contentType = model.ContentType; + + var dynamicType = ModuleBuilderManager.GetModules().GetTypeByFullName(contentType.FullName); + if (dynamicType != null) + return dynamicType.DisplayName; + } + } + + if (this.ViewPath.StartsWith(CompilationPerformanceRazorView.LayoutVirtualPathBeginning, StringComparison.OrdinalIgnoreCase)) + return CompilationPerformanceRazorView.Layout; + + var controllerName = FrontendManager.ControllerFactory.GetControllerName(controllerType); + + return controllerName; + } + + #endregion + + #region Fields and Constants + + private ControllerContext controllerContext; + private IViewPageActivator viewPageActivator; + + internal const string ViewCompilationCategory = "ViewCompilation"; + + internal const string ViewNameKey = "View"; + internal const string PageIdKey = "PageId"; + internal const string PageTitleKey = "PageTitle"; + internal const string ResourcePackageKey = "ResourcePackage"; + internal const string ActionNameKey = "Action"; + internal const string ControllerNameKey = "Controller"; + internal const string WidgetNameKey = "Widget"; + internal const string VirtualPathKey = "VirtualPath"; + internal const string MachineNameKey = "MachineName"; + internal const string SiteIdKey = "SiteId"; + internal const string RootNodeIdKey = "RootNodeId"; + internal const string SourceKey = "Source"; + internal const string ViewSourceKey = "ViewSource"; + + private const string LayoutVirtualPathBeginning = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/Mvc/Views/Layouts"; + private const string Layout = "Layout"; + private const string FormsResolverPath = "~/Mvc-Form-View/"; + private const string RazorViewSuffix = ".cshtml"; + + private static Type methodPerformanceRegionType = Assembly.GetAssembly(typeof(SystemManager)).GetType("Telerik.Sitefinity.HealthMonitoring.MethodPerformanceRegion", false); + + #endregion + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Compilation/CompilationPerformanceRazorViewEngine.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Compilation/CompilationPerformanceRazorViewEngine.cs new file mode 100644 index 000000000..7a1352bc0 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Compilation/CompilationPerformanceRazorViewEngine.cs @@ -0,0 +1,76 @@ +using System.Reflection; +using System.Web.Mvc; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Compilation +{ + /// + /// This class represents a which creates objects allowing measurement of their compilation performance. + /// + /// + internal class CompilationPerformanceRazorViewEngine : RazorViewEngine + { + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + public CompilationPerformanceRazorViewEngine() + : this(null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The page activator. + public CompilationPerformanceRazorViewEngine(IViewPageActivator pageActivator) + : base(pageActivator) + { + } + + #endregion + + #region Protected Methods + + /// + /// Creates a view by using the specified controller context and the paths of the view and master view. + /// + /// The controller context. + /// The path to the view. + /// The path to the master view. + /// + /// The view. + /// + protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) + { + var view = new CompilationPerformanceRazorView(controllerContext, viewPath, masterPath, true, this.FileExtensions, this.ViewPageActivator); + displayModeProviderProperty.SetValue(view, this.DisplayModeProvider); + + return view; + } + + /// + /// Creates a partial view using the specified controller context and partial path. + /// + /// The controller context. + /// The path to the partial view. + /// + /// The partial view. + /// + protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) + { + var view = new CompilationPerformanceRazorView(controllerContext, partialPath, null, false, this.FileExtensions, this.ViewPageActivator); + displayModeProviderProperty.SetValue(view, this.DisplayModeProvider); + + return view; + } + + #endregion + + #region Fields + + private static PropertyInfo displayModeProviderProperty = typeof(RazorView).GetProperty("DisplayModeProvider", BindingFlags.Instance | BindingFlags.NonPublic); + + #endregion + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/CacheDependentAttribute.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/CacheDependentAttribute.cs index bf29dff94..277634a2f 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/CacheDependentAttribute.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/CacheDependentAttribute.cs @@ -3,6 +3,7 @@ using System.Web.Hosting; using System.Web.Mvc; using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Web; namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes { @@ -22,19 +23,20 @@ public override void OnResultExecuted(ResultExecutedContext filterContext) { base.OnResultExecuted(filterContext); - if (SystemManager.CurrentHttpContext != null && SystemManager.CurrentHttpContext.Response != null) + var context = filterContext.HttpContext; + if (context != null && context.Response != null && context.Items[PageRouteHandler.AddCacheDependencies] != null) { var viewResult = filterContext.Result as ViewResultBase; - if (viewResult != null) + if (viewResult != null && viewResult.View != null) { - var builtView = viewResult.View as BuildManagerCompiledView; - if (builtView != null) + var viewPath = FrontendManager.VirtualPathBuilder.GetViewPath(viewResult.View); + if (!viewPath.IsNullOrEmpty()) { - var cacheDependency = this.GetCacheDependency(builtView.ViewPath); + var cacheDependency = this.GetCacheDependency(viewPath); if (cacheDependency != null) { - SystemManager.CurrentHttpContext.Response.AddCacheDependency(cacheDependency); + context.Response.AddCacheDependency(cacheDependency); } } } @@ -50,7 +52,8 @@ protected virtual CacheDependency GetCacheDependency(string virtualPath) { if (HostingEnvironment.VirtualPathProvider != null) { - return HostingEnvironment.VirtualPathProvider.GetCacheDependency(virtualPath, null, DateTime.UtcNow); + // Sitefinity 8.1 and older throw exception if the second argument of this method is null so we pass an empty array. + return HostingEnvironment.VirtualPathProvider.GetCacheDependency(virtualPath, new string[0], DateTime.UtcNow); } return null; diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/ControllerContainerAttribute.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/ControllerContainerAttribute.cs index a3450bf77..892e95b00 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/ControllerContainerAttribute.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/ControllerContainerAttribute.cs @@ -1,26 +1,77 @@ -using System; - -namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes -{ - /// - /// This attribute is used to mark assemblies that may contain types. - /// - [AttributeUsage(AttributeTargets.All)] - public class ControllerContainerAttribute : Attribute - { - public ControllerContainerAttribute() - : this(null, null) - { - } - - public ControllerContainerAttribute(Type initializationType, string initializationMethodName) - { - this.InitializationType = initializationType; - this.InitializationMethod = initializationMethodName; - } - - public Type InitializationType { get; private set; } - - public string InitializationMethod { get; private set; } - } -} +using System; +using System.Web.Mvc; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes +{ + /// + /// This attribute is used to mark assemblies that may contain types. + /// + [AttributeUsage(AttributeTargets.Assembly)] + public class ControllerContainerAttribute : Attribute + { + /// + /// Initializes a new instance of the class. + /// + public ControllerContainerAttribute() + : this(null, null, null, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// Type containing the initialization method. + /// Name of the initialization method. + public ControllerContainerAttribute(Type initializationType, string initializationMethodName) + : this(initializationType, initializationMethodName, null, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// Type containing the initialization method. + /// Name of the initialization method. + /// Type containing the uninitialization method. + /// Name of the uninitialization method. + public ControllerContainerAttribute(Type initializationType, string initializationMethodName, Type uninitializationType, string uninitializationMethodName) + { + this.InitializationType = initializationType; + this.InitializationMethod = initializationMethodName; + this.UninitializationType = uninitializationType; + this.UninitializationMethod = uninitializationMethodName; + } + + /// + /// Gets the type containing the initialization method. + /// + /// + /// The type containing the initialization method. + /// + public Type InitializationType { get; private set; } + + /// + /// Gets the initialization method name. + /// + /// + /// The name of the initialization method. + /// + public string InitializationMethod { get; private set; } + + /// + /// Gets the type containing the uninitialization method. + /// + /// + /// The type containing the uninitialization method. + /// + public Type UninitializationType { get; private set; } + + /// + /// Gets the uninitialization method name. + /// + /// + /// The name of the uninitialization method. + /// + public string UninitializationMethod { get; private set; } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/ControllerMetadataAttribute.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/ControllerMetadataAttribute.cs new file mode 100644 index 000000000..59a1d0526 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/ControllerMetadataAttribute.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes +{ + /// + /// Controller attribute for determining whether the controller is templatable control + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes"), AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] + public class ControllerMetadataAttribute : Attribute + { + /// + /// Initializes a new instance of the class. + /// + public ControllerMetadataAttribute() + { + this.IsTemplatableControl = true; + } + + /// + /// Gets or sets a value indicating whether the controller is templatable control + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Templatable")] + public bool IsTemplatableControl { get; set; } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/ResourcePackageAttribute.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/ResourcePackageAttribute.cs new file mode 100644 index 000000000..fb283d9c6 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/ResourcePackageAttribute.cs @@ -0,0 +1,36 @@ +using System; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes +{ + /// + /// This attribute is used to mark assemblies that contain a precompiled resource package. + /// + [AttributeUsage(AttributeTargets.Assembly)] + public sealed class ResourcePackageAttribute : Attribute + { + /// + /// Initializes a new instance of the class. + /// + public ResourcePackageAttribute() + : this(string.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The name of the package. + public ResourcePackageAttribute(string name) + { + this.Name = name; + } + + /// + /// Gets the name of the package. + /// + /// + /// The name. + /// + public string Name { get; private set; } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ContentBaseController.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ContentBaseController.cs new file mode 100644 index 000000000..7220e04a4 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ContentBaseController.cs @@ -0,0 +1,252 @@ +using System.Collections.Generic; +using System.ComponentModel; +using System.Web.Mvc; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.Data; +using Telerik.Sitefinity.DynamicModules; +using Telerik.Sitefinity.Model; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Mvc; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Services.Configuration; +using Telerik.Sitefinity.Web; +using Telerik.Sitefinity.ContentLocations; +using Telerik.Sitefinity.Lifecycle; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers +{ + /// + /// This class represents the base controller of content widgets. + /// + public abstract class ContentBaseController : Controller + { + #region Properties + + /// + /// Gets the metadata container.Title for search engines + /// + /// + /// + /// The metadata container. + /// + [TypeConverter(typeof(ExpandableObjectConverter))] + public virtual MetadataModel MetadataFields + { + get + { + if (this.metadata == null) + { + this.metadata = new MetadataModel(); + this.metadata.OpenGraphType = PageHelper.OpenGraphTypes.Website; + this.metadata.PageTitleMode = Telerik.Sitefinity.Mvc.ControllerActionInvoker.PageTitleModes.Replace; + } + + return this.metadata; + } + set + { + metadata = value; + } + } + + #endregion + + #region Methods + + /// + /// Populates the viewbag with values for metadata properties. + /// + /// The item. + protected void InitializeMetadataDetailsViewBag(IDataItem item) + { + if (this.IsDesignMode && !this.IsPreviewMode) + { + return; + } + + string parentMainValue = string.Empty; + var seoAndOpenGraphConfig = this.GetSeoAndOpenGraphConfig(); + MetadataModel metadataProperties = new MetadataModel(); + + metadataProperties.SEOEnabled = seoAndOpenGraphConfig.EnabledSEO; + metadataProperties.OpenGraphEnabled = seoAndOpenGraphConfig.EnabledOpenGraph; + metadataProperties.SEOEnabledPerWidget = this.MetadataFields.SEOEnabled; + metadataProperties.OpenGraphEnabledPerWidget = this.MetadataFields.OpenGraphEnabled; + bool isSeoEnabled = metadataProperties.SEOEnabled && metadataProperties.SEOEnabledPerWidget; + bool isOpenGraphEnabled = metadataProperties.OpenGraphEnabled && metadataProperties.OpenGraphEnabledPerWidget; + + if (isSeoEnabled) + { + metadataProperties.MetaTitle = this.GetTitleProperty(item, new[] { this.MetadataFields.MetaTitle, PageHelper.MetaDataProperties.MetaTitle }); + metadataProperties.MetaDescription = this.GetDescriptionProperty(item, new[] { this.MetadataFields.MetaDescription, PageHelper.MetaDataProperties.MetaDescription }); + } + + if (isOpenGraphEnabled) + { + metadataProperties.OpenGraphTitle = this.GetTitleProperty(item, new[] { this.MetadataFields.OpenGraphTitle, PageHelper.MetaDataProperties.OpenGraphTitle, this.MetadataFields.MetaTitle, PageHelper.MetaDataProperties.MetaTitle }); + metadataProperties.OpenGraphDescription = this.GetDescriptionProperty(item, new[] { this.MetadataFields.OpenGraphDescription, PageHelper.MetaDataProperties.OpenGraphDescription, this.MetadataFields.MetaDescription, PageHelper.MetaDataProperties.MetaDescription }); + metadataProperties.Url = this.GetDefaultCanonicalUrl(item); + metadataProperties.OpenGraphType = this.MetadataFields.OpenGraphType; + metadataProperties.OpenGraphImage = PageHelper.GetFieldValue(item, new[] { this.MetadataFields.OpenGraphImage, PageHelper.MetaDataProperties.OpenGraphImage }); + metadataProperties.OpenGraphVideo = PageHelper.GetFieldValue(item, new[] { this.MetadataFields.OpenGraphVideo, PageHelper.MetaDataProperties.OpenGraphVideo }); + metadataProperties.SiteName = SystemManager.CurrentContext.CurrentSite.Name; + } + + if (isSeoEnabled || isOpenGraphEnabled) + { + metadataProperties.PageTitleMode = this.MetadataFields.PageTitleMode; + + if (this.MetadataFields.PageTitleMode == Telerik.Sitefinity.Mvc.ControllerActionInvoker.PageTitleModes.Hierarchy && typeof(IDynamicContentWidget).IsAssignableFrom(this.GetType())) + { + parentMainValue = this.GetParentMainFiledValue(item); + if (!string.IsNullOrEmpty(parentMainValue)) + { + this.ViewBag.ParentMainValue = parentMainValue; + } + } + } + + this.ViewBag.Metadata = metadataProperties; + } + + /// + /// Determines whether the page is in design mode. + /// + protected virtual bool IsDesignMode + { + get + { + return SystemManager.IsDesignMode; + } + } + + /// + /// Gets a value indicating whether the current request is for page in preview mode. + /// + protected virtual bool IsPreviewMode + { + get + { + return SystemManager.IsPreviewMode; + } + } + + /// + /// Gets the item default location. + /// + /// The item. + /// + /// The item default location. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "The url is needed here as a string.")] + internal virtual string GetDefaultCanonicalUrl(IDataItem item) + { + IManager manager = null; + if (!ManagerBase.TryGetMappedManager(item.GetType(), item.GetProviderName(), out manager)) + return null; + + var locationsService = SystemManager.GetContentLocationService(); + if (item is ILifecycleDataItemGeneric lifecycleDataItem && + lifecycleDataItem.Status != GenericContent.Model.ContentLifecycleStatus.Master && + manager is ILifecycleManager lifecycleManager) + { + item = lifecycleManager.Lifecycle.GetMaster(lifecycleDataItem); + } + + var location = locationsService.GetItemDefaultLocation(item); + if (location != null) + { + return location.ItemAbsoluteUrl; + } + + var page = this.HttpContext.CurrentHandler.GetPageHandler(); + var pageNode = SiteMapBase.GetActualCurrentNode(); + var canonicalUrl = page.GetCanonicalUrlForPage(pageNode); + + return canonicalUrl; + } + + /// + /// Adds the canonical tag in the page headers HTML tag, like . + /// + /// The page. + /// The item. + protected void AddCanonicalUrlTagIfEnabled(System.Web.UI.Page page, IDataItem item) + { + var contentView = this as IContentLocatableView; + if (contentView != null) + { + var defaultCanonicalUrl = this.GetDefaultCanonicalUrl(item); + contentView.AddCanonicalUrlTagIfEnabled(page, defaultCanonicalUrl); + } + } + + internal virtual SeoAndOpenGraphElement GetSeoAndOpenGraphConfig() + { + return Config.Get().SeoAndOpenGraphConfig; + } + + private string GetParentMainFiledValue(IDataItem item) + { + string parentMainValue = string.Empty; + var property = TypeDescriptor.GetProperties(item)["ParentItem"]; + if (property != null) + { + var parent = property.GetValue(item); + parentMainValue = this.GetParentMainValueFromProperty(parent); + + var parentProperty = TypeDescriptor.GetProperties(parent)["ParentItem"]; + + if (parentProperty != null) + { + var grandParent = property.GetValue(parent); + parentMainValue = parentMainValue + " - " + this.GetParentMainValueFromProperty(grandParent); + } + } + + return parentMainValue; + } + + private string GetParentMainValueFromProperty(object itemValue) + { + var parentMainField = this.GetDynamicContentType().ParentModuleType.MainShortTextFieldName; + string[] field = { parentMainField }; + + return PageHelper.GetFieldValue(itemValue, field); + } + + private string GetTitleProperty(object detailItem, string[] propertyNames) + { + var fields = new List(propertyNames); + + if (typeof(IDynamicContentWidget).IsAssignableFrom(this.GetType())) + { + var dynamicType = this.GetDynamicContentType(); + var title = dynamicType == null ? PageHelper.MetaDataProperties.Title : dynamicType.MainShortTextFieldName; + fields.Add(title); + } + else + { + fields.Add(PageHelper.MetaDataProperties.Title); + } + + return PageHelper.GetFieldValue(detailItem, fields.ToArray()); + } + + private string GetDescriptionProperty(object detailItem, string[] propertyNames) + { + var fields = new List(propertyNames); + fields.Add(PageHelper.MetaDataProperties.Description); + + return PageHelper.GetFieldValue(detailItem, fields.ToArray()); + } + + #endregion + + #region Fields and constants + + private MetadataModel metadata; + + #endregion + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerContainerInitializer.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerContainerInitializer.cs index 2a2139d41..f7b33cb2d 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerContainerInitializer.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerContainerInitializer.cs @@ -1,295 +1,660 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Web.Hosting; -using System.Web.Mvc; -using System.Web.Routing; -using Telerik.Microsoft.Practices.Unity; -using Telerik.Sitefinity.Abstractions; -using Telerik.Sitefinity.Abstractions.VirtualPath; -using Telerik.Sitefinity.Configuration; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing; -using Telerik.Sitefinity.Frontend.Resources; -using Telerik.Sitefinity.Frontend.Resources.Resolvers; -using Telerik.Sitefinity.Localization; -using Telerik.Sitefinity.Mvc; -using Telerik.Sitefinity.Mvc.Store; -using Telerik.Sitefinity.Services; - -namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers -{ - /// - /// This class contains logic for locating and initializing controllers. - /// - public class ControllerContainerInitializer - { - #region Public members - - /// - /// Initializes the controllers that are available to the web application. - /// - public virtual void Initialize() - { - GlobalFilters.Filters.Add(new CacheDependentAttribute()); - - var assemblies = this.RetrieveAssemblies(); - - this.RegisterVirtualPaths(assemblies); - - var controllerTypes = this.GetControllers(assemblies); - this.InitializeControllers(controllerTypes); - - this.InitializeCustomRouting(); - } - - #endregion - - #region Protected members - - /// - /// Gets the assemblies that are marked as controller containers with the attribute. - /// - protected virtual IEnumerable RetrieveAssemblies() - { - var assemblyFileNames = this.RetrieveAssembliesFileNames().ToArray(); - var result = new List(); - - foreach (var assemblyFileName in assemblyFileNames) - { - if (this.IsControllerContainer(assemblyFileName)) - { - var assembly = this.LoadAssembly(assemblyFileName); - this.InitializeControllerContainer(assembly); - result.Add(assembly); - } - } - - return result; - } - - /// - /// Executes the initialization method specified in the attribute. - /// - /// - protected virtual void InitializeControllerContainer(Assembly container) - { - if (container == null) - throw new ArgumentNullException("container"); - - var containerAttribute = container.GetCustomAttributes(false).Single(attr => attr.GetType().AssemblyQualifiedName == typeof(ControllerContainerAttribute).AssemblyQualifiedName) as ControllerContainerAttribute; - - if (containerAttribute.InitializationType == null || containerAttribute.InitializationMethod.IsNullOrWhitespace()) - return; - - var initializationMethod = containerAttribute.InitializationType.GetMethod(containerAttribute.InitializationMethod); - initializationMethod.Invoke(null, null); - } - - /// - /// Loads the assembly file into the current application domain. - /// - /// Name of the assembly file. - /// The loaded assembly - protected virtual Assembly LoadAssembly(string assemblyFileName) - { - return Assembly.LoadFrom(assemblyFileName); - } - - /// - /// Registers virtual paths for the given . - /// - /// The assemblies. - protected virtual void RegisterVirtualPaths(IEnumerable assemblies) - { - foreach (var assembly in assemblies) - { - this.RegisterAssemblyPaths(assembly); - } - } - - /// - /// Gets the controllers from the given . - /// - /// The assemblies. - /// - protected virtual IEnumerable GetControllers(IEnumerable assemblies) - { - return assemblies - .SelectMany(asm => asm.GetExportedTypes().Where(FrontendManager.ControllerFactory.IsController)) - .ToArray(); - } - - /// - /// Initializes the specified by ensuring they have their proper registrations in the toolbox and that the controller factory will be able to resolve them. - /// - /// The controllers. - protected virtual void InitializeControllers(IEnumerable controllers) - { - this.RegisterControllerFactory(); - this.RemoveSitefinityViewEngine(); - this.ReplaceControllerFactory(); - - foreach (var controller in controllers) - { - this.RegisterController(controller); - } - } - - /// - /// Registers - /// - protected virtual void RegisterControllerFactory() - { - ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); - } - - /// - /// Registers the controller so its views and resources can be resolved. - /// - /// The controller. - protected virtual void RegisterController(Type controller) - { - var controllerStore = new ControllerStore(); - var configManager = ConfigManager.GetManager(); - - using (var modeRegion = new ElevatedConfigModeRegion()) - { - this.RegisterStringResources(controller); - controllerStore.AddController(controller, configManager); - } - } - - /// - /// Gets the assemblies file names that will be inspected for controllers. - /// - protected virtual IEnumerable RetrieveAssembliesFileNames() - { - var controllerAssemblyPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "bin"); - return Directory.EnumerateFiles(controllerAssemblyPath, "*.dll", SearchOption.TopDirectoryOnly); - } - - /// - /// Determines whether the given is an assembly file that is marked as . - /// - /// Filename of the assembly. - /// True if the given file name is of an assembly file that is marked as , false otherwise. - protected virtual bool IsControllerContainer(string assemblyFileName) - { - if (assemblyFileName == null) - return false; - - bool result; - AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += this.CurrentDomain_ReflectionOnlyAssemblyResolve; - try - { - try - { - var reflOnlyAssembly = Assembly.ReflectionOnlyLoadFrom(assemblyFileName); - - result = reflOnlyAssembly != null && - reflOnlyAssembly.GetCustomAttributesData() - .Any(d => d.Constructor.DeclaringType.AssemblyQualifiedName == typeof(ControllerContainerAttribute).AssemblyQualifiedName); - } - catch (IOException) - { - // We might not be able to load some .DLL files as .NET assemblies. Those files cannot contain controllers. - result = false; - } - catch (BadImageFormatException) - { - result = false; - } - } - finally - { - AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= this.CurrentDomain_ReflectionOnlyAssemblyResolve; - } - - return result; - } - - /// - /// Replaces the current controller factory used by the MVC framework with the factory that is registered by Sitefinity. - /// - protected virtual void ReplaceControllerFactory() - { - var factory = ObjectFactory.Resolve(); - ControllerBuilder.Current.SetControllerFactory(factory); - } - - /// - /// Registers types of the custom routing. - /// - protected virtual void InitializeCustomRouting() - { - ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); - ObjectFactory.Container.RegisterType("category"); - ObjectFactory.Container.RegisterType("tag"); - } - - #endregion - - #region Private members - - private Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args) - { - var assWithPolicy = AppDomain.CurrentDomain.ApplyPolicy(args.Name); - - return Assembly.ReflectionOnlyLoad(assWithPolicy); - } - - private void RegisterAssemblyPaths(Assembly assembly) - { - var assemblyName = assembly.GetName(); - var virtualPath = FrontendManager.VirtualPathBuilder.GetVirtualPath(assembly); - - VirtualPathManager.AddVirtualFileResolver( - "~/" + virtualPath + "*", - assemblyName.Name, - assemblyName.CodeBase); - - SystemManager.RegisterRoute( - assemblyName.Name, - new Route( - virtualPath + "{*Params}", - new RouteHandler()), - assemblyName.Name, - requireBasicAuthentication: false); - } - - private void RemoveSitefinityViewEngine() - { - var sitefinityViewEngine = ViewEngines.Engines.FirstOrDefault(v => v is SitefinityViewEngine); - - if (sitefinityViewEngine != null) - { - ViewEngines.Engines.Remove(sitefinityViewEngine); - } - } - - /// - /// Registers the controller string resources. - /// - /// Type of the controller. - private void RegisterStringResources(Type controller) - { - var localizationAttributes = controller.GetCustomAttributes(typeof(LocalizationAttribute), true); - foreach (var attribute in localizationAttributes) - { - var localAttr = (LocalizationAttribute)attribute; - var resourceClass = localAttr.ResourceClass; - var resourceClassId = Res.GetResourceClassId(resourceClass); - - if (!ObjectFactory.Container.IsRegistered(resourceClass, resourceClassId)) - { - Res.RegisterResource(resourceClass); - } - } - } - - #endregion - } -} +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading.Tasks; +using System.Web.Hosting; +using System.Web.Mvc; +using System.Web.Routing; +using System.Web.Script.Serialization; +using Telerik.Microsoft.Practices.Unity; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Abstractions.VirtualPath; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.Data; +using Telerik.Sitefinity.Frontend.Mvc.Controllers; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing; +using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Frontend.Resources.Resolvers; +using Telerik.Sitefinity.Localization; +using Telerik.Sitefinity.Modules.ControlTemplates; +using Telerik.Sitefinity.Mvc; +using Telerik.Sitefinity.Mvc.Proxy.TypeDescription; +using Telerik.Sitefinity.Mvc.Store; +using Telerik.Sitefinity.Pages; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Taxonomies; +using Telerik.Sitefinity.Taxonomies.Model; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers +{ + /// + /// This class contains logic for locating and initializing controllers. + /// + internal class ControllerContainerInitializer : IInitializer + { + #region Public members + + /// + /// Gets the controller container assemblies. + /// + /// + /// The controller container assemblies. + /// + public IEnumerable ControllerContainerAssemblies + { + get + { + if (ControllerContainerInitializer.controllerContainerAssemblies == null) + { + lock (ControllerContainerInitializer.ControllerContainerAssembliesLock) + { + if (ControllerContainerInitializer.controllerContainerAssemblies == null) + { + ControllerContainerInitializer.controllerContainerAssemblies = this.RetrieveAssemblies(); + } + } + } + + return ControllerContainerInitializer.controllerContainerAssemblies; + } + + private set + { + lock (ControllerContainerInitializer.ControllerContainerAssembliesLock) + { + ControllerContainerInitializer.controllerContainerAssemblies = value; + } + } + } + + /// + /// Registers the string resources. + /// + public void RegisterStringResources() + { + this.ControllerContainerAssemblies + .SelectMany(asm => asm.GetExportedTypes().Where(FrontendManager.ControllerFactory.IsController)) + .ToList() + .ForEach(ControllerContainerInitializer.RegisterStringResources); + } + + /// + /// Initializes the controllers that are available to the web application. + /// + public virtual void Initialize() + { + GlobalFilters.Filters.Add(new CacheDependentAttribute()); + + this.RegisterVirtualPaths(this.ControllerContainerAssemblies); + + var controllerTypes = this.GetControllers(); + this.InitializeControllers(controllerTypes); + + this.InitializeCustomRouting(); + + this.RegisterPrecompiledViewEngines(this.ControllerContainerAssemblies); + } + + /// + /// Uninitializes the controllers that are available to the web application. + /// + public virtual void Uninitialize() + { + this.RegisterStringResources(); + + this.UninitializeGlobalFilters(); + + foreach (var assembly in this.ControllerContainerAssemblies) + { + this.UninitializeControllerContainer(assembly); + } + + this.ControllerContainerAssemblies = null; + + // Clears all controllers + // ControllerStore.ClearControllers(); + + var sitefinityViewEngines = ViewEngines.Engines.Where(v => v != null && v.GetType() == typeof(CompositePrecompiledMvcEngineWrapper)).ToList(); + foreach (var sitefinityViewEngine in sitefinityViewEngines) + { + ViewEngines.Engines.Remove(sitefinityViewEngine); + } + + var sitefinityViewEngineExists = ViewEngines.Engines.Any(v => v.GetType() == typeof(SitefinityViewEngine)); + if (!sitefinityViewEngineExists) + { + // add Sitefinity view engine + ViewEngines.Engines.Add(new SitefinityViewEngine()); + } + } + + /// + /// Gets the assemblies that are marked as controller containers with the attribute. + /// + public virtual IEnumerable RetrieveAssemblies() + { + using (new HealthMonitoring.MethodPerformanceRegion("ControllerContainerInitializer.RetrieveAssemblies")) + { + IEnumerable assemblyFileNames = this.RetrieveControllerAssembliesFileNames().Distinct().ToArray(); + IList> retrieveAssemblyTasks = new List>(); + + foreach (string assemblyFileName in assemblyFileNames) + { + retrieveAssemblyTasks.Add(this.LoadControllerAssemblyAsync(assemblyFileName)); + } + + Task.WaitAll(retrieveAssemblyTasks.ToArray()); + + IEnumerable result = retrieveAssemblyTasks + .Select(v => v.Result) + .Where(v => v != null); + + return result; + } + } + + #endregion + + + #region Internal + internal IEnumerable GetControllers() + { + using (new HealthMonitoring.MethodPerformanceRegion("ControllerContainerInitializer.GetControllers")) + return this.GetControllers(this.ControllerContainerAssemblies); + } + #endregion + + #region Protected members + + /// + /// Executes the initialization method specified in the attribute. + /// + /// + protected virtual void InitializeControllerContainer(Assembly container) + { + if (container == null) + throw new ArgumentNullException("container"); + + var containerAttribute = container.GetCustomAttributes(false).FirstOrDefault(attr => attr.GetType().AssemblyQualifiedName == typeof(ControllerContainerAttribute).AssemblyQualifiedName) as ControllerContainerAttribute; + + if (containerAttribute == null || containerAttribute.InitializationType == null || containerAttribute.InitializationMethod.IsNullOrWhitespace()) + return; + + var initializationMethod = containerAttribute.InitializationType.GetMethod(containerAttribute.InitializationMethod); + initializationMethod.Invoke(null, null); + } + + /// + /// Executes the uninitialization method specified in the attribute. + /// + /// + protected virtual void UninitializeControllerContainer(Assembly container) + { + if (container == null) + throw new ArgumentNullException("container"); + + var containerAttribute = container.GetCustomAttributes(false).SingleOrDefault(attr => attr.GetType().AssemblyQualifiedName == typeof(ControllerContainerAttribute).AssemblyQualifiedName) as ControllerContainerAttribute; + + if (containerAttribute == null || containerAttribute.UninitializationType == null || containerAttribute.UninitializationMethod.IsNullOrWhitespace()) + return; + + var uninitializationMethod = containerAttribute.UninitializationType.GetMethod(containerAttribute.UninitializationMethod); + uninitializationMethod.Invoke(null, null); + } + + /// + /// Loads the assembly file into the current application domain. + /// + /// Name of the assembly file. + /// The loaded assembly + protected virtual Assembly LoadAssembly(string assemblyFileName) + { + return Assembly.LoadFrom(assemblyFileName); + } + + /// + /// Registers virtual paths for the given . + /// + /// The assemblies. + protected virtual void RegisterVirtualPaths(IEnumerable assemblies) + { + foreach (var assembly in assemblies) + { + this.RegisterAssemblyPaths(assembly); + } + } + + /// + /// Gets the controllers from the given . + /// + /// The assemblies. + /// + protected virtual IEnumerable GetControllers(IEnumerable assemblies) + { + return assemblies + .SelectMany(asm => asm.GetExportedTypes().Where(FrontendManager.ControllerFactory.IsController)) + .ToArray(); + } + + /// + /// Initializes the specified by ensuring they have their proper registrations in the toolbox and that the controller factory will be able to resolve them. + /// + /// The controllers. + protected virtual void InitializeControllers(IEnumerable controllers) + { + this.RegisterTemplateableControls(controllers); + this.RegisterControllerFactory(); + this.RemoveSitefinityViewEngine(); + this.ReplaceControllerFactory(); + this.RegisterControllers(controllers); + } + + protected virtual void UninitializeGlobalFilters() + { + var cacheDependentAttribute = GlobalFilters.Filters.FirstOrDefault(f => f.Instance.GetType().FullName == typeof(CacheDependentAttribute).FullName); + if (cacheDependentAttribute != null) + GlobalFilters.Filters.Remove(cacheDependentAttribute.Instance); + } + + /// + /// Registers + /// + protected virtual void RegisterControllerFactory() + { + ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); + } + + /// + /// Registers the controller so its views and resources can be resolved. + /// + /// The controller. + protected virtual void RegisterController(Type controller) + { + var controllerStore = new ControllerStore(); + var configManager = ConfigManager.GetManager(); + + using (var modeRegion = new ElevatedConfigModeRegion()) + { + controllerStore.AddController(controller, configManager); + } + } + + /// + /// Gets the assemblies file names from the controller container assembly cache. + /// + protected virtual IEnumerable RetrieveControllerAssembliesFileNames() + { + var isFeatherenabled = SystemManager.GetApplicationModule(FrontendModule.ModuleName) != null; + bool useCachedControllerContainerAssemblies = false; + if (isFeatherenabled) + { + useCachedControllerContainerAssemblies = Config.Get().UseCachedControllerContainerAssemblies; + } + + var controllerAssemblyPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "bin"); + + if (useCachedControllerContainerAssemblies) + { + var pathToCacheFile = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "bin", "ControllerContainerAsembliesLocation.json"); + if (File.Exists(pathToCacheFile)) + { + try + { + var file = File.ReadAllText(pathToCacheFile); + var filesFromcache = new JavaScriptSerializer().Deserialize(file); + + // append path to the bin in order to be able to load the assemblies + return filesFromcache.Select(x => Path.Combine(controllerAssemblyPath, x)); + } + catch (Exception ex) + { + Log.Write(string.Format("Attempt to read from ControllerContainerAsembliesLocation.json was unsuccessful: {0}", ex.Message), ConfigurationPolicy.ErrorLog); + } + } + } + + var allAssemblyNames = Directory.EnumerateFiles(controllerAssemblyPath, "*.dll", SearchOption.TopDirectoryOnly); + IList> retrieveAssemblyTasks = new List>(); + + foreach (string assemblyFileName in allAssemblyNames) + { + retrieveAssemblyTasks.Add(this.RetrieveControllerAssemblyAsync(assemblyFileName)); + } + + Task.WaitAll(retrieveAssemblyTasks.ToArray()); + var controllerAssembliesNames = retrieveAssemblyTasks + .Select(x => x.Result) + .Where(x => !string.IsNullOrEmpty(x)); + + return controllerAssembliesNames; + } + + /// + /// Determines whether the given is an assembly file that is marked as . + /// + /// Filename of the assembly. + /// True if the given file name is of an assembly file that is marked as , false otherwise. + protected virtual bool IsControllerContainer(string assemblyFileName) + { + return this.IsMarkedAssembly(assemblyFileName); + } + + /// + /// Replaces the current controller factory used by the MVC framework with the factory that is registered by Sitefinity. + /// + protected virtual void ReplaceControllerFactory() + { + var factory = ObjectFactory.Resolve(); + ControllerBuilder.Current.SetControllerFactory(factory); + } + + /// + /// Registers types of the custom routing. + /// + protected virtual void InitializeCustomRouting() + { + ObjectFactory.Container.RegisterType(); + ObjectFactory.Container.RegisterType("int"); + + Task.Run(() => + { + this.RegisterTaxonomyRoutes(); + }); + + CacheDependency.Subscribe(typeof(Taxonomy), this.OnTaxonomiesUpdated); + + string mvcControllerProxySettingsPropertyDescriptorName = string.Format("{0}.{1}", typeof(MvcWidgetProxy).FullName, "Settings"); + ObjectFactory.Container.RegisterType(mvcControllerProxySettingsPropertyDescriptorName); + + FrontendManager.AttributeRouting.MapMvcAttributeRoutes(); + } + + /// + /// Register controllers into the store + /// + /// The controllers to be registered. + protected virtual void RegisterControllers(IEnumerable controllers) + { + controllers.ToList().ForEach(c => ControllerContainerInitializer.RegisterStringResources(c)); + } + + #endregion + + #region Private members + + private void RegisterTaxonomyRoutes() + { + var taxonomies = TaxonomyManager.GetTaxonomiesCache(); + + if (taxonomies.Count() > 0) + { + foreach (var taxonomy in taxonomies) + { + var taxonomyName = this.GetTaxonomyName(taxonomy.Id, taxonomy.Name); + if (!ObjectFactory.IsTypeRegistered(taxonomyName)) + ObjectFactory.Container.RegisterType(taxonomyName, new InjectionConstructor(taxonomyName)); + } + } + } + + private string GetTaxonomyName(Guid id, string name) + { + var taxonomyName = string.Empty; + + if (id == TaxonomyManager.TagsTaxonomyId) + { + taxonomyName = "tag"; + } + else if (id == TaxonomyManager.CategoriesTaxonomyId) + { + taxonomyName = "category"; + } + else + { + taxonomyName = name.ToLowerInvariant(); + } + + return taxonomyName; + } + + private Task RetrieveControllerAssemblyAsync(string assemblyFileName) + { + return Task.Run(() => this.RetrieveAssembly(assemblyFileName)); + } + + private Task LoadControllerAssemblyAsync(string assemblyFileName) + { + return Task.Run(() => this.LoadControllerAssembly(assemblyFileName)); + } + + private Assembly LoadControllerAssembly(string assemblyFileNameWithPath) + { + try + { + Assembly assembly = this.LoadAssembly(assemblyFileNameWithPath); + this.InitializeControllerContainer(assembly); + return assembly; + } + catch (Exception) + { + var lastIndexOfPathSeperator = assemblyFileNameWithPath.LastIndexOf("\\"); + var fileNameFailedToLoad = assemblyFileNameWithPath.Substring(lastIndexOfPathSeperator >= 0 ? lastIndexOfPathSeperator : 0); + Log.Write(string.Format("Attempt to load {0} failed. Check if the assembly is present in the bin", fileNameFailedToLoad), ConfigurationPolicy.ErrorLog); + } + + return null; + } + + private string RetrieveAssembly(string assemblyFileName) + { + if (this.IsControllerContainer(assemblyFileName) || this.IsMarkedAssembly(assemblyFileName)) + { + return assemblyFileName; + } + + return null; + } + + /// + /// Registers the controller string resources. + /// + /// Type of the controller. + private static void RegisterStringResources(Type controller) + { + var localizationAttributes = controller.GetCustomAttributes(typeof(LocalizationAttribute), true); + foreach (var attribute in localizationAttributes) + { + var localAttr = (LocalizationAttribute)attribute; + var resourceClass = localAttr.ResourceClass; + var resourceClassId = Res.GetResourceClassId(resourceClass); + + if (!ObjectFactory.IsTypeRegistered(resourceClass, null, resourceClassId, false)) + { + Res.RegisterResource(resourceClass); + } + } + } + + /// + /// Determines whether the specified controller is allowed template registration + /// + /// Type of the controller. + /// + /// true if specified controller is allowed template registration; otherwise, false. + /// + private bool IsTemplatableControl(Type controllerType) + { + ControllerMetadataAttribute attr; + var attributes = controllerType.GetCustomAttributes(typeof(ControllerMetadataAttribute), false); + + if (attributes != null && attributes.Length > 0) + { + attr = (ControllerMetadataAttribute)attributes[0]; + return attr.IsTemplatableControl; + } + + // if there is no ControllerMetaDataAttribute, by default allow template registration + return true; + } + + /// + /// Determines whether the specified assembly file name is marked with a given attribute. + /// + /// The type of the attribute. + /// File name of the assembly. + /// True if the assembly has the given attribute. + private bool IsMarkedAssembly(string assemblyFileName) + where TAttribute : Attribute + { + if (assemblyFileName == null) + return false; + + bool result; + AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += this.CurrentDomain_ReflectionOnlyAssemblyResolve; + try + { + try + { + var reflOnlyAssembly = Assembly.ReflectionOnlyLoadFrom(assemblyFileName); + + result = reflOnlyAssembly != null && + reflOnlyAssembly.GetCustomAttributesData() + .Any(d => d.Constructor.DeclaringType.AssemblyQualifiedName == typeof(TAttribute).AssemblyQualifiedName); + } + catch (IOException) + { + // We might not be able to load some .DLL files as .NET assemblies. Those files cannot contain controllers. + result = false; + } + catch (BadImageFormatException) + { + result = false; + } + } + finally + { + AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= this.CurrentDomain_ReflectionOnlyAssemblyResolve; + } + + return result; + } + + private Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args) + { + var assWithPolicy = AppDomain.CurrentDomain.ApplyPolicy(args.Name); + + return Assembly.ReflectionOnlyLoad(assWithPolicy); + } + + private void RegisterAssemblyPaths(Assembly assembly) + { + var assemblyName = assembly.GetName(); + var virtualPath = FrontendManager.VirtualPathBuilder.GetVirtualPath(assembly); + + VirtualPathManager.AddVirtualFileResolver( + string.Format(CultureInfo.InvariantCulture, "~/{0}*", virtualPath), + assemblyName.Name, + assemblyName.CodeBase); + + SystemManager.RegisterRoute( + assemblyName.Name, + new Route( + virtualPath + "{*Params}", + new GenericRouteHandler(() => new ResourceHttpHandler(virtualPath))), + assemblyName.Name, + requireBasicAuthentication: false); + } + + /// + /// Registers MVC widgets as templatable controls + /// + /// The controller types. + private void RegisterTemplateableControls(IEnumerable controllerTypes) + { + controllerTypes = controllerTypes.Where(x => this.IsTemplatableControl(x)); + + foreach (Type controllerType in controllerTypes) + { + var widgetName = controllerType.Name.Replace("Controller", string.Empty); + var mvcWidgetName = string.Format(CultureInfo.InvariantCulture, "{0} (MVC)", widgetName); + + ControlTemplates.RegisterTemplatableControl(controllerType, controllerType, string.Empty, widgetName, mvcWidgetName); + } + } + + private void RemoveSitefinityViewEngine() + { + var sitefinityViewEngines = ViewEngines.Engines.Where(v => v != null && v.GetType() == typeof(SitefinityViewEngine)).ToList(); + foreach (var sitefinityViewEngine in sitefinityViewEngines) + { + ViewEngines.Engines.Remove(sitefinityViewEngine); + } + } + + private static IEnumerable controllerContainerAssemblies; + private static readonly object ControllerContainerAssembliesLock = new object(); + + private Dictionary> PrecompiledResourcePackages(IEnumerable assemblies) + { + var precompiledViewAssemblies = new Dictionary>(); + foreach (var assembly in assemblies) + { + var package = this.AssemblyPackage(assembly); + if (package == null) + continue; + + if (!precompiledViewAssemblies.ContainsKey(package)) + precompiledViewAssemblies[package] = new List(); + + precompiledViewAssemblies[package].Add(new PrecompiledViewAssemblyWrapper(assembly, package)); + } + + return precompiledViewAssemblies; + } + + private void RegisterPrecompiledViewEngines(IEnumerable assemblies) + { + var precompiledAssemblies = assemblies.Where(a => a.GetCustomAttribute() != null).Select(a => new PrecompiledViewAssemblyWrapper(a, null)).ToArray(); + if (precompiledAssemblies.Length > 0) + { + ViewEngines.Engines.Insert(0, new CompositePrecompiledMvcEngineWrapper(precompiledAssemblies)); + } + + var precompiledResourcePackages = this.PrecompiledResourcePackages(assemblies); + foreach (var package in precompiledResourcePackages.Keys) + { + if (package == null) + continue; + + var packageAssemblies = precompiledResourcePackages[package]; + if (packageAssemblies.Count > 0) + ViewEngines.Engines.Insert(0, new CompositePrecompiledMvcEngineWrapper(packageAssemblies, null, package)); + } + } + + private string AssemblyPackage(Assembly assembly) + { + var attribute = assembly.GetCustomAttribute(); + if (attribute == null) + return null; + else + return attribute.Name; + } + + private void OnTaxonomiesUpdated(ICacheDependencyHandler caller, Type itemType, string itemKey) + { + // needs to run on a separate thread otherwise messes up the open access cache for som reason + // no time to investigate and I see this method has already been called in the same fashion in earlier checkins + Task.Run(() => + { + RegisterTaxonomyRoutes(); + }); + } + + #endregion + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerContainerInitializer.cs.orig b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerContainerInitializer.cs.orig deleted file mode 100644 index db8b7b53c..000000000 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerContainerInitializer.cs.orig +++ /dev/null @@ -1,317 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Web.Hosting; -using System.Web.Mvc; -using System.Web.Routing; -using Telerik.Microsoft.Practices.Unity; -using Telerik.Sitefinity.Abstractions; -using Telerik.Sitefinity.Abstractions.VirtualPath; -using Telerik.Sitefinity.Configuration; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing; -using Telerik.Sitefinity.Frontend.Resources; -using Telerik.Sitefinity.Frontend.Resources.Resolvers; -using Telerik.Sitefinity.Localization; -using Telerik.Sitefinity.Mvc; -using Telerik.Sitefinity.Mvc.Store; -using Telerik.Sitefinity.Services; - -namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers -{ - /// - /// This class contains logic for locating and initializing controllers. - /// - public class ControllerContainerInitializer - { - #region Public members - - /// - /// Initializes the controllers that are available to the web application. - /// - public virtual void Initialize() - { - GlobalFilters.Filters.Add(new CacheDependentAttribute()); - - var assemblies = this.Assemblies; - - this.RegisterVirtualPaths(assemblies); - - var controllerTypes = this.GetControllers(assemblies); - this.InitializeControllers(controllerTypes); - - this.InitializeCustomRouting(); - } - - #endregion - - #region Protected members - - /// - /// Gets the assemblies that are marked as controller containers with the attribute. - /// - protected virtual IEnumerable Assemblies - { - get - { - var assemblyFileNames = this.AssemblyFileNames.ToArray(); - var result = new List(); - - foreach (var assemblyFileName in assemblyFileNames) - { - if (this.IsControllerContainer(assemblyFileName)) - { - var assembly = this.LoadAssembly(assemblyFileName); - this.InitializeControllerContainer(assembly); - result.Add(assembly); - } - } - - return result; - } - } - - /// - /// Executes the initialization method specified in the attribute. - /// - /// - protected virtual void InitializeControllerContainer(Assembly container) - { - if (container == null) - { - return; - } - - var containerAttribute = container.GetCustomAttributes(false).Single(attr => attr.GetType().AssemblyQualifiedName == typeof(ControllerContainerAttribute).AssemblyQualifiedName) as ControllerContainerAttribute; - - if (containerAttribute.InitializationType == null || containerAttribute.InitializationMethod.IsNullOrWhitespace()) - return; - - var initializationMethod = containerAttribute.InitializationType.GetMethod(containerAttribute.InitializationMethod); - initializationMethod.Invoke(null, null); - } - - /// - /// Loads the assembly file into the current application domain. - /// - /// Name of the assembly file. - /// The loaded assembly - protected virtual Assembly LoadAssembly(string assemblyFileName) - { - return Assembly.LoadFrom(assemblyFileName); - } - - /// - /// Registers virtual paths for the given . - /// - /// The assemblies. - protected virtual void RegisterVirtualPaths(IEnumerable assemblies) - { - foreach (var assembly in assemblies) - { - this.RegisterAssemblyPaths(assembly); - } - } - - /// - /// Gets the controllers from the given . - /// - /// The assemblies. - /// - protected virtual IEnumerable GetControllers(IEnumerable assemblies) - { - return assemblies - .SelectMany(asm => asm.GetExportedTypes().Where(FrontendManager.ControllerFactory.IsController)) - .ToArray(); - } - - /// - /// Initializes the specified by ensuring they have their proper registrations in the toolbox and that the controller factory will be able to resolve them. - /// - /// The controllers. - protected virtual void InitializeControllers(IEnumerable controllers) - { - this.RegisterControllerFactory(); - this.RemoveSitefinityViewEngine(); - this.ReplaceControllerFactory(); - - if (controllers != null) - return; - - foreach (var controller in controllers) - { - this.RegisterController(controller); - } - } - - /// - /// Registers - /// - protected virtual void RegisterControllerFactory() - { - ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); - } - - /// - /// Registers the controller so its views and resources can be resolved. - /// - /// The controller. - protected virtual void RegisterController(Type controller) - { - var controllerStore = new ControllerStore(); - var configManager = ConfigManager.GetManager(); - - using (var modeRegion = new ElevatedConfigModeRegion()) - { - this.RegisterStringResources(controller); - controllerStore.AddController(controller, configManager); - } - } - - /// - /// Gets the assembly file names that will be inspected for controllers. - /// - /// The assembly path. - protected virtual IEnumerable AssemblyFileNames - { - get - { - var controllerAssemblyPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "bin"); - return Directory.EnumerateFiles(controllerAssemblyPath, "*.dll", SearchOption.TopDirectoryOnly); - } - } - - /// - /// Determines whether the given is an assembly file that is marked as . - /// - /// Filename of the assembly. - /// True if the given file name is of an assembly file that is marked as , false otherwise. - protected virtual bool IsControllerContainer(string assemblyFileName) - { - if (assemblyFileName == null) - return false; - - bool result; - AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += this.CurrentDomain_ReflectionOnlyAssemblyResolve; - try - { - try - { - var reflOnlyAssembly = Assembly.ReflectionOnlyLoadFrom(assemblyFileName); - - result = reflOnlyAssembly != null && - reflOnlyAssembly.GetCustomAttributesData() - .Any(d => d.Constructor.DeclaringType.AssemblyQualifiedName == typeof(ControllerContainerAttribute).AssemblyQualifiedName); - } - catch (IOException) - { - // We might not be able to load some .DLL files as .NET assemblies. Those files cannot contain controllers. - result = false; - } - catch (BadImageFormatException) - { - result = false; - } - } - finally - { - AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= this.CurrentDomain_ReflectionOnlyAssemblyResolve; - } - - return result; - } - - /// - /// Replaces the current controller factory used by the MVC framework with the factory that is registered by Sitefinity. - /// - protected virtual void ReplaceControllerFactory() - { - var factory = ObjectFactory.Resolve(); - ControllerBuilder.Current.SetControllerFactory(factory); - } - - /// - /// Registers types of the custom routing. - /// - protected virtual void InitializeCustomRouting() - { -<<<<<<< HEAD - // Sf 7.2: - // ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); - - // ObjectFactory.Container.RegisterType("category"); - // ObjectFactory.Container.RegisterType("tag"); -======= - //Sf 7.2: - ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); - - ObjectFactory.Container.RegisterType("category"); - ObjectFactory.Container.RegisterType("tag"); ->>>>>>> d63719b939d4d39fd3efad20daffb9e5c4f05d8d - } - - #endregion - - #region Private members - - private Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args) - { - var assWithPolicy = AppDomain.CurrentDomain.ApplyPolicy(args.Name); - - return Assembly.ReflectionOnlyLoad(assWithPolicy); - } - - private void RegisterAssemblyPaths(Assembly assembly) - { - var assemblyName = assembly.GetName(); - var virtualPath = FrontendManager.VirtualPathBuilder.GetVirtualPath(assembly); - - VirtualPathManager.AddVirtualFileResolver( - "~/" + virtualPath + "*", - assemblyName.Name, - assemblyName.CodeBase); - - SystemManager.RegisterRoute( - assemblyName.Name, - new Route( - virtualPath + "{*Params}", - new RouteHandler()), - assemblyName.Name, - requireBasicAuthentication: false); - } - - private void RemoveSitefinityViewEngine() - { - var sitefinityViewEngine = ViewEngines.Engines.FirstOrDefault(v => v is SitefinityViewEngine); - - if (sitefinityViewEngine != null) - { - ViewEngines.Engines.Remove(sitefinityViewEngine); - } - } - - /// - /// Registers the controller string resources. - /// - /// Type of the controller. - private void RegisterStringResources(Type controller) - { - var localizationAttributes = controller.GetCustomAttributes(typeof(LocalizationAttribute), true); - foreach (var attribute in localizationAttributes) - { - var localAttr = (LocalizationAttribute)attribute; - var resourceClass = localAttr.ResourceClass; - var resourceClassId = Res.GetResourceClassId(resourceClass); - - if (!ObjectFactory.Container.IsRegistered(resourceClass, resourceClassId)) - { - Res.RegisterResource(resourceClass); - } - } - } - - #endregion - } -} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerExtensions.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerExtensions.cs index 8510e2cd5..b36a8430f 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerExtensions.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerExtensions.cs @@ -1,239 +1,679 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Reflection; -using System.Web; -using System.Web.Mvc; -using Telerik.Sitefinity.Abstractions; -using Telerik.Sitefinity.Abstractions.VirtualPath; -using Telerik.Sitefinity.Data; -using Telerik.Sitefinity.Frontend.Resources.Resolvers; -using Telerik.Sitefinity.Services; -using Telerik.Sitefinity.Web; - -namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers -{ - /// - /// Provides extension methods for MVC controllers. - /// - public static class ControllerExtensions - { - #region Public methods - - /// - /// Updates the view engines collection of the given by making the engines aware of the controller's container virtual path. - /// - /// The controller. - /// controller - /// Transformations that have to be applied to each view engine search path. - public static void UpdateViewEnginesCollection(this Controller controller, IList> pathTransformations) - { - if (pathTransformations == null) - throw new ArgumentNullException("pathTransformations"); - - if (controller == null) - throw new ArgumentNullException("controller"); - - var viewEngines = new ViewEngineCollection(); - - foreach (var globalEngine in ViewEngines.Engines) - { - var vppEngine = globalEngine as VirtualPathProviderViewEngine; - var newEngine = vppEngine != null ? ControllerExtensions.GetViewEngine(vppEngine, pathTransformations) : globalEngine; - viewEngines.Add(newEngine); - } - - controller.ViewEngineCollection = viewEngines; - } - - /// - /// Gets the partial views that are available to the controller. - /// - /// The controller. - public static IEnumerable GetPartialViews(this Controller controller) - { - var viewLocations = ControllerExtensions.GetPartialViewLocations(controller); - return ControllerExtensions.GetViews(controller, viewLocations); - } - - /// - /// Gets the views that are available to the controller. - /// - /// The controller. - public static IEnumerable GetViews(this Controller controller) - { - var viewLocations = ControllerExtensions.GetViewLocations(controller); - return ControllerExtensions.GetViews(controller, viewLocations); - } - - /// - /// Adds cache dependencies for the current response. - /// - /// The controller. - /// The cache dependency keys to be added. - public static void AddCacheDependencies(this Controller controller, IEnumerable keys) - { - if (controller == null) - throw new ArgumentNullException("controller"); - - if (keys == null) - throw new ArgumentNullException("keys"); - - if (SystemManager.CurrentHttpContext == null) - throw new InvalidOperationException("Current HttpContext is null. Cannot add cache dependencies."); - - IList dependencies = null; - if (SystemManager.CurrentHttpContext.Items.Contains(PageCacheDependencyKeys.PageData)) - { - dependencies = SystemManager.CurrentHttpContext.Items[PageCacheDependencyKeys.PageData] as IList; - } - - if (dependencies == null) - { - dependencies = new List(); - SystemManager.CurrentHttpContext.Items.Add(PageCacheDependencyKeys.PageData, dependencies); - } - - foreach (var key in keys) - dependencies.Add(key); - } - - /// - /// Gets the partial view paths of the given controller. - /// - /// The controller. - public static IEnumerable GetPartialViewLocations(this Controller controller) - { - return ControllerExtensions.GetControllerViewEngineLocations(controller, v => v.PartialViewLocationFormats); - } - - /// - /// Gets the URL of the current page. - /// - /// The controller. - /// URL of the currents page without a trailing slash. - [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "controller")] - [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")] - public static string GetCurrentPageUrl(this IController controller) - { - var currentSiteMap = (SiteMapBase)SitefinitySiteMap.GetCurrentProvider(); - var currentNode = currentSiteMap.CurrentNode; - var url = string.Empty; - - if (currentNode != null) - { - url = UrlPath.ResolveUrl(currentNode.Url, absolute: false, removeTrailingSlash: true); - } - - return url; - } - - #endregion - - #region Private methods - - /// - /// Gets a view engine that is a clone of the given and has enhanced search locations. - /// - /// The view engine. - /// Transformations that have to be applied to each view engine search path. - private static IViewEngine GetViewEngine(VirtualPathProviderViewEngine viewEngine, IList> pathTransformations) - { - var newEngine = (VirtualPathProviderViewEngine)Activator.CreateInstance(viewEngine.GetType()); - newEngine.AreaViewLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.AreaViewLocationFormats, pathTransformations); - newEngine.AreaMasterLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.AreaPartialViewLocationFormats, pathTransformations); - newEngine.AreaPartialViewLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.AreaPartialViewLocationFormats, pathTransformations); - newEngine.ViewLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.ViewLocationFormats, pathTransformations); - newEngine.MasterLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.MasterLocationFormats, pathTransformations); - newEngine.PartialViewLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.PartialViewLocationFormats, pathTransformations); - - newEngine.ViewLocationCache = new VoidViewLocationCache(); - - return newEngine; - } - - private static string[] AppendControllerVirtualPath(string[] originalPaths, IList> pathTransformations) - { - var result = originalPaths.ToList(); - foreach (var transform in pathTransformations) - { - result.AddRange(originalPaths.Select(transform)); - } - - return result.ToArray(); - } - - /// - /// Gets the view paths of the given controller. - /// - /// The controller. - private static IEnumerable GetViewLocations(Controller controller) - { - return ControllerExtensions.GetControllerViewEngineLocations(controller, v => v.ViewLocationFormats); - } - - private static IEnumerable GetControllerViewEngineLocations(Controller controller, Func locationExtractor) - { - return controller.ViewEngineCollection.OfType() - .SelectMany(v => locationExtractor(v)) - .Distinct() - .Select(v => v.Replace("{1}", FrontendManager.ControllerFactory.GetControllerName(controller.GetType()))) - .Select(VirtualPathUtility.GetDirectory) - .Distinct(); - } - - /// - /// Gets the file extensions that this controller will recognize when resolving view templates. - /// - /// The controller. - private static IEnumerable GetViewFileExtensions(Controller controller) - { - return controller.ViewEngineCollection.OfType() - .SelectMany(v => v.FileExtensions.Select(e => "." + e)) - .Distinct(); - } - - private static IEnumerable GetViews(Controller controller, IEnumerable viewLocations) - { - var viewExtensions = ControllerExtensions.GetViewFileExtensions(controller); - var widgetName = controller.RouteData != null ? controller.RouteData.Values["widgetName"] as string : null; - - var baseFiles = ControllerExtensions.GetViewsForAssembly(controller.GetType().Assembly, viewLocations, viewExtensions); - if (!widgetName.IsNullOrEmpty()) - { - var widgetAssembly = FrontendManager.ControllerFactory.ResolveControllerType(widgetName).Assembly; - var widgetFiles = ControllerExtensions.GetViewsForAssembly(widgetAssembly, viewLocations, viewExtensions); - return baseFiles.Union(widgetFiles); - } - - return baseFiles; - } - - private static IEnumerable GetViewsForAssembly(Assembly assembly, IEnumerable viewLocations, IEnumerable viewExtensions) - { - var pathDef = FrontendManager.VirtualPathBuilder.GetPathDefinition(assembly); - return viewLocations - .SelectMany(l => ControllerExtensions.GetViewsForPath(pathDef, l, viewExtensions)) - .Distinct(); - } - - private static IEnumerable GetViewsForPath(PathDefinition definition, string path, IEnumerable viewExtensions) - { - var files = ObjectFactory.Resolve().GetFiles(definition, path); - - if (files != null) - { - return files - .Where(f => viewExtensions.Any(e => f.EndsWith(e, StringComparison.Ordinal))) - .Select(VirtualPathUtility.GetFileName) - .Select(System.IO.Path.GetFileNameWithoutExtension) - .Distinct(); - } - - return new string[] { }; - } - - #endregion - } -} +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Reflection; +using System.Web; +using System.Web.Mvc; +using ServiceStack.Text; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Abstractions.VirtualPath; +using Telerik.Sitefinity.Data; +using Telerik.Sitefinity.DynamicModules.Builder; +using Telerik.Sitefinity.DynamicModules.Builder.Model; +using Telerik.Sitefinity.Frontend.Mvc.Controllers; +using Telerik.Sitefinity.Frontend.Mvc.Models; +using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Frontend.Resources.Resolvers; +using Telerik.Sitefinity.Security.Sanitizers; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Web; +using Telerik.Sitefinity.Web.OutputCache; +using Telerik.Sitefinity.Web.UI; +using Telerik.Sitefinity.Web.UI.ContentUI.Enums; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers +{ + /// + /// Provides extension methods for MVC controllers. + /// + public static class ControllerExtensions + { + #region Public methods + + /// + /// Determines whether the controller should return the details view. + /// + /// The controller. + /// Display mode of the view. + /// A view model containing list of selected items. + /// A value indicating whether the controller should return the details view. + public static bool ShouldReturnDetails(this Controller controller, ContentViewDisplayMode contentViewDisplayMode, ContentListViewModel viewModel) + { + if (controller == null) + throw new ArgumentNullException("controller"); + + if (contentViewDisplayMode == ContentViewDisplayMode.Detail && viewModel != null) + { + return true; + } + + return false; + } + + /// + /// Updates the view engines collection of the given by making the engines aware of the controller's container virtual path. + /// + /// The controller. + /// Transformations func that have to be applied to each view engine search path. + /// controller + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] + public static void UpdateViewEnginesCollection(this Controller controller, Func>> pathTransformationsFunc) + { + if (pathTransformationsFunc == null) + throw new ArgumentNullException("pathTransformationsFunc"); + + if (controller == null) + throw new ArgumentNullException("controller"); + + controller.ViewEngineCollection = GetViewEngineCollection(controller, pathTransformationsFunc); + } + + /// + /// Updates the view engines collection of the given by making the engines aware of the controller's container virtual path. + /// + /// The controller. + /// controller + /// Transformations that have to be applied to each view engine search path. + [Obsolete("Use the UpdateViewEnginesCollection with the Func>> overload")] + public static void UpdateViewEnginesCollection(this Controller controller, IList> pathTransformations) + { + if (pathTransformations == null) + throw new ArgumentNullException("pathTransformations"); + + if (controller == null) + throw new ArgumentNullException("controller"); + + controller.ViewEngineCollection = GetViewEngineCollection(controller, () => pathTransformations); + } + + /// + /// Gets the partial views that are available to the controller. + /// + /// The controller. + /// The full view paths. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "fullViewPaths")] + public static IEnumerable GetPartialViews(this Controller controller, IList fullViewPaths = null) + { + var viewLocations = ControllerExtensions.GetPartialViewLocations(controller); + return ControllerExtensions.GetViews(controller, viewLocations); + } + + /// + /// Gets the views that are available to the controller. + /// + /// The controller. + /// The full view paths. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "fullViewPaths")] + public static IEnumerable GetViews(this Controller controller, IList fullViewPaths = null) + { + return ControllerExtensions.GetViews(controller, fullViewPaths, null); + } + + /// + /// Gets the views that are available to the controller. + /// + /// The controller. + /// The full view paths. + /// The name of dynamic module (if any). Default is null. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "fullViewPaths")] + public static IEnumerable GetViews(this Controller controller, IList fullViewPaths, string moduleName) + { + var viewLocations = ControllerExtensions.GetViewLocations(controller); + return ControllerExtensions.GetViews(controller, viewLocations, moduleName); + } + + /// + /// Adds cache dependencies for the current response. + /// + /// The controller. + /// The cache dependency keys to be added. + public static void AddCacheDependencies(this Controller controller, IEnumerable keys) + { + if (controller == null) + throw new ArgumentNullException("controller"); + + if (keys == null) + throw new ArgumentNullException("keys"); + + var httpContext = SystemManager.CurrentHttpContext; + if (httpContext == null) + throw new InvalidOperationException("Current HttpContext is null. Cannot add cache dependencies."); + + string widgetId = controller.ViewData[Telerik.Sitefinity.Mvc.ControllerActionInvoker.ControlDataIdKey] as string; + + httpContext.AddCacheDependencies(keys, widgetId); + } + + /// + /// Adds cache dependencies for the current response. + /// + /// The controller. + /// The type of the content. + /// The name of the provider. + public static void AddCacheVariations(this Controller controller, Type contentType, string providerName = null) + { + if (controller == null) + throw new ArgumentNullException("controller"); + + if (contentType == null) + throw new ArgumentNullException("contentType"); + + PageRouteHandler.RegisterContentListCacheVariation(contentType, providerName); + } + + + /// + /// Gets the partial view paths of the given controller. + /// + /// The controller. + public static IEnumerable GetPartialViewLocations(this Controller controller) + { + return ControllerExtensions.GetControllerViewEngineLocations(controller, v => v.PartialViewLocationFormats); + } + + /// + /// Gets the URL of the current page. + /// + /// The controller. + /// URL of the currents page without a trailing slash. + [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "controller")] + [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings")] + public static string GetCurrentPageUrl(this IController controller) + { + var currentSiteMap = (SiteMapBase)SitefinitySiteMap.GetCurrentProvider(); + var currentNode = currentSiteMap.CurrentNode; + var url = string.Empty; + + if (currentNode != null) + { + url = UrlPath.ResolveUrl(currentNode.Url, absolute: false, removeTrailingSlash: true); + } + + return url; + } + + /// + /// Gets the type of the dynamic content that is inferred for the given controller. + /// + /// The controller. + /// The dynamic module type. + public static IDynamicModuleType GetDynamicContentType(this ControllerBase controller) + { + if (controller == null) + throw new ArgumentNullException("controller"); + + if (controller.ControllerContext == null || controller.ControllerContext.RouteData == null) + return null; + + var controllerName = controller.ControllerContext.RouteData.Values["controller"] as string; + return controller.GetDynamicContentType(controllerName); + } + + /// + /// Gets the type of the dynamic content that is inferred for the given controller. + /// + /// The controller. + /// Name of the controller. + /// + /// The dynamic module type. + /// + public static IDynamicModuleType GetDynamicContentType(this ControllerBase controller, string controllerName) + { + if (controller == null) + throw new ArgumentNullException("controller"); + + if (controllerName == null) + throw new ArgumentNullException("controllerName"); + + var moduleName = controller.ViewBag.ModuleName as string; + + return ControllerExtensions.GetDynamicContentType(controllerName, moduleName); + } + + /// + /// Gets the type of the dynamic content that is inferred for the given controller name. + /// + /// Name of the controller. + /// + /// The dynamic module type. + /// + public static IDynamicModuleType GetDynamicContentType(string controllerName) + { + return ControllerExtensions.GetDynamicContentType(controllerName, null); + } + + /// + /// Gets the type of the dynamic content that is inferred for the given controller name. + /// + /// Name of the controller. + /// The name of the module. If empty or null will search all dynamic modules. Default value is null. + /// + /// The dynamic module type. + /// + public static IDynamicModuleType GetDynamicContentType(string controllerName, string moduleName) + { + return ControllerExtensions.FindDynamicContentTypes(controllerName, moduleName).FirstOrDefault(); + } + + /// + /// Determines whether this controller will produce output when rendered in-memory by the search engine. + /// + public static IndexRenderModes GetIndexRenderMode(this IController controller) + { + if (controller == null) + throw new ArgumentNullException("controller"); + + var searchableControl = controller as ISearchIndexBehavior; + if (searchableControl != null) + { + var exclude = searchableControl.ExcludeFromSearchIndex; + if (exclude) + return IndexRenderModes.NoOutput; + else + return IndexRenderModes.Normal; + } + + var attribute = controller.GetType().GetCustomAttributes(true).OfType().LastOrDefault(); + return attribute == null ? IndexRenderModes.Normal : attribute.Mode; + } + + /// + /// Returns the invalid response for the details view. + /// + /// The + public static ActionResult HandleInvalidDetailsAction(this IController controller, string message) + { + if (SystemManager.IsDesignMode || SystemManager.IsPreviewMode) + { + var sanitizer = ObjectFactory.Resolve(); + message = sanitizer.Sanitize(message); + + var response = new ContentResult(); + response.Content = message; + + return response; + } + + return new EmptyResult(); + } + + #endregion + + #region Internal methods + + /// + /// Gets the type of the dynamic content that is inferred for the given controller name. + /// + /// Name of the controller. + /// The name of the module. If empty or null will search all dynamic modules. + /// + /// The dynamic module types. + /// + internal static IEnumerable FindDynamicContentTypes(string controllerName, string moduleName) + { + if (controllerName == null) + throw new ArgumentNullException("controllerName"); + + if (SystemManager.GetModule("ModuleBuilder") == null) + return Enumerable.Empty().AsQueryable(); + + var dynamicModuleTypes = ModuleBuilderManager.GetActiveTypes() + .Where(t => string.Equals(t.TypeName, controllerName, StringComparison.OrdinalIgnoreCase)); + + if (!moduleName.IsNullOrWhitespace()) + { + dynamicModuleTypes = dynamicModuleTypes.Where(t => t.ModuleName == moduleName); + } + + return dynamicModuleTypes; + } + + /// + /// Gets the partial views that are available to the controller. + /// + /// The controller. + /// The view files mappings. + /// The name of dynamic module name. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "fullViewPaths")] + internal static IEnumerable GetPartialViews(this Controller controller, ref Dictionary viewFilesMappings, string moduleName) + { + var viewLocations = ControllerExtensions.GetPartialViewLocations(controller); + return ControllerExtensions.GetViews(controller, viewLocations, ref viewFilesMappings, moduleName); + } + + /// + /// Resolves the widget name of the dynamic widget controller. + /// + /// The controller. + /// + /// The widget name. + /// + internal static string ResolveDynamicControllerWidgetName(this Controller controller) + { + if (controller == null || + controller.Request == null || + controller.Request.QueryString == null || + controller.RouteData == null || + !controller.RouteData.Values.ContainsKey("widgetName") || + (string)controller.RouteData.Values["widgetName"] != "DynamicContent") + { + return null; + } + + var controlId = controller.Request.QueryStringGet("controlId") as string; + Guid controlIdGuid; + if (string.IsNullOrEmpty(controlId) || !Guid.TryParse(controlId, out controlIdGuid)) + return null; + + var pageManager = Telerik.Sitefinity.Modules.Pages.PageManager.GetManager(); + var controlObjectData = pageManager.GetControl(controlIdGuid); + if (controlObjectData == null || controlObjectData.Properties == null) + return null; + + var controllerWidgetProperty = controlObjectData.Properties.FirstOrDefault(x => x.Name == "WidgetName"); + if (controllerWidgetProperty == null) + return null; + + return controllerWidgetProperty.Value; + } + + #endregion + + #region Private methods + + /// + /// Gets an already cached view engine collection from the dictionary or builds a new one. + /// + /// The controller. + /// The path transformations function. + private static ViewEngineCollection GetViewEngineCollection(Controller controller, Func>> pathTransformationsFunc) + { + var key = ControllerExtensions.GetKey(controller); + + if (!ControllerExtensions.ViewEngineCollections.ContainsKey(key)) + { + lock (ControllerExtensions.ViewEngineCollections) + { + if (!ControllerExtensions.ViewEngineCollections.ContainsKey(key)) + { + var viewEngineCollection = ControllerExtensions.BuildViewEngineCollection(pathTransformationsFunc()); + ControllerExtensions.ViewEngineCollections.Add(key, viewEngineCollection); + } + } + } + + return ControllerExtensions.ViewEngineCollections[key]; + } + + /// + /// Gets the key to be used in the view engine collection dictionary based on the controller type and the widget name. + /// + /// The controller. + private static string GetKey(Controller controller) + { + const string WidgetNameKey = "widgetName"; + + var key = controller.GetType().FullName; + + if (controller.RouteData != null && controller.RouteData.Values != null && controller.RouteData.Values.ContainsKey(WidgetNameKey)) + { + var widgetName = (string)controller.RouteData.Values[WidgetNameKey]; + key = string.Format("{0}-{1}", key, widgetName); + + var dynamicControllerWidgetName = controller.ResolveDynamicControllerWidgetName(); + if (!string.IsNullOrEmpty(dynamicControllerWidgetName)) + key = string.Format("{0}-{1}", key, dynamicControllerWidgetName); + } + + var currentPackage = new PackageManager().GetCurrentPackage(); + if (!currentPackage.IsNullOrEmpty()) + { + key += "-" + currentPackage; + } + + return key; + } + + /// + /// Builds the view engine collection by applying the passed path transformations to each view engine. + /// + /// The path transformations. + private static ViewEngineCollection BuildViewEngineCollection(IList> pathTransformations) + { + var viewEngines = new ViewEngineCollection(); + + foreach (var globalEngine in ViewEngines.Engines) + { + var vppEngine = globalEngine as VirtualPathProviderViewEngine; + var newEngine = vppEngine != null ? ControllerExtensions.GetViewEngine(vppEngine, pathTransformations) : globalEngine; + if (newEngine != null) + { + viewEngines.Add(newEngine); + } + } + + return viewEngines; + } + + /// + /// Gets a view engine that is a clone of the given and has enhanced search locations. + /// + /// The view engine. + /// Transformations that have to be applied to each view engine search path. + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] + private static IViewEngine GetViewEngine(VirtualPathProviderViewEngine viewEngine, IList> pathTransformations) + { + VirtualPathProviderViewEngine newEngine; + var precompiledEngine = viewEngine as CompositePrecompiledMvcEngineWrapper; + if (precompiledEngine != null) + { + if (!precompiledEngine.PackageName.IsNullOrEmpty() && + !string.Equals(precompiledEngine.PackageName, new PackageManager().GetCurrentPackage(), StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + newEngine = precompiledEngine.Clone(); + } + else + { + var viewEngineType = viewEngine.GetType(); + var defaultCtor = viewEngineType.GetConstructor(Type.EmptyTypes); + if (defaultCtor != null) + newEngine = (VirtualPathProviderViewEngine)Activator.CreateInstance(viewEngineType); + else + return null; + } + + newEngine.ViewLocationCache = DefaultViewLocationCache.Null; + + newEngine.AreaViewLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.AreaViewLocationFormats, pathTransformations); + newEngine.AreaMasterLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.AreaPartialViewLocationFormats, pathTransformations); + newEngine.AreaPartialViewLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.AreaPartialViewLocationFormats, pathTransformations); + newEngine.ViewLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.ViewLocationFormats, pathTransformations); + newEngine.MasterLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.MasterLocationFormats, pathTransformations); + newEngine.PartialViewLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.PartialViewLocationFormats, pathTransformations); + + if (precompiledEngine != null) + { + newEngine.AreaViewLocationFormats = newEngine.AreaViewLocationFormats.Select(p => FrontendManager.VirtualPathBuilder.RemoveParams(p)).ToArray(); + newEngine.AreaMasterLocationFormats = newEngine.AreaMasterLocationFormats.Select(p => FrontendManager.VirtualPathBuilder.RemoveParams(p)).ToArray(); + newEngine.AreaPartialViewLocationFormats = newEngine.AreaPartialViewLocationFormats.Select(p => FrontendManager.VirtualPathBuilder.RemoveParams(p)).ToArray(); + newEngine.ViewLocationFormats = newEngine.ViewLocationFormats.Select(p => FrontendManager.VirtualPathBuilder.RemoveParams(p)).ToArray(); + newEngine.MasterLocationFormats = newEngine.MasterLocationFormats.Select(p => FrontendManager.VirtualPathBuilder.RemoveParams(p)).ToArray(); + newEngine.PartialViewLocationFormats = newEngine.PartialViewLocationFormats.Select(p => FrontendManager.VirtualPathBuilder.RemoveParams(p)).ToArray(); + } + + return newEngine; + } + + private static string[] AppendControllerVirtualPath(string[] originalPaths, IList> pathTransformations) + { + var result = originalPaths.ToList(); + foreach (var transform in pathTransformations) + { + result.AddRange(originalPaths.Select(transform)); + } + + return result.ToArray(); + } + + /// + /// Gets the view paths of the given controller. + /// + /// The controller. + private static IEnumerable GetViewLocations(Controller controller) + { + return ControllerExtensions.GetControllerViewEngineLocations(controller, v => v.ViewLocationFormats); + } + + private static IEnumerable GetControllerViewEngineLocations(Controller controller, Func locationExtractor) + { + string controllerName; + if (controller.RouteData != null && controller.RouteData.Values["controller"] as string != null) + controllerName = controller.RouteData.Values["controller"] as string; + else + controllerName = FrontendManager.ControllerFactory.GetControllerName(controller.GetType()); + + return controller.ViewEngineCollection.OfType() + .SelectMany(v => locationExtractor(v)) + .Distinct() + .Select(v => v.Replace("{1}", controllerName)) + .Select(VirtualPathUtility.GetDirectory) + .Distinct(); + } + + /// + /// Gets the file extensions that this controller will recognize when resolving view templates. + /// + /// The controller. + private static IEnumerable GetViewFileExtensions(Controller controller) + { + return controller.ViewEngineCollection.OfType() + .SelectMany(v => v.FileExtensions.Select(e => "." + e)) + .Distinct(); + } + + private static IEnumerable GetViews(Controller controller, IEnumerable viewLocations, string moduleName = null) + { + var viewExtensions = ControllerExtensions.GetViewFileExtensions(controller); + var widgetName = controller.RouteData != null ? controller.RouteData.Values["widgetName"] as string : null; + + var assembly = controller.GetType().Assembly; + var baseFiles = ControllerExtensions.GetViewsForAssembly(assembly, viewLocations, viewExtensions, moduleName).ToList(); + + foreach (var viewEngine in controller.ViewEngineCollection) + { + var compositeViewEngine = viewEngine as CompositePrecompiledMvcEngineWrapper; + if (compositeViewEngine != null) + { + var files = compositeViewEngine.GetViews(viewLocations); + baseFiles.AddRange(files); + } + } + var filesForBasePath = baseFiles.Distinct(); + + if (!widgetName.IsNullOrEmpty()) + { + var widgetAssembly = FrontendManager.ControllerFactory.ResolveControllerType(widgetName).Assembly; + var widgetFiles = ControllerExtensions.GetViewsForAssembly(widgetAssembly, viewLocations, viewExtensions); + return filesForBasePath.Union(widgetFiles); + } + + return filesForBasePath; + } + + private static IEnumerable GetViews(Controller controller, IEnumerable viewLocations, ref Dictionary viewFilesMappings, string moduleName = null) + { + var viewExtensions = ControllerExtensions.GetViewFileExtensions(controller); + var widgetName = controller.RouteData != null ? controller.RouteData.Values["widgetName"] as string : null; + + var baseFiles = ControllerExtensions.GetViewsForAssembly(controller.GetType().Assembly, viewLocations, viewExtensions, + ref viewFilesMappings, moduleName); + if (!widgetName.IsNullOrEmpty()) + { + var widgetAssembly = FrontendManager.ControllerFactory.ResolveControllerType(widgetName).Assembly; + var widgetFiles = ControllerExtensions.GetViewsForAssembly(widgetAssembly, viewLocations, viewExtensions, + ref viewFilesMappings, moduleName); + return baseFiles.Union(widgetFiles); + } + + return baseFiles; + } + + private static IEnumerable GetViewsForAssembly(Assembly assembly, IEnumerable viewLocations, IEnumerable viewExtensions, string moduleName = null) + { + var pathDef = FrontendManager.VirtualPathBuilder.GetPathDefinition(assembly, moduleName); + return viewLocations + .SelectMany(l => ControllerExtensions.GetViewsForPath(pathDef, l, viewExtensions)) + .Distinct(); + } + + private static IEnumerable GetViewsForAssembly(Assembly assembly, IEnumerable viewLocations, IEnumerable viewExtensions, + ref Dictionary viewFilesMappings, string moduleName = null) + { + var pathDef = FrontendManager.VirtualPathBuilder.GetPathDefinition(assembly, moduleName); + var views = new List(); + + foreach (var viewLocation in viewLocations) + { + views.AddRange(ControllerExtensions.GetViewsForPath(pathDef, viewLocation, viewExtensions, ref viewFilesMappings)); + } + + return views.Distinct(); + } + + private static IEnumerable GetViewsForPath(PathDefinition definition, string path, IEnumerable viewExtensions) + { + var files = ObjectFactory.Resolve().GetFiles(definition, path); + + if (files != null) + { + var returnResult = files + .Where(f => viewExtensions.Any(e => f.EndsWith(e, StringComparison.Ordinal))) + .Select(VirtualPathUtility.GetFileName) + .Select(System.IO.Path.GetFileNameWithoutExtension) + .Distinct(); + + return returnResult; + } + + return new string[] { }; + } + + private static IEnumerable GetViewsForPath(PathDefinition definition, string path, IEnumerable viewExtensions, ref Dictionary viewFilesMappings) + { + var views = new List(); + var files = ObjectFactory.Resolve().GetFiles(definition, path); + + if (files != null) + { + foreach (var file in files) + { + if (viewExtensions.Any(e => file.EndsWith(e, StringComparison.Ordinal))) + { + var fileName = VirtualPathUtility.GetFileName(file); + var fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(fileName); + if (!viewFilesMappings.ContainsKey(fileNameWithoutExtension)) + { + viewFilesMappings.Add(fileNameWithoutExtension, file); + views.Add(fileNameWithoutExtension); + } + } + } + } + + return views; + } + + #endregion + + #region Private Fields + + private static readonly Dictionary ViewEngineCollections = new Dictionary(); + + #endregion + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerModelFactory.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerModelFactory.cs index 1774b9e9d..299f4a68b 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerModelFactory.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerModelFactory.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Reflection; using System.Web.Mvc; using Ninject; @@ -25,21 +24,34 @@ public static T GetModel(Type controllerType, IDictionary con if (controllerType == null) throw new ArgumentNullException("controllerType"); - using (var kernel = new StandardKernel()) + ConstructorArgument[] parameters; + if (constructorParameters != null && constructorParameters.Count > 0) { - var assemblies = ControllerModelFactory.GetTypeHierarchyAssemblies(controllerType); - kernel.Load(assemblies); + parameters = new ConstructorArgument[constructorParameters.Count]; - var parameters = new List(); - if (constructorParameters != null && constructorParameters.Any()) + int i = 0; + foreach (var param in constructorParameters) { - foreach (var param in constructorParameters) - { - parameters.Add(new ConstructorArgument(param.Key, param.Value)); - } + parameters[i] = new ConstructorArgument(param.Key, param.Value); + i++; } + } + else + { + parameters = new ConstructorArgument[0]; + } - return kernel.Get(parameters.ToArray()); + if (FrontendModule.Current != null) + { + return FrontendModule.Current.DependencyResolver.Get(parameters); + } + else + { + using (var kernel = new StandardKernel()) + { + kernel.Load(ControllerModelFactory.GetTypeHierarchyAssemblies(controllerType)); + return kernel.Get(parameters); + } } } @@ -50,7 +62,11 @@ private static IEnumerable GetTypeHierarchyAssemblies(Type type) while (currentType != null && currentType != typeof(Controller) && currentType != typeof(object)) { - result.Add(currentType.Assembly); + if (!result.Contains(currentType.Assembly)) + { + result.Add(currentType.Assembly); + } + currentType = currentType.BaseType; } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/FeatherEnabledToolboxFilter.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/FeatherEnabledToolboxFilter.cs new file mode 100644 index 000000000..a0c4923ec --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/FeatherEnabledToolboxFilter.cs @@ -0,0 +1,36 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Telerik.Sitefinity.DesignerToolbox; +using Telerik.Sitefinity.Services; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers +{ + /// + /// Determines which controls should be visible in the toolbox of the when Feather is deactivated. + /// + internal class FeatherEnabledToolboxFilter : IToolboxFilter + { + /// + public virtual bool IsSectionVisible(IToolboxSection section, IToolboxFilterContext context) + { + return true; + } + + /// + public virtual bool IsToolVisible(IToolboxItem tool) + { + var isFeatherDeactivated = SystemManager.GetModule("Feather") == null; + if (isFeatherDeactivated) + { + var isFeatherWidget = tool.ControllerType.StartsWith("Telerik.Sitefinity.Frontend", StringComparison.Ordinal); + if (isFeatherWidget) + return false; + } + + return true; + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/FrontendControllerFactory.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/FrontendControllerFactory.cs index 05474116d..11fd93e9a 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/FrontendControllerFactory.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/FrontendControllerFactory.cs @@ -1,130 +1,187 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes; -using Telerik.Sitefinity.Frontend.Resources; -using Telerik.Sitefinity.Mvc; - -namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers -{ - /// - /// This class extends the by adding additional virtual paths for controller view engines. - /// - public class FrontendControllerFactory : SitefinityControllerFactory - { - #region Overridden members - - /// - /// Creates the specified controller by using the specified request context. - /// - /// The controller. - /// - /// The context of the HTTP request, which includes the HTTP context and route data. - /// - /// The name of the controller. - /// - /// The parameter is null. - /// - /// - /// The parameter is null or empty. - /// - public override IController CreateController(RequestContext requestContext, string controllerName) - { - var baseController = base.CreateController(requestContext, controllerName); - var controller = baseController as Controller; - if (controller != null) - { - this.EnhanceViewEngines(controller); - } - - return baseController; - } - - #endregion - - #region Private members - - private static IList> GetControllerPathTransformations(Controller controller, string customPath) - { - var packagesManager = new PackageManager(); - var currentPackage = packagesManager.GetCurrentPackage(); - var pathTransformations = new List>(); - - if (controller.RouteData != null && controller.RouteData.Values.ContainsKey("widgetName")) - { - var widgetName = (string)controller.RouteData.Values["widgetName"]; - var controllerType = FrontendManager.ControllerFactory.ResolveControllerType(widgetName); - var widgetVp = AppendDefaultPath(FrontendManager.VirtualPathBuilder.GetVirtualPath(controllerType)); - pathTransformations.Add(FrontendControllerFactory.GetPathTransformation(widgetVp, currentPackage, widgetName)); - } - - var controllerVp = customPath ?? AppendDefaultPath(FrontendManager.VirtualPathBuilder.GetVirtualPath(controller.GetType().Assembly)); - pathTransformations.Add(FrontendControllerFactory.GetPathTransformation(controllerVp, currentPackage)); - - return pathTransformations; - } - - private static Func GetPathTransformation(string controllerVirtualPath, string currentPackage, string widgetName = null) - { - return path => - { - var result = path.Replace("~/", "~/" + controllerVirtualPath); - - if (!widgetName.IsNullOrEmpty()) - { - // {1} is the ControllerName argument in VirtualPathProviderViewEngines - result = result.Replace("{1}", widgetName); - } - - if (!currentPackage.IsNullOrEmpty()) - result = result + "#" + currentPackage + Path.GetExtension(path); - - return result; - }; - } - - private static string AppendDefaultPath(string virtualPath) - { - return VirtualPathUtility.AppendTrailingSlash(virtualPath) + "Mvc/"; - } - - private void EnhanceViewEngines(Controller controller) - { - var enhanceAttr = this.GetEnhanceAttribute(controller.GetType()); - if (!enhanceAttr.Disabled) - { - controller.UpdateViewEnginesCollection(GetControllerPathTransformations(controller, enhanceAttr.VirtualPath)); - } - } - - private EnhanceViewEnginesAttribute GetEnhanceAttribute(Type controllerType) - { - var enhanceAttr = controllerType.GetCustomAttributes(typeof(EnhanceViewEnginesAttribute), true).FirstOrDefault() as EnhanceViewEnginesAttribute; - if (enhanceAttr != null) - { - return enhanceAttr; - } - - enhanceAttr = new EnhanceViewEnginesAttribute - { - Disabled = !this.IsInDefaultMvcNamespace(controllerType), - VirtualPath = - AppendDefaultPath( - FrontendManager.VirtualPathBuilder.GetVirtualPath( - controllerType.Assembly)) - }; - return enhanceAttr; - } - - private bool IsInDefaultMvcNamespace(Type controller) - { - var expectedTypeName = controller.Assembly.GetName().Name + ".Mvc.Controllers." + controller.Name; - return string.Equals(expectedTypeName, controller.FullName, StringComparison.OrdinalIgnoreCase); - } - #endregion - } -} +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Web; +using System.Web.Mvc; +using System.Web.Routing; +using Ninject; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers.Attributes; +using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Mvc; +using Telerik.Sitefinity.Pages.Model; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers +{ + /// + /// This class extends the by adding additional virtual paths for controller view engines. + /// + public class FrontendControllerFactory : SitefinityControllerFactory + { + #region Public members + + /// + /// Creates the specified controller by using the specified request context. + /// + /// The controller. + /// + /// The context of the HTTP request, which includes the HTTP context and route data. + /// + /// The name of the controller. + /// + /// The parameter is null. + /// + /// + /// The parameter is null or empty. + /// + public override IController CreateController(RequestContext requestContext, string controllerName) + { + var baseController = base.CreateController(requestContext, controllerName); + var controller = baseController as Controller; + if (controller != null) + { + FrontendControllerFactory.EnhanceViewEngines(controller); + } + + return baseController; + } + + /// + /// Enhances the view engines. + /// + /// The controller. + internal static void EnhanceViewEngines(Controller controller) + { + var enhanceAttr = FrontendControllerFactory.GetEnhanceAttribute(controller.GetType()); + if (!enhanceAttr.Disabled) + { + controller.UpdateViewEnginesCollection(() => FrontendControllerFactory.GetControllerPathTransformations(controller, enhanceAttr.VirtualPath)); + } + } + + #endregion + + #region Protected members + + /// + protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) + { + object controllerObject = FrontendModule.Current.DependencyResolver.Get(controllerType); + IController controller = (IController)controllerObject; + + return controller; + } + + #endregion + + #region Private members + + private static IList> GetControllerPathTransformations(Controller controller, string customPath) + { + var packagesManager = new PackageManager(); + var currentPackage = packagesManager.GetCurrentPackage(); + var pathTransformations = new List>(); + + var controllerVp = customPath ?? AppendDefaultPath(FrontendManager.VirtualPathBuilder.GetVirtualPath(controller.GetType().Assembly)); + FrontendControllerFactory.AddDynamicControllerPathTransformations(controller, controllerVp, currentPackage, pathTransformations); + + if (controller.RouteData != null && controller.RouteData.Values.ContainsKey("widgetName")) + { + var widgetName = (string)controller.RouteData.Values["widgetName"]; + var controllerType = FrontendManager.ControllerFactory.ResolveControllerType(widgetName); + var widgetVp = AppendDefaultPath(FrontendManager.VirtualPathBuilder.GetVirtualPath(controllerType)); + pathTransformations.Add(FrontendControllerFactory.GetPathTransformation(widgetVp, currentPackage, widgetName)); + } + + pathTransformations.Add(FrontendControllerFactory.GetPathTransformation(controllerVp, currentPackage)); + + var frontendVp = AppendDefaultPath(FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(FrontendControllerFactory).Assembly)); + if (!string.Equals(controllerVp, frontendVp, StringComparison.OrdinalIgnoreCase)) + { + pathTransformations.Add(FrontendControllerFactory.GetPathTransformation(frontendVp, currentPackage)); + } + + return pathTransformations; + } + + private static void AddDynamicControllerPathTransformations(Controller controller, string virtualPath, string currentPackage, List> pathTransformations) + { + var dynamicControllerWidgetName = controller.ResolveDynamicControllerWidgetName(); + if (string.IsNullOrEmpty(dynamicControllerWidgetName)) + return; + + pathTransformations.Add(FrontendControllerFactory.GetPathTransformation(virtualPath, currentPackage, dynamicControllerWidgetName)); + } + + private static Func GetPathTransformation(string controllerVirtualPath, string currentPackage, string widgetName = null) + { + return path => + { + var result = path.Replace("~/", "~/" + controllerVirtualPath); + + if (!widgetName.IsNullOrEmpty()) + { + // {1} is the ControllerName argument in VirtualPathProviderViewEngines + result = result.Replace("{1}", widgetName); + } + + if (!currentPackage.IsNullOrEmpty()) + result = result + "#" + currentPackage + Path.GetExtension(path); + + return result; + }; + } + + private static string AppendDefaultPath(string virtualPath) + { + return VirtualPathUtility.AppendTrailingSlash(virtualPath) + "Mvc/"; + } + + private static EnhanceViewEnginesAttribute GetEnhanceAttribute(Type controllerType) + { + var enhanceAttr = controllerType.GetCustomAttributes(typeof(EnhanceViewEnginesAttribute), true).FirstOrDefault() as EnhanceViewEnginesAttribute; + if (enhanceAttr != null) + { + return enhanceAttr; + } + + var key = controllerType.FullName; + + if (!FrontendControllerFactory.EnhanceAttributes.ContainsKey(key)) + { + lock (FrontendControllerFactory.EnhanceAttributes) + { + if (!FrontendControllerFactory.EnhanceAttributes.ContainsKey(key)) + { + var newEnhanceAttr = new EnhanceViewEnginesAttribute + { + Disabled = !FrontendControllerFactory.IsInDefaultMvcNamespace(controllerType), + VirtualPath = AppendDefaultPath(FrontendManager.VirtualPathBuilder.GetVirtualPath(controllerType.Assembly)) + }; + + FrontendControllerFactory.EnhanceAttributes.Add(key, newEnhanceAttr); + } + } + } + + enhanceAttr = FrontendControllerFactory.EnhanceAttributes[key]; + + return enhanceAttr; + } + + private static bool IsInDefaultMvcNamespace(Type controller) + { + var expectedTypeName = controller.Assembly.GetName().Name + ".Mvc.Controllers." + controller.Name; + return string.Equals(expectedTypeName, controller.FullName, StringComparison.OrdinalIgnoreCase); + } + + #endregion + + #region Fields + + private static readonly Dictionary EnhanceAttributes = new Dictionary(); + + #endregion + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ICanFilterByParent.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ICanFilterByParent.cs new file mode 100644 index 000000000..be2317a25 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ICanFilterByParent.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers +{ + /// + /// Classes that implement this interface can filter items by parent item resolved from URL + /// + public interface ICanFilterByParent + { + /// + /// Gets the parent types. + /// + /// Collection of parent types to filter by. + IEnumerable GetParentTypes(); + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/IRouteMapper.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/IRouteMapper.cs new file mode 100644 index 000000000..1802ba7fb --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/IRouteMapper.cs @@ -0,0 +1,18 @@ +using System.Web.Routing; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers +{ + /// + /// Classes that implement this interface can provide custom routing logic. + /// + public interface IRouteMapper + { + /// + /// Maps the route parameters from URL and returns true of the URL is a valid route. + /// + /// The URL parameters. + /// The request context. + /// True if the URL is a valid route. False otherwise. + bool TryMapRouteParameters(string[] urlParams, RequestContext requestContext); + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/MvcWidgetProxy.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/MvcWidgetProxy.cs new file mode 100644 index 000000000..95dcf3821 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/MvcWidgetProxy.cs @@ -0,0 +1,75 @@ +using System; +using System.ComponentModel; +using System.Web.Mvc; +using Telerik.Sitefinity.Mvc.Proxy; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers +{ + /// + /// Web forms control that is used as a proxy for MVC controllers and has information about the specific widget it is used for. + /// + public class MvcWidgetProxy : MvcControllerProxy + { + /// + /// Gets or sets the name of the widget. + /// + /// The name of the widget. + [Browsable(true)] + public string WidgetName + { + get + { + return this.widgetName; + } + + set + { + this.widgetName = value; + UpdateControllerViewBag(this.Controller); + } + } + + /// + /// Gets or sets the name of the module. + /// + /// The name of the module. + [Browsable(true)] + public string ModuleName + { + get + { + return this.moduleName; + } + + set + { + this.moduleName = value; + UpdateControllerViewBag(this.Controller); + } + } + + /// + protected override void OnControllerInitialized(Controller controller) + { + UpdateControllerViewBag(controller); + } + + private string widgetName; + private string moduleName; + + private void UpdateControllerViewBag(Controller controller) + { + if (controller == null || controller.ViewBag == null) return; + + if (!this.WidgetName.IsNullOrEmpty()) + { + controller.ViewBag.WidgetName = this.WidgetName; + } + + if (!this.ModuleName.IsNullOrEmpty()) + { + controller.ViewBag.ModuleName = this.ModuleName; + } + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/VoidViewLocationCache.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/VoidViewLocationCache.cs deleted file mode 100644 index 3145dc651..000000000 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/VoidViewLocationCache.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Web; -using System.Web.Mvc; - -namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers -{ - /// - /// This class is used to disable view location cache for controllers. - /// - internal class VoidViewLocationCache : IViewLocationCache - { - /// - /// Gets the view location by using the specified HTTP context and the cache key. - /// - /// The HTTP context. - /// The cache key. - /// - /// The view location. - /// - public string GetViewLocation(HttpContextBase httpContext, string key) - { - return null; - } - - /// - /// Inserts the specified view location into the cache by using the specified HTTP context and the cache key. - /// - /// The HTTP context. - /// The cache key. - /// The virtual path. - public void InsertViewLocation(HttpContextBase httpContext, string key, string virtualPath) - { - // Do nothing. We don't want cache. - } - } -} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/HttpHandlerExtensions.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/HttpHandlerExtensions.cs new file mode 100644 index 000000000..4a7b8ab73 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/HttpHandlerExtensions.cs @@ -0,0 +1,44 @@ +using System; +using System.Linq; +using System.Web; +using System.Web.UI; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure +{ + /// + /// Holds all extension methods for transforming an to + /// + public static class HttpHandlerExtensions + { + /// + /// Casts the IHttpHandler to Page. If the handler is a wrapper of this page - extracts it. + /// + /// The handler. + /// + /// The Page or null if the cast failed. + /// + public static Page GetPageHandler(this IHttpHandler handler) + { + Page page = null; + + if (handler != null) + { + page = handler as Page; + + if (page == null) + { + var pageHandlerWrapperType = Type.GetType("Telerik.Sitefinity.Web.PageHandlerWrapper, Telerik.Sitefinity"); + if (handler.GetType() == pageHandlerWrapperType) + { + var baseHandlerField = pageHandlerWrapperType.GetField("baseHandler", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); + var valueObject = baseHandlerField.GetValue(handler); + + page = valueObject as Page; + } + } + } + + return page; + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/InfrastructureResources.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/InfrastructureResources.cs new file mode 100644 index 000000000..f1cab8b98 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/InfrastructureResources.cs @@ -0,0 +1,284 @@ +using System.Diagnostics.CodeAnalysis; +using Telerik.Sitefinity.Localization; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure +{ + /// + /// Localizable strings for the Frontend infrastructure. + /// + [ObjectInfo(typeof(InfrastructureResources), Title = "InfrastructureResourcesTitle", Description = "InfrastructureResourcesDescription")] + public class InfrastructureResources : Resource + { + /// + /// Title for the infrastructure resources class. + /// + [ResourceEntry("InfrastructureResourcesTitle", + Value = "Frontend Infrastructure resources", + Description = "Title for the infrastructure resources class.", + LastModified = "2015/01/12")] + public string InfrastructureResourcesTitle + { + get + { + return this["InfrastructureResourcesTitle"]; + } + } + + /// + /// Description for the infrastructure resources class. + /// + [ResourceEntry("InfrastructureResourcesDescription", + Value = "Localizable strings for the Frontend infrastructure.", + Description = "Description for the infrastructure resources class.", + LastModified = "2015/01/12")] + public string InfrastructureResourcesDescription + { + get + { + return this["InfrastructureResourcesDescription"]; + } + } + + /// + /// Message that is to be displayed for a widget when its controller execution throws exception. + /// + [ResourceEntry("ErrorExecutingController", + Value = "Exception occured while executing the controller. Check error logs for details.", + Description = "Description for the infrastructure resources class.", + LastModified = "2015/01/12")] + public string ErrorExecutingController + { + get + { + return this["ErrorExecutingController"]; + } + } + + /// + /// Caption of the Feather config section. + /// + [ResourceEntry("FeatherConfigCaption", + Value = "Feather", + Description = "Caption of the Feather config section.", + LastModified = "2015/11/23")] + public string FeatherConfigCaption + { + get + { + return this["FeatherConfigCaption"]; + } + } + + /// + /// Description of the Feather config section. + /// + [ResourceEntry("FeatherConfigDescription", + Value = "Configuration for the Feather module.", + Description = "Description of the Feather config section.", + LastModified = "2015/11/23")] + public string FeatherConfigDescription + { + get + { + return this["FeatherConfigDescription"]; + } + } + + /// + /// Caption of the 'Disable precompiled views' checkbox. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Precompilation")] + [ResourceEntry("DisablePrecompilationCaption", + Value = "Disable precompiled views", + Description = "Caption of the 'Disable precompiled views' checkbox.", + LastModified = "2015/11/23")] + public string DisablePrecompilationCaption + { + get + { + return this["DisablePrecompilationCaption"]; + } + } + + /// + /// Description of the 'Disable precompiled views' checkbox. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Precompilation")] + [ResourceEntry("DisablePrecompilationDescription", + Value = "Feather will use precompiled view templated unless this checkbox is checked.", + Description = "Description of the 'Disable precompiled views' checkbox.", + LastModified = "2015/11/23")] + public string DisablePrecompilationDescription + { + get + { + return this["DisablePrecompilationDescription"]; + } + } + + /// + /// Caption of the 'Always use precompiled version' checkbox. + /// + [ResourceEntry("AlwaysUsePrecompiledVersionCaption", + Value = "Always use precompiled version", + Description = "Caption of the 'Always use precompiled version' checkbox.", + LastModified = "2015/11/23")] + public string AlwaysUsePrecompiledVersionCaption + { + get + { + return this["AlwaysUsePrecompiledVersionCaption"]; + } + } + + /// + /// Description of the 'Always use precompiled version' checkbox. + /// + [ResourceEntry("AlwaysUsePrecompiledVersionDescription", + Value = "When checked Feather will always use the precompiled version of a resource regardless of changes to physical files.", + Description = "Description of the 'Always use precompiled version' checkbox.", + LastModified = "2015/11/23")] + public string AlwaysUsePrecompiledVersionDescription + { + get + { + return this["AlwaysUsePrecompiledVersionDescription"]; + } + } + + /// + /// Caption of the 'Log usage of precompiled views' checkbox. + /// + [ResourceEntry("LogPrecompiledViewUsageCaption", + Value = "Log usage of precompiled views", + Description = "Caption of the 'Log usage of precompiled views' checkbox.", + LastModified = "2015/11/24")] + public string LogPrecompiledViewUsageCaption + { + get + { + return this["LogPrecompiledViewUsageCaption"]; + } + } + + /// + /// Description of the 'Log usage of precompiled views' checkbox. + /// + [ResourceEntry("LogPrecompiledViewUsageDescription", + Value = "Feather will log when it uses precompiled views in the Trace log. Use for debugging.", + Description = "Description of the 'Log usage of precompiled views' checkbox.", + LastModified = "2015/11/24")] + public string LogPrecompiledViewUsageDescription + { + get + { + return this["LogPrecompiledViewUsageDescription"]; + } + } + + /// + /// Caption of the 'Log usage of precompiled views' checkbox. + /// + [ResourceEntry("UseNamedParametersRoutingCaption", + Value = "Use named route parameters", + Description = "Caption of the 'Use named route parameters' checkbox.", + LastModified = "2019/6/20")] + public string UseNamedParametersRoutingCaption + { + get + { + return this["UseNamedParametersRoutingCaption"]; + } + } + + /// + /// Description of the 'Log usage of precompiled views' checkbox. + /// + [ResourceEntry("UseNamedParametersRoutingDescription", + Value = "If enabled, the frontend routes will work only with named params (e.g /tag/london/page/2); otherwise, the route will be /london/2.", + Description = "Description of the 'Use named route parameters' checkbox.", + LastModified = "2019/6/20")] + public string UseNamedParametersRoutingDescription + { + get + { + return this["UseNamedParametersRoutingDescription"]; + } + } + + /// + /// Detailed error message when cannot find template in MVC form. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "Telerik.Sitefinity.Localization.Resource.get_Item(System.String)"), ResourceEntry("CannotFindTemplateMvcForm", + Value = "Cannot find template \"{0}\". Most probably it is specific for a particular resource package which is not applied in the current context. Try duplicating the template in SitefinityWebApp root folder while keeping the same folder hierarchy.", + Description = "Detailed error message when cannot find template in MVC form.", + LastModified = "2016/11/28")] + public string CannotFindTemplateMvcForm + { + get + { + return base["CannotFindTemplateMvcForm"]; + } + } + + /// + /// Title of the "Use cached controller container assemblies" setting + /// + [ResourceEntry("UseCachedControllerContainerAssembliesTitle", + Value = "Use cached controller container assemblies", + Description = "Title of the setting", + LastModified = "2019/9/04")] + public string UseCachedControllerContainerAssembliesTitle + { + get + { + return this["UseCachedControllerContainerAssembliesTitle"]; + } + } + + /// + /// Description of the "Use cached controller container assemblies" setting + /// + [ResourceEntry("UseCachedControllerContainerAssembliesDescription", + Value = "Use a JSON with the location to the assemblies that contain controllers.", + Description = "Description of the setting", + LastModified = "2019/9/04")] + public string UseCachedControllerContainerAssembliesDescription + { + get + { + return this["UseCachedControllerContainerAssembliesDescription"]; + } + } + + /// + /// Caption of the NinjectLoadExtensions config property + /// + [ResourceEntry("NinjectLoadExtensionsTitle", + Value = "Automatically load Ninject extensions", + Description = "Caption of the NinjectLoadExtensions config property", + LastModified = "2019/09/18")] + public string NinjectLoadExtensionsTitle + { + get + { + return this["NinjectLoadExtensionsTitle"]; + } + } + + /// + /// Description of the NinjectLoadExtensions config property + /// + [ResourceEntry("NinjectLoadExtensionsDescription", + Value = "Indicates whether the Ninject kernel should automatically load extensions at startup", + Description = "Description of the NinjectLoadExtensions config property", + LastModified = "2019/09/18")] + public string NinjectLoadExtensionsDescription + { + get + { + return this["NinjectLoadExtensionsDescription"]; + } + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/DuplicateSectionException.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/DuplicateSectionException.cs new file mode 100644 index 000000000..edbc0134f --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/DuplicateSectionException.cs @@ -0,0 +1,54 @@ +using System; +using System.Runtime.Serialization; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts +{ + /// + /// This type of exception is thrown when sections with duplicating names are found on the current page. + /// + [Serializable] + public class DuplicateSectionException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public DuplicateSectionException() + : base() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// Name of the section. + public DuplicateSectionException(string sectionName) + : base(DuplicateSectionException.ExceptionMessage(sectionName)) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// Name of the section. + /// The inner exception. + public DuplicateSectionException(string sectionName, Exception innerException) + : base(DuplicateSectionException.ExceptionMessage(sectionName), innerException) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + protected DuplicateSectionException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + + private static string ExceptionMessage(string sectionName) + { + return "Duplicate section name found: \"{0}\".".Arrange(sectionName); + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutInitializer.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutInitializer.cs index b2b452f0f..f9264fd4b 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutInitializer.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutInitializer.cs @@ -1,22 +1,117 @@ -using Telerik.Microsoft.Practices.Unity; -using Telerik.Sitefinity.Abstractions; -using Telerik.Sitefinity.Abstractions.VirtualPath; - -namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts -{ - /// - /// This class contains logic for registration and initialization of the layouts. - /// - public class LayoutInitializer - { - /// - /// Registers the types and resolvers related to the layouts functionality. - /// - public virtual void Initialize() - { - ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); - - VirtualPathManager.AddVirtualFileResolver(string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}{1}{2}", "~/", LayoutVirtualFileResolver.ResolverPath, "*"), typeof(LayoutVirtualFileResolver).FullName); - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using Telerik.Microsoft.Practices.Unity; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Abstractions.VirtualPath; +using Telerik.Sitefinity.Data; +using Telerik.Sitefinity.Frontend.FilesMonitoring; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Security; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts +{ + /// + /// This class contains logic for registration and initialization of the layouts. + /// + internal class LayoutInitializer : IInitializer + { + /// + /// Registers the types and resolvers related to the layouts functionality. + /// + public virtual void Initialize() + { + ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); + ObjectFactory.Container.RegisterType("PureMvcPageResolver", new ContainerControlledLifetimeManager(), new InjectionConstructor()); + + VirtualPathManager.AddVirtualFileResolver(string.Format(System.Globalization.CultureInfo.InvariantCulture, "~/{0}*", LayoutVirtualFileResolver.ResolverPath), typeof(LayoutVirtualFileResolver).FullName); + ObjectFactory.Container.RegisterType(); + ObjectFactory.Container.RegisterType(); + ObjectFactory.Container.RegisterType(); + + this.mvcVersioningRoute = new System.Web.Routing.Route("Sitefinity/Versioning/{itemId}/{VersionNumber}", ObjectFactory.Resolve()); + System.Web.Routing.RouteTable.Routes.Insert(1, this.mvcVersioningRoute); + + PageManager.Executing -= LayoutInitializer.Provider_Executing; + PageManager.Executing += LayoutInitializer.Provider_Executing; + + PageManager.Executed -= LayoutInitializer.Provider_Executed; + PageManager.Executed += LayoutInitializer.Provider_Executed; + } + + /// + /// Uninitializes the functionality related to the layouts. + /// + public virtual void Uninitialize() + { + System.Web.Routing.RouteTable.Routes.Remove(this.mvcVersioningRoute); + + PageManager.Executed -= LayoutInitializer.Provider_Executed; + PageManager.Executing -= LayoutInitializer.Provider_Executing; + } + + private System.Web.Routing.Route mvcVersioningRoute; + private const string CreatedPageTemplatesCategoryIds = "created-page-templates"; + + private static void Provider_Executing(object sender, ExecutingEventArgs args) + { + if (!(args.CommandName == "CommitTransaction" || args.CommandName == "FlushTransaction")) + return; + + var provider = sender as PageDataProvider; + + var dirtyItems = provider.GetDirtyItems(); + if (dirtyItems.Count == 0) + return; + + var createdPageTemplates = provider.GetExecutionStateData(CreatedPageTemplatesCategoryIds) as HashSet; + if (createdPageTemplates == null) + createdPageTemplates = new HashSet(); + + foreach (var item in dirtyItems) + { + SecurityConstants.TransactionActionType itemStatus = provider.GetDirtyItemStatus(item); + var pageTemplate = item as PageTemplate; + if (pageTemplate != null) + { + if (itemStatus == SecurityConstants.TransactionActionType.New && pageTemplate.Framework == PageTemplateFramework.Mvc) + { + // the template name is formulated as Bootstrap.default + var nameParts = pageTemplate.Name.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); + if (nameParts.Length > 1) + { + var package = nameParts[0]; + + // always create the template, desipite if the package is not there + // in case the client first performs a sync and then deploys the files by mistake + createdPageTemplates.Add(package); + } + } + } + } + + if (createdPageTemplates.Any()) + { + provider.SetExecutionStateData(CreatedPageTemplatesCategoryIds, createdPageTemplates); + } + } + + private static void Provider_Executed(object sender, ExecutedEventArgs args) + { + if (args.CommandName != "CommitTransaction") + return; + + var provider = sender as PageDataProvider; + var packageNames = provider.GetExecutionStateData(CreatedPageTemplatesCategoryIds) as HashSet; + if (packageNames != null) + { + provider.SetExecutionStateData(CreatedPageTemplatesCategoryIds, null); + var layoutFileManager = ObjectFactory.Resolve(Enum.GetName(typeof(ResourceType), ResourceType.Layouts)) as LayoutFileManager; + layoutFileManager.CreateTemplateCategories(packageNames, true); + } + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutMvcPageResolver.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutMvcPageResolver.cs new file mode 100644 index 000000000..83e4bc860 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutMvcPageResolver.cs @@ -0,0 +1,91 @@ +using System; +using System.Globalization; +using System.IO; +using System.Text; +using System.Web; +using System.Web.Routing; +using Telerik.Sitefinity.Abstractions.VirtualPath; +using Telerik.Sitefinity.Frontend.Mvc.Helpers; +using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Localization; +using Telerik.Sitefinity.Mvc.Rendering; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts +{ + /// + /// Instances of this class render virtual page files for pure MVC pages that can be based on a layout file. + /// + internal class LayoutMvcPageResolver : PureMvcPageResolver + { + /// + /// Determines whether the specified virtual path is path of a layout file. + /// + /// The virtual path. + /// True if the specified virtual path is path of a layout file. + public static bool IsLayoutPath(string virtualPath) + { + if (virtualPath.IsNullOrEmpty()) + return false; + + string resolverPath; + if (virtualPath.StartsWith("~/", StringComparison.OrdinalIgnoreCase)) + resolverPath = string.Format(CultureInfo.InvariantCulture, "~/{0}", LayoutVirtualFileResolver.ResolverPath); + else if (virtualPath.StartsWith("/", StringComparison.OrdinalIgnoreCase)) + resolverPath = RouteHelper.ResolveUrl(string.Format(CultureInfo.InvariantCulture, "~/{0}", LayoutVirtualFileResolver.ResolverPath), UrlResolveOptions.Rooted | UrlResolveOptions.AppendTrailingSlash); + else + resolverPath = LayoutVirtualFileResolver.ResolverPath; + + return virtualPath.StartsWith(resolverPath, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Appends markup to the virtual page file depending on the current master page. + /// + /// The master page virtual path. + /// The context. + /// The output. + /// The place holders. + /// The directives. + protected override void BuildWithMasterPage(string virtualPath, RequestContext context, StringBuilder output, CursorCollection placeHolders, DirectiveCollection directives) + { + if (LayoutMvcPageResolver.IsLayoutPath(virtualPath)) + { + SystemManager.RunWithElevatedPrivilege((args) => + { + HttpContext.Current.Items[PackageManager.CurrentPackageKey] = context.HttpContext.Items[PackageManager.CurrentPackageKey]; + base.BuildWithMasterPage(virtualPath, context, output, placeHolders, directives); + }); + } + else + { + base.BuildWithMasterPage(virtualPath, context, output, placeHolders, directives); + } + } + + /// + /// Appends the layout. + /// + /// + /// If the layout is not found error message will be rendered instead. + /// + /// The layout template. + /// The assembly information. + /// The parent place holder. + /// The place holders. + /// The layout identifier. + /// The directives. + protected override void AppendLayout(string layoutTemplate, string assemblyInfo, PlaceHolderCursor parentPlaceHolder, CursorCollection placeHolders, string layoutId, DirectiveCollection directives) + { + try + { + base.AppendLayout(layoutTemplate, assemblyInfo, parentPlaceHolder, placeHolders, layoutId, directives); + } + catch (FileNotFoundException) + { + parentPlaceHolder.Output.Append(Res.Get("CannotFindTemplate", layoutTemplate)); + } + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutRenderer.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutRenderer.cs index 40522afad..c8e6d7801 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutRenderer.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutRenderer.cs @@ -1,11 +1,14 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; +using System.Text.RegularExpressions; using System.Web; using System.Web.Hosting; using System.Web.Mvc; using System.Web.Routing; using Telerik.Sitefinity.Frontend.Mvc.Controllers; +using Telerik.Sitefinity.Frontend.Mvc.Helpers; using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; using Telerik.Sitefinity.Frontend.Resources; using Telerik.Sitefinity.Services; @@ -15,17 +18,16 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts /// /// This class builds the layout master page by using the Mvc view engines. /// - public class LayoutRenderer + internal class LayoutRenderer { #region Public methods /// /// Creates a controller instance and sets its ControllerContext depending on the current Http context. /// - /// /// The route data. - /// The context. /// + /// Can not create ControllerContext if no active HttpContext instance is available. /// Can't create Controller Context if no active HttpContext instance is available. public virtual Controller CreateController(RouteData routeData = null) { @@ -45,11 +47,11 @@ public virtual Controller CreateController(RouteData routeData = null) // add the controller routing if not existing if (!routeData.Values.ContainsKey("controller") && !routeData.Values.ContainsKey("Controller")) - routeData.Values.Add( - "controller", - controller.GetType().Name.ToLowerInvariant().Replace("controller", string.Empty)); + { + routeData.Values.Add("controller", "Generic"); + } - controller.UpdateViewEnginesCollection(this.GetPathTransformations()); + controller.UpdateViewEnginesCollection(() => this.GetPathTransformations()); // here we create the context for the controller passing the just created controller the httpcontext and the route data that we built above controller.ControllerContext = new ControllerContext(context, routeData, controller); @@ -62,23 +64,22 @@ public virtual Controller CreateController(RouteData routeData = null) /// /// The context. /// The view path. - /// The model. - /// if set to true the view should be partial. + /// /// /// View cannot be found. - public virtual string RenderViewToString(ControllerContext context, string viewPath, object model = null, bool isPartial = false) + public virtual string RenderViewToString(ControllerContext context, string viewPath, bool placeholdersOnly = false) { if (context == null) throw new ArgumentNullException("context"); if (viewPath == null) throw new ArgumentNullException("viewPath"); - + string result = null; IView view = null; // Obtaining the view engine result - var viewEngineResult = this.GetViewEngineResult(context, viewPath, isPartial); + var viewEngineResult = this.GetViewEngineResult(context, viewPath, isPartial: false); if (viewEngineResult != null) view = viewEngineResult.View; @@ -86,12 +87,20 @@ public virtual string RenderViewToString(ControllerContext context, string viewP if (view != null) { // assigning the model so it can be available to the view - context.Controller.ViewData.Model = model; + context.Controller.ViewData.Model = null; + var viewVirtualPath = FrontendManager.VirtualPathBuilder.GetViewPath(view); using (var writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture)) { - var viewConext = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, writer); - view.Render(viewConext, writer); + if (placeholdersOnly && !viewVirtualPath.IsNullOrEmpty()) + { + this.RenderContentPlaceHolders(viewVirtualPath, writer); + } + else + { + var viewConext = new ViewContext(context, view, context.Controller.ViewData, context.Controller.TempData, writer); + view.Render(viewConext, writer); + } // the view must be released viewEngineResult.ViewEngine.ReleaseView(context, view); @@ -100,11 +109,10 @@ public virtual string RenderViewToString(ControllerContext context, string viewP // Add cache dependency on the virtual file that is used for rendering the view. var httpContext = SystemManager.CurrentHttpContext; - var builtView = view as BuildManagerCompiledView; - if (httpContext != null && builtView != null) + if (httpContext != null && !viewVirtualPath.IsNullOrEmpty()) { var virtualPathDependency = HostingEnvironment.VirtualPathProvider != null ? - HostingEnvironment.VirtualPathProvider.GetCacheDependency(builtView.ViewPath, null, DateTime.UtcNow) : null; + HostingEnvironment.VirtualPathProvider.GetCacheDependency(viewVirtualPath, null, DateTime.UtcNow) : null; if (virtualPathDependency != null) { httpContext.Response.AddCacheDependency(virtualPathDependency); @@ -146,16 +154,15 @@ public virtual ViewEngineResult GetViewEngineResult(ControllerContext context, s /// /// Gets the layout template. /// - /// - /// The model. - /// if set to true requested view is partial. + /// The name of the layout template to render. + /// When true the method returns a master page containing only content placeholders. /// - public virtual string GetLayoutTemplate(string templateName, object model = null, bool isPartial = false) + public virtual string GetLayoutTemplate(string templateName, bool placeholdersOnly = false) { var genericController = this.CreateController(); - var layoutHtmlString = this.RenderViewToString(genericController.ControllerContext, templateName, model, isPartial); + var layoutHtmlString = this.RenderViewToString(genericController.ControllerContext, templateName, placeholdersOnly); - if (!layoutHtmlString.IsNullOrEmpty()) + if (!layoutHtmlString.IsNullOrEmpty() && !placeholdersOnly) { var htmlProcessor = new MasterPageBuilder(); layoutHtmlString = htmlProcessor.ProcessLayoutString(layoutHtmlString); @@ -183,6 +190,27 @@ public bool LayoutExists(string templateName, bool partial = false) return result; } + /// + /// Gets the file name of the layout. + /// + /// Name of the template. + /// File name of the layout. + public string LayoutViewPath(string templateName) + { + string result = null; + + var genericController = this.CreateController(); + var viewEngineResult = this.GetViewEngineResult(genericController.ControllerContext, templateName, isPartial: false); + + if (viewEngineResult != null && viewEngineResult.View != null) + { + result = FrontendManager.VirtualPathBuilder.GetViewPath(viewEngineResult.View); + viewEngineResult.ViewEngine.ReleaseView(genericController.ControllerContext, viewEngineResult.View); + } + + return result; + } + #endregion #region Private methods @@ -214,6 +242,76 @@ private IList> GetPathTransformations() return pathTransformations; } + private void RenderContentPlaceHolders(string layoutPath, StringWriter writer) + { + writer.WriteLine("<%@ Master Language=\"C#\" %>"); + writer.WriteLine(""); + + string layoutText; + using (var layoutFile = new StreamReader(HostingEnvironment.VirtualPathProvider.GetFile(layoutPath).Open())) + { + layoutText = layoutFile.ReadToEnd(); + } + + layoutText = this.RenderPartialViews(layoutPath, layoutText, new HashSet()); + + var matches = new Regex(@"@Html\.SfPlaceHolder(?:\(\s*\""(?\w*)\""\s*\)|(?\(\)))").Matches(layoutText); + foreach (Match match in matches) + { + var group = match.Groups["placeHolder"]; + if (group.Success) + { + foreach (Capture capture in group.Captures) + { + var placeHolderName = capture.Value != "()" ? capture.Value : null; + writer.Write(LayoutsHelpers.ContentPlaceHolderMarkup(placeHolderName)); + } + } + } + + writer.Write(""); + } + + private string RenderPartialViews(string layoutPath, string layoutText, ISet processedPaths) + { + if (processedPaths.Contains(layoutPath)) + return layoutText; + + processedPaths.Add(layoutPath); + + var matches = new Regex(LayoutRenderer.PartialViewRegexPattern).Matches(layoutText); + if (matches.Count == 0) + return layoutText; + + var controller = this.CreateController(); + foreach (Match match in matches) + { + var view = match.Groups[1].Value; + + var result = this.GetViewEngineResult(controller.ControllerContext, view); + if (result == null || result.View == null) + continue; + + var viewPath = FrontendManager.VirtualPathBuilder.GetViewPath(result.View); + using (var reader = new StreamReader(HostingEnvironment.VirtualPathProvider.GetFile(viewPath).Open())) + { + var content = reader.ReadToEnd(); + content = this.RenderPartialViews(view, content, processedPaths); + + var htmlHelperStatement = match.Groups[0].Value; + layoutText = layoutText.Replace(htmlHelperStatement, content); + } + } + + return layoutText; + } + + #endregion + + #region Fields and Constants + + private const string PartialViewRegexPattern = "@Html.Partial\\(\"(.*)\",?(.*)\\)"; + #endregion } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutResolver.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutResolver.cs index 807708d8a..4f6dfcc8b 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutResolver.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutResolver.cs @@ -1,4 +1,5 @@ -using Telerik.Sitefinity.Abstractions; +using System; +using Telerik.Sitefinity.Abstractions; using Telerik.Sitefinity.Abstractions.VirtualPath; using Telerik.Sitefinity.Model; using Telerik.Sitefinity.Pages.Model; @@ -8,7 +9,7 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts /// /// This class is responsible for the operations concerning the resolving of the layout pages. /// - public class LayoutResolver : ILayoutResolver + internal class LayoutResolver : ILayoutResolver { /// /// Resolves the layout virtual path and ensures that file exist on the specified location. @@ -24,20 +25,37 @@ public virtual string GetVirtualPath(Pages.Model.IPageTemplate template) if (template.GetTemplateFramework() != PageTemplateFramework.Mvc) return null; - var hasTitle = template as IHasTitle; + string templateName; + var strictTemplate = template as PageTemplate; + if (strictTemplate != null && strictTemplate.Name != null) + { + templateName = !strictTemplate.LayoutPath.IsNullOrWhitespace() ? strictTemplate.LayoutPath : strictTemplate.Name; + } + else + { + var hasTitle = template as IHasTitle; + if (hasTitle != null) + templateName = hasTitle.GetTitle(); + else + templateName = null; + } - if (hasTitle == null) + if (templateName == null) return null; - string templateTitle = hasTitle.GetTitle(); - var virtualBuilder = new LayoutVirtualPathBuilder(); - var layoutVirtualPath = virtualBuilder.BuildPathFromTitle(templateTitle); + var virtualBuilder = this.CreateLayoutVirtualPathBuilder(); + var layoutVirtualPath = virtualBuilder.BuildPathFromName(templateName); var doesLayoutExist = VirtualPathManager.FileExists(layoutVirtualPath); if (!doesLayoutExist) layoutVirtualPath = null; return layoutVirtualPath; - } + } + + protected virtual LayoutVirtualPathBuilder CreateLayoutVirtualPathBuilder() + { + return new LayoutVirtualPathBuilder(); + } } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutVirtualFileResolver.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutVirtualFileResolver.cs index c5091ac9e..0cdb9afb8 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutVirtualFileResolver.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutVirtualFileResolver.cs @@ -4,6 +4,7 @@ using System.Text; using System.Web; using System.Web.Caching; +using System.Web.Hosting; using Telerik.Sitefinity.Abstractions.VirtualPath; using Telerik.Sitefinity.Frontend.Resources; @@ -12,7 +13,7 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts /// /// This class is responsible for locating and resolving of the Layouts. /// - public class LayoutVirtualFileResolver : IHashedVirtualFileResolver + internal class LayoutVirtualFileResolver : IVirtualFileResolver { #region Public methods @@ -45,17 +46,18 @@ public virtual bool Exists(PathDefinition definition, string virtualPath) /// The virtual path of the file to open. public virtual Stream Open(PathDefinition definition, string virtualPath) { + var placeholdersOnly = virtualPath.EndsWith(".master", StringComparison.OrdinalIgnoreCase); virtualPath = this.virtualPathBuilder.RemoveParams(virtualPath); MemoryStream outPutStream = null; virtualPath = VirtualPathUtility.ToAppRelative(virtualPath); var virtualBuilder = new LayoutVirtualPathBuilder(); var viewName = virtualBuilder.GetLayoutName(definition, virtualPath); - var layoutHtmlString = this.RenderLayout(viewName); + var layoutHtmlString = this.RenderLayout(viewName, placeholdersOnly); if (!string.IsNullOrEmpty(layoutHtmlString)) { - var layoutBytes = Encoding.Default.GetBytes(layoutHtmlString.ToCharArray()); + var layoutBytes = Encoding.UTF8.GetBytes(layoutHtmlString.ToCharArray()); outPutStream = new MemoryStream(layoutBytes); } @@ -72,37 +74,29 @@ public virtual Stream Open(PathDefinition definition, string virtualPath) /// public CacheDependency GetCacheDependency(PathDefinition definition, string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart) { - return null; - } + virtualPath = this.virtualPathBuilder.RemoveParams(virtualPath); + virtualPath = VirtualPathUtility.ToAppRelative(virtualPath); - /// - /// Returns a hash of the specified virtual paths. - /// - /// The file resolver definition. - /// The path to the primary virtual resource. - /// An array of paths to other virtual resources required by the primary virtual resource. - /// - /// A hash of the specified virtual paths. - /// - public string GetFileHash(PathDefinition definition, string virtualPath, IEnumerable virtualPathDependencies) - { - return Guid.NewGuid().ToString(); - } + var layoutVirtualPathBuilder = new LayoutVirtualPathBuilder(); + string viewName = layoutVirtualPathBuilder.GetLayoutName(definition, virtualPath); + var layoutTemplateBuilder = new LayoutRenderer(); + + if (string.IsNullOrEmpty(viewName)) + return null; + + var viewPath = layoutTemplateBuilder.LayoutViewPath(viewName); + return HostingEnvironment.VirtualPathProvider.GetCacheDependency(viewPath, virtualPathDependencies, utcStart); + } #endregion #region Private Methods - /// - /// Renders the layout. - /// - /// Filename of the layout. - /// Rendered layout as HTML. - private string RenderLayout(string pageTemplateName) + private string RenderLayout(string pageTemplateName, bool placeholdersOnly) { var layoutTemplateBuilder = new LayoutRenderer(); - return layoutTemplateBuilder.GetLayoutTemplate(pageTemplateName); + return layoutTemplateBuilder.GetLayoutTemplate(pageTemplateName, placeholdersOnly); } #endregion diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutVirtualPathBuilder.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutVirtualPathBuilder.cs index a9a3559df..34c152419 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutVirtualPathBuilder.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutVirtualPathBuilder.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -7,32 +8,29 @@ using System.Web.Hosting; using Telerik.Sitefinity.Abstractions.VirtualPath; using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Services; namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts { /// /// This class is responsible for resolving virtual paths for the layout templates. /// - public class LayoutVirtualPathBuilder + internal class LayoutVirtualPathBuilder { #region Public members /// - /// Builds the path from template title. + /// Builds the path from template name. /// - /// Title of the template. + /// Name of the template. /// Resolved path will be in the following format: "~/SfLayouts/some_title.master" - public virtual string BuildPathFromTitle(string templateTitle) + public virtual string BuildPathFromName(string templateName) { var templateFileNameParser = new TemplateTitleParser(); - var fileName = templateFileNameParser.GetLayoutName(templateTitle); + var fileName = templateFileNameParser.GetLayoutName(templateName); - var layoutVirtualPath = string.Format(System.Globalization.CultureInfo.InvariantCulture, LayoutVirtualPathBuilder.LayoutVirtualPathTemplate, LayoutVirtualPathBuilder.LayoutsPrefix, fileName, LayoutVirtualPathBuilder.LayoutSuffix); - - var packagesManager = new PackageManager(); - var currentPackage = packagesManager.GetCurrentPackage(); - - layoutVirtualPath = (new VirtualPathBuilder()).AddParams(layoutVirtualPath, currentPackage); + var layoutVirtualPath = string.Format(CultureInfo.InvariantCulture, LayoutVirtualPathBuilder.LayoutVirtualPathTemplate, LayoutVirtualPathBuilder.LayoutsPrefix, fileName, LayoutVirtualPathBuilder.LayoutSuffix); + layoutVirtualPath = this.AddVariablesToPath(layoutVirtualPath); return layoutVirtualPath; } @@ -62,6 +60,24 @@ public virtual string GetLayoutName(PathDefinition definition, string virtualPat #endregion + #region Protected and Private methods + + /// + /// Adds variable parameters to the virtual path to allow caching of multiple versions based on parameters. + /// + /// The layout virtual path. + /// The path with appended variables. + protected virtual string AddVariablesToPath(string layoutVirtualPath) + { + var packagesManager = new PackageManager(); + var currentPackage = packagesManager.GetCurrentPackage(); + layoutVirtualPath = (new VirtualPathBuilder()).AddParams(layoutVirtualPath, currentPackage ?? "_"); + + return layoutVirtualPath; + } + + #endregion + #region Constants /// diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MasterPageBuilder.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MasterPageBuilder.cs index 8952f6bee..a32de1c64 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MasterPageBuilder.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MasterPageBuilder.cs @@ -4,6 +4,7 @@ using System.Text; using System.Web; using Telerik.Sitefinity.Clients.JS; +using Telerik.Sitefinity.Configuration; using Telerik.Sitefinity.Modules.Pages; using Telerik.Sitefinity.Mvc.Rendering; using Telerik.Sitefinity.Pages.Model; @@ -18,7 +19,7 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts /// /// This class is appends all additional data to the html of the layout template. This required header elements, scripts, stylesheets, form tags, etc. /// - public class MasterPageBuilder + internal class MasterPageBuilder { #region Public methods @@ -30,7 +31,7 @@ public class MasterPageBuilder /// public virtual string ProcessLayoutString(string targetTemplate) { - var includeFormTag = this.IsFormTagRequired(); + var includeFormTag = MasterPageBuilder.IsFormTagRequired(); StringBuilder outPut = new StringBuilder(); HtmlChunk chunk = null; @@ -107,7 +108,7 @@ public virtual string AddMasterPageDirectives(string layoutHtmlValue) return layoutHtmlValue; } - #endregion + #endregion #region Protected methods @@ -115,7 +116,7 @@ public virtual string AddMasterPageDirectives(string layoutHtmlValue) /// Determines whether the form tag is required. /// /// - protected virtual bool IsFormTagRequired() + internal static bool IsFormTagRequired() { bool insertFormTag = true; var isBackendRequest = true; @@ -124,12 +125,26 @@ protected virtual bool IsFormTagRequired() if (currentContext.Items.Contains("IsBackendRequest")) isBackendRequest = (bool)currentContext.Items["IsBackendRequest"]; - if (!isBackendRequest && currentContext.Items.Contains("ServedPageNode") && currentContext.Items["ServedPageNode"] is PageSiteNode) + if (!isBackendRequest || SystemManager.IsPreviewMode) { - var servedPageNode = currentContext.Items["ServedPageNode"] as PageSiteNode; - - if (servedPageNode.Framework == Pages.Model.PageTemplateFramework.Mvc) - insertFormTag = false; + if (currentContext.Items.Contains("PageTemplateFramework") && currentContext.Items["PageTemplateFramework"] is PageTemplateFramework) + { + if ((PageTemplateFramework)currentContext.Items["PageTemplateFramework"] == PageTemplateFramework.Mvc) + { + insertFormTag = false; + } + } + else + { + if (currentContext.Items.Contains("ServedPageNode") && currentContext.Items["ServedPageNode"] is PageSiteNode) + { + var servedPageNode = currentContext.Items["ServedPageNode"] as PageSiteNode; + if (servedPageNode.Framework == Pages.Model.PageTemplateFramework.Mvc) + { + insertFormTag = false; + } + } + } } return insertFormTag; @@ -140,145 +155,60 @@ protected virtual bool IsFormTagRequired() /// /// /// Invalid SiteMap node specified. Either the current group node doesn't have child nodes or the current user does not have rights to view any of the child nodes. - protected virtual PageData GetRequestedPageData() + internal static PageData GetRequestedPageData() { - var node = this.GetRequestedPageNode(); - - if (node == null) - throw new InvalidOperationException("Invalid SiteMap node specified. Either the current group node doesn't have child nodes or the current user does not have rights to view any of the child nodes."); + var node = MasterPageBuilder.GetRequestedPageNode(); - var siteMap = (SiteMapBase)node.Provider; - var pageManager = PageManager.GetManager(siteMap.PageProviderName); - var pageData = pageManager.GetPageData(node.PageId); + if (node != null) + { + var siteMap = (SiteMapBase)node.Provider; + var pageManager = PageManager.GetManager(siteMap.PageProviderName); + var pageData = pageManager.GetPageData(node.PageId); - return pageData; + return pageData; + } + else + { + return null; + } } #endregion #region Private methods - /// - /// Appends the content of the required header. - /// - /// The string builder. - /// Invalid SiteMap node specified. Either the current group node doesn't have child nodes or the current user does not have rights to view any of the child nodes. - private void AppendRequiredHeaderContent(StringBuilder stringBuilder, bool setTitle = true) - { - var pageData = this.GetRequestedPageData(); - stringBuilder.Append(this.ResourceRegistrations()); - var robotsTag = this.GetRobotsMetaTag(pageData); - - if (!string.IsNullOrEmpty(robotsTag)) - stringBuilder.Append("\r\n\t" + robotsTag); - - if (setTitle) - stringBuilder.Append("\r\n\t" + pageData.HtmlTitle.ToString() + "\r\n\t"); - - var descriptionTag = this.GetDescriptionTag(pageData); - - if (!string.IsNullOrEmpty(descriptionTag)) - stringBuilder.Append("\r\n\t" + descriptionTag); - - var keywordsTag = this.GetKeywordsTag(pageData); - - if (!string.IsNullOrEmpty(keywordsTag)) - stringBuilder.Append("\r\n\t" + keywordsTag); - } - - /// - /// Generates the robots meta tag. - /// - /// - /// The information about the page. - /// - /// - /// Robots meta tag if page is not crawlable, otherwise empty string. - /// - private string GetRobotsMetaTag(PageData pageData) - { - if (pageData == null) - throw new ArgumentNullException("pageData"); - - if (pageData.NavigationNode.Crawlable) - return null; - - return MasterPageBuilder.RobotsMetaTag; - } - - /// - /// Generates the page keywords meta tag from page data - /// - /// The information about the page - /// Keywords meta tag if page has set keywords, otherwise null - private string GetKeywordsTag(PageData pageData) - { - if (pageData == null) - throw new ArgumentNullException("pageData"); - - if (string.IsNullOrEmpty(pageData.Keywords)) - return null; - - return string.Format(System.Globalization.CultureInfo.InvariantCulture, MasterPageBuilder.KeywordsMetaTag, pageData.Keywords); - } - - /// - /// Generates the page description meta tag from page data - /// - /// The information about the page. - /// Description meta tag if page has set description, otherwise null - private string GetDescriptionTag(PageData pageData) - { - if (pageData == null) - throw new ArgumentNullException("pageData"); - - if (string.IsNullOrEmpty(pageData.Description)) - return null; - - return string.Format(System.Globalization.CultureInfo.InvariantCulture, MasterPageBuilder.PageDescriptionMetaTag, pageData.Description); - } - - /// - /// Generates scripts tag needed on the page. Doesn't include any resources for the default themes as opposite to the hybrid mode which always includes the default frontend theme. - /// - /// - private string ResourceRegistrations() - { - var pageProxy = new PageProxy(string.Empty); - - StringBuilder sb = new StringBuilder(); - - string appPath = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath; - - if (!appPath.EndsWith("/", StringComparison.Ordinal)) - appPath = string.Concat(appPath, "/"); - - sb.Append(string.Concat("\t")); - - // add the scripts for personalization in the page - sb.Append("\t"); - - return sb.ToString(); - } - /// /// Gets the requested page node. /// /// The request context. /// /// This resolver hasn’t been invoked with the proper route handler. - private PageSiteNode GetRequestedPageNode() + private static PageSiteNode GetRequestedPageNode() { var httpContext = SystemManager.CurrentHttpContext; var requestContext = httpContext.Request.RequestContext; - var node = (PageSiteNode)requestContext.RouteData.DataTokens["SiteMapNode"]; + var node = requestContext.RouteData.DataTokens["SiteMapNode"] as PageSiteNode; + + if (node != null) + return RouteHelper.GetFirstPageDataNode(node, true); + else + return null; + } - if (node == null) - throw new ArgumentException("This resolver hasn’t been invoked with the proper route handler."); + /// + /// Appends the content of the required header. + /// + /// The string builder. + /// if set to true will set the title. + /// Invalid SiteMap node specified. Either the current group node doesn't have child nodes or the current user does not have rights to view any of the child nodes. + private void AppendRequiredHeaderContent(StringBuilder stringBuilder, bool setTitle = true) + { + var pageData = MasterPageBuilder.GetRequestedPageData(); - return RouteHelper.GetFirstPageDataNode(node, true); + if (pageData != null && setTitle) + { + stringBuilder.Append("\r\n\t" + pageData.HtmlTitle.ToString() + "\r\n\t"); + } } #endregion @@ -286,9 +216,6 @@ private PageSiteNode GetRequestedPageNode() #region Constants private const string MasterPageDirective = "<%@ Master Language=\"C#\" AutoEventWireup=\"true\" %>\r\n \r\n"; - private const string PageDescriptionMetaTag = ""; - private const string RobotsMetaTag = ""; - private const string KeywordsMetaTag = ""; #endregion } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MvcMasterPage.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MvcMasterPage.cs new file mode 100644 index 000000000..cae4f2846 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MvcMasterPage.cs @@ -0,0 +1,270 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Text; +using System.Web.Hosting; +using System.Web.UI; +using System.Web.UI.HtmlControls; +using System.Web.UI.WebControls; +using Telerik.Sitefinity.Abstractions.VirtualPath; +using Telerik.Sitefinity.Frontend.Mvc.Helpers; +using Telerik.Sitefinity.Utilities.HtmlParsing; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts +{ + /// + /// A MasterPage that is dynamically constructed from the MasterPageFile without compilation. + /// + public class MvcMasterPage : MasterPage + { + /// + /// Applies the master to the specified page. + /// + /// The page. + public void ApplyToPage(Page page) + { + this.SetMasterInternals(page); + this.InitializeAsUserControl(page); + page.Controls.Add(this); + + string masterFile; + if (page.MasterPageFile.EndsWith(".master", StringComparison.OrdinalIgnoreCase)) + masterFile = page.MasterPageFile.Left(page.MasterPageFile.Length - ".master".Length); + else + masterFile = page.MasterPageFile; + + var source = this.LayoutOutput(masterFile); + this.InitializeControls(source); + } + + private string LayoutOutput(string path) + { + var pathDefinition = new PathDefinition() + { + IsWildcard = true, + VirtualPath = UrlPath.ResolveUrl("~/" + LayoutVirtualFileResolver.ResolverPath), + ResolverName = typeof(LayoutVirtualFileResolver).FullName + }; + + //// Do not use the VirtualPathProvider chain. It may cause unexpected behavior on concurrent requests. + string result; + var resolver = new LayoutVirtualFileResolver(); + using (var streamReader = new StreamReader(resolver.Open(pathDefinition, path))) + { + result = streamReader.ReadToEnd(); + } + + return result; + } + + private void SetMasterInternals(Page page) + { + var templateControlVirtualPathProperty = typeof(TemplateControl).GetProperty("TemplateControlVirtualPath", BindingFlags.NonPublic | BindingFlags.Instance); + var masterPageFileVp = typeof(Page).GetField("_masterPageFile", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(page); + var pageVirtualPath = templateControlVirtualPathProperty.GetValue(page, null); + var templateControlVp = typeof(VirtualPathProvider).GetMethod("CombineVirtualPathsInternal", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, new object[] { pageVirtualPath, masterPageFileVp }); + templateControlVirtualPathProperty.SetValue(this, templateControlVp, null); + + typeof(Page).GetField("_master", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(page, this); + typeof(MasterPage).GetField("_ownerControl", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, page); + + var templateCollection = typeof(Page).GetField("_contentTemplateCollection", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(page); + typeof(MasterPage).GetField("_contentTemplates", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(this, templateCollection); + } + + private void InitializeControls(string source) + { + var container = new Stack(); + container.Push(this); + HtmlChunk chunk; + StringBuilder currentLiteralText; + + using (HtmlParser parser = new HtmlParser(source)) + { + parser.SetChunkHashMode(true); + parser.KeepRawHTML = true; + parser.AutoKeepScripts = true; + parser.AutoKeepComments = true; + parser.AutoExtractBetweenTagsOnly = false; + + currentLiteralText = new StringBuilder(); + while ((chunk = parser.ParseNext()) != null) + { + if (chunk.Type == HtmlChunkType.OpenTag) + { + this.HandleOpenTag(container, chunk, currentLiteralText); + } + else if (chunk.Type == HtmlChunkType.CloseTag) + { + this.HandleCloseTag(container, chunk, currentLiteralText); + } + else + { + currentLiteralText.Append(chunk.Html); + } + } + } + + this.AddIfNotEmpty(currentLiteralText.ToString(), container.Peek()); + } + + private void HandleOpenTag(Stack container, HtmlChunk chunk, StringBuilder currentLiteralText) + { + if (chunk.TagName.Equals("title", StringComparison.OrdinalIgnoreCase) && isCurrentlyInHeadTag) + { + // if we are not currently parsing the tag, then this title must be in the body and we should skip it + this.AddIfNotEmpty(currentLiteralText.ToString(), container.Peek()); + var title = new HtmlTitle(); + container.Peek().Controls.Add(title); + container.Push(title); + } + else if (chunk.TagName.Equals("head", StringComparison.OrdinalIgnoreCase)) + { + this.AddIfNotEmpty(currentLiteralText.ToString(), container.Peek()); + currentLiteralText.Clear(); + var head = new HtmlHead(); + container.Peek().Controls.Add(head); + container.Push(head); + isCurrentlyInHeadTag = true; + } + else if (chunk.TagName.Equals("asp:ContentPlaceHolder", StringComparison.OrdinalIgnoreCase)) + { + this.AddIfNotEmpty(currentLiteralText.ToString(), container.Peek()); + currentLiteralText.Clear(); + + if (chunk.HasAttribute("ID")) + { + var id = chunk.AttributesMap["ID"] as string; + var placeHolder = new ContentPlaceHolder() { ID = id }; + container.Peek().Controls.Add(placeHolder); + this.AddContentPlaceHolder(id); + this.InstantiateControls(placeHolder); + } + } + else if (chunk.TagName.Equals("form", StringComparison.OrdinalIgnoreCase) && chunk.HasAttribute("runat")) + { + this.AddIfNotEmpty(currentLiteralText.ToString(), container.Peek()); + currentLiteralText.Clear(); + + var form = new HtmlForm(); + if (chunk.HasAttribute("id")) + form.ID = chunk.AttributesMap["id"] as string; + else + form.ID = "aspnetForm"; + + container.Peek().Controls.Add(form); + container.Push(form); + } + else if (chunk.TagName.Equals(LayoutsHelpers.SectionTag, StringComparison.OrdinalIgnoreCase)) + { + this.AddIfNotEmpty(currentLiteralText.ToString(), container.Peek()); + currentLiteralText.Clear(); + + var sectionRenderer = new SectionRenderer(); + if (chunk.HasAttribute("name")) + { + sectionRenderer.Name = chunk.AttributesMap["name"].ToString(); + } + + container.Peek().Controls.Add(sectionRenderer); + } + else if (chunk.TagName.Equals("meta", StringComparison.OrdinalIgnoreCase)) + { + this.AddIfNotEmpty(currentLiteralText.ToString(), container.Peek()); + currentLiteralText.Clear(); + + this.AddIfNotEmpty(chunk.Html, container.Peek()); + } + else if (chunk.TagName == "%@") + { + //// Ignore + } + else + { + currentLiteralText.Append(chunk.Html); + } + } + + private void HandleCloseTag(Stack container, HtmlChunk chunk, StringBuilder currentLiteralText) + { + if (chunk.TagName.Equals("title", StringComparison.OrdinalIgnoreCase) && isCurrentlyInHeadTag) + { + // if we are not currently parsing the tag, then this title must be in the body and we should skip it + if (container.Peek() is HtmlTitle) + { + ((HtmlTitle)container.Pop()).Text = currentLiteralText.ToString(); + } + else + { + this.AddIfNotEmpty(currentLiteralText.ToString(), container.Pop()); + } + + currentLiteralText.Clear(); + } + else if (chunk.TagName.Equals("head", StringComparison.OrdinalIgnoreCase)) + { + this.AddIfNotEmpty(currentLiteralText.ToString(), container.Pop()); + currentLiteralText.Clear(); + isCurrentlyInHeadTag = false; + } + else if (chunk.TagName.Equals("form", StringComparison.OrdinalIgnoreCase)) + { + if (container.Peek() is HtmlForm) + { + this.AddIfNotEmpty(currentLiteralText.ToString(), container.Pop()); + currentLiteralText.Clear(); + } + else + { + currentLiteralText.Append(chunk.Html); + } + } + else if (chunk.TagName.Equals("asp:ContentPlaceHolder", StringComparison.OrdinalIgnoreCase)) + { + //// Ignore + } + else if (chunk.TagName.Equals(LayoutsHelpers.SectionTag, StringComparison.OrdinalIgnoreCase)) + { + //// Ignore + } + else if (chunk.TagName.Equals("meta", StringComparison.OrdinalIgnoreCase)) + { + //// Ignore + } + else + { + currentLiteralText.Append(chunk.Html); + } + } + + private void AddIfNotEmpty(string literal, Control container) + { + if (!literal.IsNullOrEmpty()) + { + var control = new LiteralControl(); + control.Text = literal; + container.Controls.Add(control); + } + } + + private void AddContentPlaceHolder(string control) + { + this.ContentPlaceHolders.Add(control); + } + + private void InstantiateControls(Control placeHolder) + { + if (placeHolder == null) + throw new ArgumentNullException("placeHolder"); + + if (this.ContentTemplates != null && this.ContentTemplates.Contains(placeHolder.ID)) + { + this.InstantiateInContentPlaceHolder(placeHolder, (ITemplate)this.ContentTemplates[placeHolder.ID]); + } + } + + private bool isCurrentlyInHeadTag = false; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/PageTemplateExtensions.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/PageTemplateExtensions.cs index add1abf62..d3f549e44 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/PageTemplateExtensions.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/PageTemplateExtensions.cs @@ -9,7 +9,7 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts /// /// This class contains extension methods for the IPageTemplate. /// - public static class PageTemplateExtensions + internal static class PageTemplateExtensions { /// /// Gets the template framework. diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/SectionRenderer.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/SectionRenderer.cs new file mode 100644 index 000000000..d04a71b0b --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/SectionRenderer.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Web.UI; +using Telerik.Sitefinity.Frontend.Mvc.Helpers; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts +{ + /// + /// This control is responsible for rendering the section content. + /// + public class SectionRenderer : Control + { + /// + /// Gets or sets the name of the section. + /// + /// + /// The name. + /// + public string Name { get; set; } + + /// + /// Determines whether the specified section is available on the page. + /// + /// The page. + /// Name of the section. + /// True if the section is available on the page and false otherwise. + internal static bool IsAvailable(Page page, string sectionName) + { + if (ResourceHelper.RenderScriptSection) + return true; + + if (sectionName == null) + throw new ArgumentNullException("sectionName"); + + if (page == null) + return false; + + return page.Items.Contains(SectionRenderer.AvailableSectionsKey) && ((ISet)page.Items[SectionRenderer.AvailableSectionsKey]).Contains(sectionName); + } + + /// + /// Marks the specified section as availabile. + /// + /// The page. + /// Name of the section. + /// + internal static void MarkAvailability(Page page, string sectionName) + { + if (page != null && !sectionName.IsNullOrEmpty()) + { + ISet availableSections; + if (page.Items.Contains(SectionRenderer.AvailableSectionsKey)) + { + availableSections = (ISet)page.Items[SectionRenderer.AvailableSectionsKey]; + } + else + { + availableSections = new HashSet(); + page.Items.Add(SectionRenderer.AvailableSectionsKey, availableSections); + } + + if (!availableSections.Contains(sectionName)) + { + availableSections.Add(sectionName); + } + else + { + throw new DuplicateSectionException(sectionName); + } + } + } + + /// + /// Sends server control content to a provided object, which writes the content to be rendered on the client. + /// + /// The object that receives the server control content. + protected override void Render(HtmlTextWriter writer) + { + var context = new HttpContextWrapper(this.Context); + writer.Write(ResourceHelper.RenderAllScripts(context, this.Name)); + writer.Write(ResourceHelper.RenderAllStylesheets(context, this.Name)); + } + + private const string AvailableSectionsKey = "available-sections"; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/TemplateTitleParser.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/TemplateTitleParser.cs index 9d8290213..b546eecec 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/TemplateTitleParser.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/TemplateTitleParser.cs @@ -11,7 +11,7 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts /// /// This class is responsible for resolving the actual file name of the layout used for template based on convention. /// - public class TemplateTitleParser + internal class TemplateTitleParser { #region Public methods diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/MvcConstants.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/MvcConstants.cs new file mode 100644 index 000000000..5aa1f67f3 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/MvcConstants.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure +{ + /// + /// This class contains commonly used MVC words, phrases and extensions. + /// + public static class MvcConstants + { + /// + /// Initialize dependant static variables. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] + static MvcConstants() + { + MvcConstants.MvcFieldControlNameTemplate = string.Concat("{0} ", MvcConstants.MvcSuffix); + } + + /// Template for 's fields. Used by MVC widgets. + public static readonly string MvcFieldControlNameTemplate; + + /// Suffix for MVC widgets friendly control name + public static readonly string MvcSuffix = "(MVC)"; + + /// Filename extension used by Razor views + public static readonly string RazorFileNameExtension = ".cshtml"; + + /// + /// The MVC template condition + /// + /// + /// {Module type full name} AND MVC; + /// + public static readonly string MvcTemplateCondition = "{0} AND MVC"; + + /// + /// The friendly control name template for list. + /// + /// + /// {Module title} - {ModuleType plural name} - list (MVC); + /// + public static readonly string FriendlyControlDynamicListTemplate = "{0} - {1} - list (MVC)"; + + /// + /// The friendly control name template for detail. + /// + /// + /// {Module title} - {ModuleType plural name} - single (MVC); + /// + public static readonly string FriendlyControlDynamicDetailTemplate = "{0} - {1} - single (MVC)"; + + /// + /// The detail template name + /// + public static readonly string DetailTemplateName = "Detail.{0}"; + + /// + /// The list template name + /// + public static readonly string ListTemplateName = "List.{0}"; + + /// + /// The area format. + /// + /// + /// {Module title} - {ModuleType display name}; + /// + public static readonly string DynamicAreaFormat = "{0} - {1}"; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/PageInitializer.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/PageInitializer.cs new file mode 100644 index 000000000..432e7bbba --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/PageInitializer.cs @@ -0,0 +1,71 @@ +using System; +using System.Linq; +using System.Reflection; +using System.Web; +using System.Web.UI; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure +{ + /// + /// Instances of this are used to manipulated a page right after it is created. + /// + internal class PageInitializer + { + /// + /// Initializes the specified handler as a page. This method is called right after the handler is created and can be used to add controls to the Page. + /// + /// The handler. + /// handler + public void Initialize(IHttpHandler handler) + { + if (handler == null) + throw new ArgumentNullException("handler"); + + Page page = handler.GetPageHandler(); + + if (page != null) + { + this.Initialize(page); + } + } + + /// + /// Gets the inline style. + /// + /// + public string GetInlineStyle() + { + var loadingUrl = "assets/dist/css/loading.min.css"; + + var fullLoadingUrl = RouteHelper.ResolveUrl(string.Format("~/{0}{1}", FrontendManager.VirtualPathBuilder.GetVirtualPath(this.GetType().Assembly), loadingUrl), UrlResolveOptions.Rooted); + var cssValue = @".sfMvcIcn { position: relative; } .sfMvcIcn:after { content: ""MVC""; display: block; position: absolute; padding: 2px 3px; left: 26px; bottom: 4px; background: #105CB6; color: #fff; font-size: 8px;} a.sfAddContentLnk.sfMvcIcn:after{ bottom: 24px; left: calc(50% - 2px); }"; + var inlineCss = string.Format(@"", cssValue, fullLoadingUrl); + + return inlineCss; + } + + private void Initialize(Page page) + { + if (page == null) + throw new ArgumentNullException("page"); + + if (page != null) + { + page.PreInit += this.PreInitHandler; + } + } + + private void PreInitHandler(object sender, EventArgs e) + { + var page = ((IHttpHandler)sender).GetPageHandler(); + + if (LayoutMvcPageResolver.IsLayoutPath(page.MasterPageFile)) + { + page.Request.RequestContext.HttpContext.Items.Remove("JsRegister"); + new MvcMasterPage().ApplyToPage(page); + } + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Personalization/PersonalizationInitializer.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Personalization/PersonalizationInitializer.cs new file mode 100644 index 000000000..09f96d350 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Personalization/PersonalizationInitializer.cs @@ -0,0 +1,20 @@ +using Telerik.Microsoft.Practices.Unity; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Personalization; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Personalization +{ + internal class PersonalizationInitializer : IInitializer + { + /// + public void Initialize() + { + ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); + } + + /// + public void Uninitialize() + { + } + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Personalization/PersonalizedMvcWidgetResolver.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Personalization/PersonalizedMvcWidgetResolver.cs new file mode 100644 index 000000000..628b74fb4 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Personalization/PersonalizedMvcWidgetResolver.cs @@ -0,0 +1,53 @@ +using System; +using System.Linq; +using System.Text; +using Telerik.Sitefinity.Mvc.Proxy; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Personalization.Impl.Web; +using Telerik.Sitefinity.Utilities.TypeConverters; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Personalization +{ + /// + /// Defines the common methods for building pages with personalized MVC widgets. + /// + /// + public class PersonalizedMvcWidgetResolver : PersonalizedWidgetResolver + { + /// + public override Type ResolveWrapperType(Type widgetType) + { + if (typeof(MvcProxyBase).IsAssignableFrom(widgetType)) + { + return typeof(PersonalizedWidgetProxy); + } + else + { + return base.ResolveWrapperType(widgetType); + } + } + + /// + public override void AppendPersonalizationProperties(StringBuilder output, ControlData controlData, Type controlType, Guid pageDataId, out bool appendAllProperties) + { + if (typeof(MvcProxyBase).IsAssignableFrom(controlType)) + { + appendAllProperties = true; + + var controllerName = controlData.Properties.Where(p => p.Name == "ControllerName" && p.Value != null) + .Select(p => p.Value).FirstOrDefault(); + + if (!controllerName.IsNullOrEmpty()) + { + controlType = TypeResolutionService.ResolveType(controllerName, throwOnError: false); + } + + output.Append(string.Format(" ControlDataId=\"{0}\" ControlTypeName=\"{1}\" PageDataId=\"{2}\"", controlData.Id, controlType.FullName, pageDataId)); + } + else + { + base.AppendPersonalizationProperties(output, controlData, controlType, pageDataId, out appendAllProperties); + } + } + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Personalization/PersonalizedWidgetProxy.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Personalization/PersonalizedWidgetProxy.cs new file mode 100644 index 000000000..64d326779 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Personalization/PersonalizedWidgetProxy.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web.UI; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.Frontend.Mvc.Helpers; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; +using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Personalization.Impl.Configuration; +using Telerik.Sitefinity.Personalization.Impl.Web.UI; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Personalization +{ + /// + /// Web forms control that is used as a proxy for personalized MVC controllers and has information about the specific widget it is used for. + /// + public class PersonalizedWidgetProxy : MvcWidgetProxy + { + #region Construction + + /// + /// Initializes a new instance of the class. + /// + public PersonalizedWidgetProxy() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The control data ID. + /// The page data ID. + /// Full name of the control type. + public PersonalizedWidgetProxy(Guid controlDataId, Guid pageDataId, string controlTypeName) + { + this.ControlDataId = controlDataId; + this.PageDataId = pageDataId; + this.ControlTypeName = controlTypeName; + } + + #endregion + + #region Properties + + /// + /// Gets or sets the control data ID. + /// + /// + /// The control data ID. + /// + public Guid ControlDataId { get; set; } + + /// + /// Gets or sets the page data ID. + /// + /// + /// The page data ID. + /// + public Guid PageDataId { get; set; } + + /// + /// Gets or sets the name of the control type. + /// + /// + /// The name of the control type. + /// + public string ControlTypeName { get; set; } + + #endregion + + #region Public Methods + + /// + protected override void CreateChildControls() + { + base.CreateChildControls(); + + this.personalizedViewWrapper = new PersonalizedViewWrapper(this.ControlDataId, this.PageDataId, this.ControlTypeName); + this.Controls.Add(this.personalizedViewWrapper); + } + + /// + protected override void Render(HtmlTextWriter writer) + { + var isMvcDetailsView = (string)(this.Controller.RouteData.Values["action"]) == "Details"; + this.personalizedViewWrapper.RaiseEvents = !isMvcDetailsView; + + if (this.Page.Items["ScriptSourcesLoaded"] == null) + { + var currentNode = SiteMapBase.GetActualCurrentNode(); + if (currentNode != null && currentNode.Framework == PageTemplateFramework.Mvc) + { + var registeredScripts = SystemManager.CurrentHttpContext.Items[ResourceHelper.JsRegisterName] as Dictionary>; + if (registeredScripts != null) + { + this.personalizedViewWrapper.LoadedScripts = registeredScripts.SelectMany(p => p.Value.Select(x => x.ResourceKey)); + } + } + else + { + var scriptManager = ScriptManager.GetCurrent(this.Page); + if (scriptManager != null && scriptManager.Scripts != null && scriptManager.Scripts.Count > 0) + { + var scriptRef = scriptManager.Scripts.Select(r => new ResourceHelper.MvcScriptReference(r)); + this.personalizedViewWrapper.LoadedScripts = scriptRef.Select(r => r.GetResourceUrl()); + } + } + + this.Page.Items["ScriptSourcesLoaded"] = true; + } + + this.personalizedViewWrapper.RenderControl(writer); + } + + #endregion + + #region Private fields + + private PersonalizedViewWrapper personalizedViewWrapper; + + #endregion + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/AttributeRoutingManager.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/AttributeRoutingManager.cs new file mode 100644 index 000000000..cb982f427 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/AttributeRoutingManager.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Web.Mvc; +using System.Web.Routing; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + /// + /// Instances of this class manage attribute routing for controllers. + /// + internal sealed class AttributeRoutingManager + { + /// + /// Initializes a new instance of the class. + /// + public AttributeRoutingManager() + { + this.routesPerController = new Dictionary(); + } + + /// + /// Maps the attribute-defined routes for the application. + /// + public void MapMvcAttributeRoutes() + { + //// Map direct routes in the global route table. + RouteTable.Routes.MapMvcAttributeRoutes(); + + var routeCollection = new RouteCollection(); + routeCollection.MapMvcAttributeRoutes(new RelativeDirectRouteProvider()); + + this.OrganizeRoutes(routeCollection); + } + + /// + /// Determines whether the controller in the specified route data has attribute routing. + /// + /// The route data. + /// routeData + public bool HasAttributeRouting(RouteData routeData) + { + if (routeData == null) + throw new ArgumentNullException("routeData"); + + var controllerName = routeData.Values[FeatherActionInvoker.ControllerNameKey] as string; + return this.routesPerController.ContainsKey(controllerName); + } + + /// + /// Updates the route data using the applicable routes for the given context. Returns false if there are no applicable routes. Infers controller name from the given route data. + /// + /// The context. + /// The route data. + /// True if any attribute route matches the request of the given context. + /// + /// context + /// or + /// routeData + /// + public bool UpdateRouteData(HttpContextBase context, RouteData routeData) + { + if (context == null) + throw new ArgumentNullException("context"); + + if (routeData == null) + throw new ArgumentNullException("routeData"); + + if (context.Request == null || context.Request.RequestContext == null || !routeData.Values.ContainsKey(FeatherActionInvoker.ControllerNameKey)) + return false; + + var controllerName = routeData.Values[FeatherActionInvoker.ControllerNameKey] as string; + if (this.routesPerController.ContainsKey(controllerName)) + { + RouteData newRouteData; + using (new PageRelativePathContextRegion(context)) + { + newRouteData = this.routesPerController[controllerName].GetRouteData(context); + } + + if (newRouteData != null) + { + foreach (KeyValuePair value in newRouteData.Values) + { + if (value.Key != FeatherActionInvoker.ControllerNameKey) + routeData.Values[value.Key] = value.Value; + } + + return true; + } + } + + return false; + } + + private void OrganizeRoutes(RouteCollection routeCollection) + { + if (routeCollection.Count == 0) + return; + + var compoundRoute = routeCollection[0] as IEnumerable; + if (compoundRoute == null) + return; + + var controllerRoutes = new Dictionary>(); + foreach (var route in compoundRoute) + { + var directRoute = route as Route; + if (directRoute != null) + { + var controllerName = directRoute.Defaults[FeatherActionInvoker.ControllerNameKey] as string; + + if (directRoute.Defaults.ContainsKey(FeatherActionInvoker.ControllerNameKey)) + { + if (!controllerRoutes.ContainsKey(controllerName)) + controllerRoutes.Add(controllerName, new List()); + + controllerRoutes[controllerName].Add(directRoute); + } + } + } + + foreach (var controllerRoutesList in controllerRoutes) + { + if (controllerRoutesList.Value.Count > 0) + { + var collectionRoute = (RouteBase)Activator.CreateInstance(compoundRoute.GetType(), controllerRoutesList.Value); + this.routesPerController[controllerRoutesList.Key] = collectionRoute; + } + } + } + + private readonly Dictionary routesPerController; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/CustomActionParamsMapper.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/CustomActionParamsMapper.cs index 0b94b61ad..51cab61ed 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/CustomActionParamsMapper.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/CustomActionParamsMapper.cs @@ -3,6 +3,7 @@ using System.Reflection; using System.Web.Mvc; using System.Web.Routing; +using Telerik.Sitefinity.Frontend.Mvc.Models; using Telerik.Sitefinity.Web; namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing @@ -30,18 +31,31 @@ public CustomActionParamsMapper(ControllerBase controller, Func routeTem this.routeTemplateResolver = routeTemplateResolver; } + /// + /// Initializes a new instance of the class. + /// + /// The controller. + /// This function should return the route template that the mapper will use. + /// Name of the action. + /// routeTemplateResolver + public CustomActionParamsMapper(ControllerBase controller, Func routeTemplateResolver, string actionName, string[] urlParamNames) + : this(controller, routeTemplateResolver, actionName) + { + this.urlParamNames = urlParamNames; + } + /// - protected override bool TryMatchUrl(string[] urlParams, RequestContext requestContext) + protected override bool TryMatchUrl(string[] urlParams, RequestContext requestContext, string urlKeyPrefix) { - if (urlParams == null) + if (urlParams == null || !this.IsPaginationAllowed()) return false; var routeTemplate = this.routeTemplateResolver(); var metaParams = routeTemplate - .Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries); + .Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); - var parameterMap = this.MapParams(this.actionMethod, metaParams, urlParams); + var parameterMap = this.MapParams(this.actionMethod, metaParams, urlParams, this.urlParamNames); if (parameterMap == null) return false; @@ -53,6 +67,32 @@ protected override bool TryMatchUrl(string[] urlParams, RequestContext requestCo return true; } + private bool IsPaginationAllowed() + { + if (this.actionName == "Index") + { + var modelProperty = this.Controller.GetType().GetProperty("Model"); + if (modelProperty != null) + { + var model = modelProperty.GetValue(this.Controller, null); + if (model != null) + { + var displayModeProp = model.GetType().GetProperty("DisplayMode"); + if (displayModeProp != null) + { + var displayModeValue = displayModeProp.GetValue(model, null); + if (displayModeValue != null && displayModeValue.ToString() != ListDisplayMode.Paging.ToString()) + { + return false; + } + } + } + } + } + + return true; + } + private void PopulateRouteData(RouteValueDictionary routeDataValues, IList parameters) { foreach (var parameter in parameters) @@ -64,6 +104,7 @@ private void PopulateRouteData(RouteValueDictionary routeDataValues, IList routeTemplateResolver; + private string[] urlParamNames; private const string DefaultActionName = "Index"; } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Date/DateUrlEvaluatorAdapter.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Date/DateUrlEvaluatorAdapter.cs new file mode 100644 index 000000000..6808e0899 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Date/DateUrlEvaluatorAdapter.cs @@ -0,0 +1,61 @@ +using System; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Web.UrlEvaluation; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing.Date +{ + /// + internal class DateUrlEvaluatorAdapter : IDateUrlEvaluatorAdapter + { + /// + /// Initializes a new instance for . + /// + public DateUrlEvaluatorAdapter() + { + this.dateEvaluator = this.GetDefaultEvaluator(); + } + + /// + public bool TryGetDateFromUrl(string url, string urlKeyPrefix, out DateTime from, out DateTime to) + { + from = default(DateTime); + to = default(DateTime); + + int datePrefixIndex = url.IndexOf(DatePrefix, StringComparison.InvariantCultureIgnoreCase); + if (datePrefixIndex == -1) + { + return false; + } + + url = url.Substring(datePrefixIndex + DatePrefix.Length); + object[] values; + + string dateExpression = this.dateEvaluator.Evaluate(url, "PublicationDate", null, UrlEvaluationMode.UrlPath, null, out values); + if (string.IsNullOrWhiteSpace(dateExpression)) + { + return false; + } + + from = (DateTime)values[0]; + to = (DateTime)values[1]; + + return true; + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + private DateEvaluator GetDefaultEvaluator() + { + try + { + return UrlEvaluator.GetEvaluator("Date") as DateEvaluator; + } + catch + { + return null; + } + } + + private const string DatePrefix = "archive"; + private readonly DateEvaluator dateEvaluator; + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Date/DateUrlParamsMapper.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Date/DateUrlParamsMapper.cs new file mode 100644 index 000000000..33dbbf82a --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Date/DateUrlParamsMapper.cs @@ -0,0 +1,77 @@ +using System; +using System.Reflection; +using System.Web.Mvc; +using System.Web.Routing; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing.Date +{ + /// + /// Instances of this class map URL parameters to Route Data following a provided route template and action name. + /// + internal class DateUrlParamsMapper : UrlParamsMapperBase + { + /// + /// Initializes a new instance of the class. + /// + /// The controller. + /// The adapter for date URL evaluator. + /// Name of the action. + public DateUrlParamsMapper(ControllerBase controller, IDateUrlEvaluatorAdapter dateUrlEvaluatorAdapter, string actionName = DateUrlParamsMapper.DefaultActionName) : base(controller) + { + this.actionName = actionName; + this.actionMethod = controller.GetType().GetMethod(this.actionName, BindingFlags.Instance | BindingFlags.Public); + this.dateUrlEvaluatorAdapter = dateUrlEvaluatorAdapter; + } + + /// + protected override bool TryMatchUrl(string[] urlParams, RequestContext requestContext, string urlKeyPrefix) + { + if (urlParams == null || urlParams.Length == 0) + { + return false; + } + + string url = string.Join(@"/", urlParams); + DateTime from = default(DateTime); + DateTime to = default(DateTime); + + if (!this.dateUrlEvaluatorAdapter.TryGetDateFromUrl(url, urlKeyPrefix, out from, out to)) + { + return false; + } + + this.SetControllerActionParams(requestContext, from, to); + + RouteHelper.SetUrlParametersResolved(); + + return true; + } + + private void SetControllerActionParams(RequestContext requestContext, DateTime from, DateTime to) + { + requestContext.RouteData.Values[UrlParamsMapperBase.ActionNameKey] = this.actionName; + ParameterInfo[] parameters = this.actionMethod.GetParameters(); + + foreach (ParameterInfo paramInfo in this.actionMethod.GetParameters()) + { + if (paramInfo.ParameterType == typeof(DateTime)) + { + if (string.Equals(paramInfo.Name, "from", StringComparison.InvariantCultureIgnoreCase)) + { + requestContext.RouteData.Values[paramInfo.Name] = from; + } + else if (string.Equals(paramInfo.Name, "to", StringComparison.InvariantCultureIgnoreCase)) + { + requestContext.RouteData.Values[paramInfo.Name] = to; + } + } + } + } + + private readonly string actionName; + private readonly MethodInfo actionMethod; + private const string DefaultActionName = "ListByDate"; + private readonly IDateUrlEvaluatorAdapter dateUrlEvaluatorAdapter; + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Date/IDateUrlEvaluatorAdapter.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Date/IDateUrlEvaluatorAdapter.cs new file mode 100644 index 000000000..29b612294 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Date/IDateUrlEvaluatorAdapter.cs @@ -0,0 +1,20 @@ +using System; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing.Date +{ + /// + /// Adapter for + /// + internal interface IDateUrlEvaluatorAdapter + { + /// + /// Will try to get date filter from URL and save result in 'from' date and 'to' date parameters. + /// + /// The url path that contains the date filter. + /// The url prefix that might be configured for the URL path expression. + /// The 'from' date in the filter. + /// The 'to' date in the filter. + /// True if date filter was successfully parsed, otherwise false. + bool TryGetDateFromUrl(string url, string urlKeyPrefix, out DateTime from, out DateTime to); + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DefaultUrlParamsMapper.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DefaultUrlParamsMapper.cs index d4db7d515..3ed602e18 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DefaultUrlParamsMapper.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DefaultUrlParamsMapper.cs @@ -1,7 +1,8 @@ using System.Web.Mvc; using System.Web.Routing; -using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; using Telerik.Sitefinity.Mvc; +using Telerik.Sitefinity.Web; namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing { @@ -20,11 +21,35 @@ public DefaultUrlParamsMapper(ControllerBase controller) } /// - protected override bool TryMatchUrl(string[] urlParams, RequestContext requestContext) - { - var controllerName = requestContext.RouteData.Values[DynamicUrlParamActionInvoker.ControllerNameKey] as string; - requestContext.RouteData.Values.Remove(DynamicUrlParamActionInvoker.ControllerNameKey); - MvcRequestContextBuilder.SetRouteParameters(urlParams, requestContext, this.Controller as Controller, controllerName); + protected override bool TryMatchUrl(string[] urlParams, RequestContext requestContext, string urlKeyPrefix) + { + var selfRouting = this.Controller as IRouteMapper; + if (urlParams != null && selfRouting != null && selfRouting.TryMapRouteParameters(urlParams, requestContext)) + { + RouteHelper.SetUrlParametersResolved(); + return true; + } + + var controllerName = requestContext.RouteData.Values[FeatherActionInvoker.ControllerNameKey] as string; + string actionName = null; + if (requestContext.RouteData.Values.ContainsKey("action")) + { + actionName = requestContext.RouteData.Values["action"] as string; + requestContext.RouteData.Values.Remove("action"); + } + + try + { + requestContext.RouteData.Values.Remove(FeatherActionInvoker.ControllerNameKey); + MvcRequestContextBuilder.SetRouteParameters(urlParams, requestContext, this.Controller as Controller, controllerName); + } + finally + { + if (actionName != null) + { + requestContext.RouteData.Values["action"] = actionName; + } + } return true; } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DetailActionParamsMapper.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DetailActionParamsMapper.cs index 25aceda3e..9679afd48 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DetailActionParamsMapper.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DetailActionParamsMapper.cs @@ -1,14 +1,23 @@ using System; +using System.Linq; using System.Web.Mvc; using System.Web.Routing; +using Telerik.Sitefinity.Abstractions; using Telerik.Sitefinity.ContentLocations; using Telerik.Sitefinity.Data; +using Telerik.Sitefinity.DynamicModules.Model; +using Telerik.Sitefinity.Frontend.Mvc.Helpers; +using Telerik.Sitefinity.Frontend.Mvc.Models; using Telerik.Sitefinity.GenericContent.Model; using Telerik.Sitefinity.Lifecycle; using Telerik.Sitefinity.Model; using Telerik.Sitefinity.Modules.GenericContent; +using Telerik.Sitefinity.Publishing; +using Telerik.Sitefinity.Security.Model; using Telerik.Sitefinity.Services; using Telerik.Sitefinity.Web; +using Telerik.Sitefinity.Web.DataResolving; +using Telerik.Sitefinity.Web.UI.ContentUI.Enums; namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing { @@ -17,6 +26,8 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing /// internal class DetailActionParamsMapper : UrlParamsMapperBase { + private bool showDetailsViewOnChildDetailsView; + /// /// Initializes a new instance of the class. /// @@ -60,151 +71,337 @@ public DetailActionParamsMapper(ControllerBase controller, Type itemType, Func - protected override bool TryMatchUrl(string[] urlParams, RequestContext requestContext) + private bool TryMatchUrl(string[] urlParams, RequestContext requestContext, bool setUrlParametersResolved, bool setToContext = true) { - if (urlParams == null) + if (urlParams == null || urlParams.Length == 0 || !this.IsDetailsModeSupported()) return false; var url = RouteHelper.GetUrlParameterString(urlParams); string redirectUrl; - var item = this.GetItemByUrl(url, out redirectUrl); + var providerName = this.providerNameResolver != null ? this.providerNameResolver() : null; + var contentItemResolver = new ContentDataItemResolver(); + var item = contentItemResolver.GetItemByUrl(url, this.ItemType, providerName, out redirectUrl); - if (item != null) + if (item != null && this.CanDisplayItem(item)) { - this.AddContentItemToRouteData(requestContext, redirectUrl, item); + if(setToContext) + SystemManager.CurrentHttpContext.Items["detailItem"] = item; + + this.AddContentItemToRouteData(requestContext, redirectUrl, item, setUrlParametersResolved); return true; } + else if (this.showDetailsViewOnChildDetailsView) + { + return this.TryMatchUrl(urlParams.Take(urlParams.Length - 1).ToArray(), requestContext, setUrlParametersResolved, false); + } return false; } /// - /// Adds the content item to route data. + /// Determines whether an item should be displayed depending if the item or it`s parent is selected or the the item does not have any filtration /// - /// The request context. - /// The redirect URL. - /// The item. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#")] - protected virtual void AddContentItemToRouteData(RequestContext requestContext, string redirectUrl, IDataItem item) + /// Data item + /// Return true if the item is selected, has a selected parent or does not have any filtration, else return false + private bool CanDisplayItem(IDataItem item) { - requestContext.RouteData.Values[UrlParamsMapperBase.ActionNameKey] = this.actionName; + bool canDispay = true; - var parameters = this.ActionMethod.GetParameters(); - if (parameters.Length > 0 && parameters[0].ParameterType.IsAssignableFrom(this.ItemType)) + var modelProperty = this.Controller.GetType().GetProperty("Model"); + if (modelProperty != null) { - requestContext.RouteData.Values[parameters[0].ParameterName] = item; + var model = modelProperty.GetValue(this.Controller); + if (model != null) + { + if (this.IsPreviewRequested()) + item = this.TryGetLiveItem(item); + + string serializedSelectedItemsIds = this.GetSelectedItemsIds(model); + if (serializedSelectedItemsIds != null) + { + canDispay = this.IsSelectedItem(item, model, serializedSelectedItemsIds); + } + else + { + if (this.IsParentFilterModeSelected(model)) + { + string serializedSelectedParentsItemsIds = this.GetSelectedParentsIds(model); + if (serializedSelectedParentsItemsIds != null) + { + canDispay = this.HasSelectedParentItem(item, model, serializedSelectedParentsItemsIds); + } + } + } + } } - if (redirectUrl.IsNullOrEmpty() == false && parameters.Length > 1 && parameters[1].ParameterType == typeof(string)) + return canDispay; + } + + /// + /// Checks to see if the item given is the master one. If true returns the live item. + /// + /// Data item + /// + private IDataItem TryGetLiveItem(IDataItem item) + { + if (item is ILifecycleDataItem itemAsLifecycle) { - requestContext.RouteData.Values[parameters[1].ParameterName] = redirectUrl; + if (itemAsLifecycle.Status == ContentLifecycleStatus.Master) + { + var manager = ManagerBase.GetMappedManager(item.GetType(), item.Provider.ToString()); + var lifecycleManager = manager as ILifecycleManager; + + var liveItem = lifecycleManager.Lifecycle.GetLive(itemAsLifecycle); + if (liveItem != null) + { + return liveItem; + } + } } - RouteHelper.SetUrlParametersResolved(); + return item; + } + + private bool IsPreviewRequested() + { + var actionParam = SystemManager.CurrentHttpContext.Request.ParamsGet("sf-content-action"); + bool isPreview = actionParam != null && actionParam == "preview"; + + return isPreview; } /// - /// Gets content item by URL. + /// Determines whether the item is selected /// - /// The URL. - /// The redirect URL. - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#")] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")] - protected virtual IDataItem GetItemByUrl(string url, out string redirectUrl) + /// Data item + /// The widget model + /// Return false if item is not in the selected items, else return true + private bool IsSelectedItem(IDataItem item, object model, string serializedSelectedItemsIds) { - var manager = this.ResolveManager(); - if (manager == null) - { - redirectUrl = null; - return null; - } + bool isSelectedItem = true; - var itemIdFromQueryParam = (SystemManager.CurrentHttpContext.Request.Params["sf-itemId"] ?? SystemManager.CurrentHttpContext.Items["sf-itemId"]) as string; - if (!itemIdFromQueryParam.IsNullOrEmpty()) + var selectionModeProperty = model.GetType().GetProperty("SelectionMode"); + if (selectionModeProperty != null) { - Guid itemIdGuid; - if (Guid.TryParse(itemIdFromQueryParam, out itemIdGuid)) + var selectionMode = selectionModeProperty.GetValue(model); + if (selectionMode != null) { - redirectUrl = null; - return manager.GetItem(this.ItemType, itemIdGuid) as IDataItem; + if (selectionMode.ToString() == SelectionMode.SelectedItems.ToString()) + { + isSelectedItem = serializedSelectedItemsIds.Contains(item.Id.ToString()); + if (!isSelectedItem) + { + if (item is ILifecycleDataItemGeneric itemAsLifecycleGeneric) + { + isSelectedItem = serializedSelectedItemsIds.Contains(itemAsLifecycleGeneric.OriginalContentId.ToString()); + } + else if (item is SitefinityProfile profile) + { + isSelectedItem = serializedSelectedItemsIds.Contains(profile.User.Id.ToString()); + } + } + } + // This is a special case for the list item as it`s parent id is stored in the selected items property + else if (item is IHasParent) + { + isSelectedItem = serializedSelectedItemsIds.Contains((item as IHasParent).Parent.Id.ToString()); + } } } - IDataItem item; - var contentManager = manager as IContentManager; - if (contentManager != null) + return isSelectedItem; + } + + /// + /// Determines whether ParentFilterMode property is set to Selected + /// + /// The widget model + /// Return true if the ParentFilterMode is set to Selected, else return false + private bool IsParentFilterModeSelected(object model) + { + var parentFilterModeProperty = model.GetType().GetProperty("ParentFilterMode"); + if (parentFilterModeProperty != null) { - var isPublished = !this.IsPreviewRequested() || - this.ResolveRequestedItemStatus() == ContentLifecycleStatus.Live; - item = contentManager.GetItemFromUrl(this.ItemType, url, isPublished, out redirectUrl); + var parentFilterMode = parentFilterModeProperty.GetValue(model); + if (parentFilterMode != null && parentFilterMode.ToString() == "Selected") + { + return true; + } } - else + return false; + } + + /// + /// Gets the selected items ids + /// + /// The widget model + /// The selected items ids as a string + private string GetSelectedItemsIds(object model) + { + var serializedSelectedItemsIdsProperty = model.GetType().GetProperty("SerializedSelectedItemsIds"); + + if (serializedSelectedItemsIdsProperty != null) { - item = ((IUrlProvider)manager.Provider).GetItemFromUrl(this.ItemType, url, out redirectUrl); + var serializedSelectedItemsIds = serializedSelectedItemsIdsProperty.GetValue(model); + if (serializedSelectedItemsIds != null && serializedSelectedItemsIds.ToString() != "[]") + { + return serializedSelectedItemsIds.ToString(); + } } - var lifecycleItem = item as ILifecycleDataItem; - var lifecycleManager = manager as ILifecycleManager; - if (lifecycleItem != null && lifecycleManager != null) + return null; + } + + /// + /// Determines whether the item has a selected parent + /// + /// Data item + /// The widget model + /// The selected parets ids + /// Return false if the item`s parent is not selected, else return true + private bool HasSelectedParentItem(IDataItem item, object model, string serializedSelectedParentsIds) + { + bool hasSelectedParentItem = true; + + // The parent id is retrieved differently depending if it implement IHasParent or is Dynamic content + if (item is IHasParent) { - object requestedItem; - if (ContentLocatableViewExtensions.TryGetItemWithRequestedStatus(lifecycleItem, lifecycleManager, out requestedItem)) + hasSelectedParentItem = serializedSelectedParentsIds.ToString().Contains((item as IHasParent).Parent.Id.ToString()); + if (!hasSelectedParentItem) { - item = requestedItem as IDataItem; + // If the item is saved in a folder, e.g. document, images, videos, the id of the folder corresponds with the parent id + var folderIdProperty = item.GetType().GetProperty("FolderId"); + if (folderIdProperty != null) + { + var folderId = folderIdProperty.GetValue(item); + if (folderId != null) + { + hasSelectedParentItem = serializedSelectedParentsIds.ToString().Contains(folderId.ToString()); + } + } } } + else if (item is DynamicContent) + { + hasSelectedParentItem = serializedSelectedParentsIds.ToString().Contains((item as DynamicContent).SystemParentId.ToString()); + } - return item; + return hasSelectedParentItem; } /// - /// Resolves the manager. + /// Gets the selected parents ids /// - /// - /// Items of the {0} type cannot be found by URL..Arrange(this.ItemType.FullName) - protected IManager ResolveManager() + /// The widget model + /// The selected parents ids as a string + private string GetSelectedParentsIds(object model) { - var providerName = this.providerNameResolver != null ? this.providerNameResolver() : null; - var manager = ManagerBase.GetMappedManager(this.ItemType, providerName); + var serializedSelectedParentsIdsProperty = model.GetType().GetProperty("SerializedSelectedParentsIds"); + + if (serializedSelectedParentsIdsProperty != null) + { + var serializedSelectedParentsIds = serializedSelectedParentsIdsProperty.GetValue(model); + if (serializedSelectedParentsIds != null && serializedSelectedParentsIds.ToString() != "[]") + { + return serializedSelectedParentsIds.ToString(); + } + } - if (!(manager is IContentManager) && !(manager.Provider is IUrlProvider)) - throw new InvalidOperationException("Items of the {0} type cannot be found by URL.".Arrange(this.ItemType.FullName)); + return null; + } - return manager; + /// + protected override bool TryMatchUrl(string[] urlParams, RequestContext requestContext, string urlKeyPrefix) + { + return this.TryMatchUrl(urlParams, requestContext, true); } /// - /// This method returns the requested item status based on content location url parameters. + /// Adds the content item to route data. /// - /// Copied from IContentLocatableView in Sitefinity. Should use it instead when it goes public. - /// Requested item status. - private ContentLifecycleStatus ResolveRequestedItemStatus() + /// The request context. + /// The redirect URL. + /// The item. + /// Whether to set the url parameters resolved + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#")] + protected virtual void AddContentItemToRouteData(RequestContext requestContext, string redirectUrl, IDataItem item, bool setUrlParametersResolved = true) { - var itemStatusParam = SystemManager.CurrentHttpContext.Request.Params["sf-lc-status"] ?? SystemManager.CurrentHttpContext.Items["sf-lc-status"]; - ContentLifecycleStatus status = ContentLifecycleStatus.Live; - if (itemStatusParam != null) + requestContext.RouteData.Values[UrlParamsMapperBase.ActionNameKey] = this.actionName; + + var parameters = this.ActionMethod.GetParameters(); + if (parameters.Length > 0 && parameters[0].ParameterType.IsAssignableFrom(this.ItemType)) { - if (!Enum.TryParse(itemStatusParam as string, out status)) - status = ContentLifecycleStatus.Live; + requestContext.RouteData.Values[parameters[0].ParameterName] = item; + } + + if (!redirectUrl.IsNullOrEmpty()) + { + var node = SiteMapBase.GetCurrentProvider().CurrentNode as PageSiteNode; + string urlKeyPrefix = string.Empty; + var modelProperty = this.Controller.GetType().GetProperty("Model"); + if (modelProperty != null) + { + var model = modelProperty.GetValue(this.Controller, null); + if (model != null) + { + var urlKeyPrefixProperty = model.GetType().GetProperty("UrlKeyPrefix"); + if (urlKeyPrefixProperty != null) + { + urlKeyPrefix = (string)urlKeyPrefixProperty.GetValue(model); + } + } + } + + var resolvedUrl = DataResolver.Resolve(item, "URL", urlKeyPrefix, node.Id.ToString()); + + if (requestContext.HttpContext.Request.QueryString.Count > 0) + { + resolvedUrl = $"{resolvedUrl}?{requestContext.HttpContext.Request.QueryString}"; + } + + requestContext.RouteData.Values[Telerik.Sitefinity.Mvc.ControllerActionInvoker.SfRedirectUrlKey] = resolvedUrl; } - return status; + if (redirectUrl.IsNullOrEmpty() == false && parameters.Length > 1 && parameters[1].ParameterType == typeof(string)) + { + requestContext.RouteData.Values[parameters[1].ParameterName] = redirectUrl; + } + + if (setUrlParametersResolved) + { + RouteHelper.SetUrlParametersResolved(); + } } /// - /// Determines whether preview of the item is requested. + /// Check if the widget is configured to support details mode. /// - /// Copied from IContentLocatableView in Sitefinity. Should use it instead when it goes public. - /// Whether preview is requested. - private bool IsPreviewRequested() + protected bool IsDetailsModeSupported() { - var actionParam = SystemManager.CurrentHttpContext.Request.Params["sf-content-action"]; - bool isPreview = actionParam != null && actionParam == "preview"; - return isPreview; + var modelProperty = this.Controller.GetType().GetProperty("Model"); + if (modelProperty != null) + { + var model = modelProperty.GetValue(this.Controller, null); + var contentViewDisplayModeProperty = model == null ? null : model.GetType().GetProperty("ContentViewDisplayMode"); + if (contentViewDisplayModeProperty != null) + { + var contentViewDisplayModeValue = contentViewDisplayModeProperty.GetValue(model, null); + if (contentViewDisplayModeValue != null && contentViewDisplayModeValue.ToString() == ContentViewDisplayMode.Master.ToString()) + return false; + } + } + + return true; } protected Type ItemType { get; set; } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DynamicUrlParamActionInvoker.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DynamicUrlParamActionInvoker.cs deleted file mode 100644 index ae2ee226d..000000000 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DynamicUrlParamActionInvoker.cs +++ /dev/null @@ -1,180 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Web; -using System.Web.Mvc; -using Telerik.Sitefinity.Data; -using Telerik.Sitefinity.DynamicModules.Builder; -using Telerik.Sitefinity.DynamicModules.Builder.Model; -using Telerik.Sitefinity.DynamicModules.Model; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; -using Telerik.Sitefinity.Model; -using Telerik.Sitefinity.Mvc; -using Telerik.Sitefinity.Mvc.Proxy; -using Telerik.Sitefinity.Taxonomies.Model; -using Telerik.Sitefinity.Utilities.TypeConverters; -using Telerik.Sitefinity.Web; - -namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing -{ - /// - /// Extends by providing logic for custom routing. - /// - internal class DynamicUrlParamActionInvoker : Telerik.Sitefinity.Mvc.ControllerActionInvoker - { - /// - protected override void InitializeRouteParameters(MvcProxyBase proxyControl) - { - RouteHelper.SetUrlParametersResolved(false); - - var originalContext = proxyControl.Context.Request.RequestContext ?? proxyControl.Page.GetRequestContext(); - - var paramsMapper = this.GetDefaultParamsMapper(proxyControl.Controller); - if (paramsMapper != null) - { - var requestContext = proxyControl.RequestContext; - var originalParams = MvcRequestContextBuilder.GetRouteParams(originalContext); - var controllerName = SitefinityViewEngine.GetControllerName(proxyControl.Controller); - requestContext.RouteData.Values[DynamicUrlParamActionInvoker.ControllerNameKey] = controllerName; - - paramsMapper.ResolveUrlParams(originalParams, requestContext); - proxyControl.Controller.TempData.Add("IsInPureMode", proxyControl.IsInPureMode); - - if (!proxyControl.ContentTypeName.IsNullOrEmpty()) - proxyControl.Controller.RouteData.Values.Add("contentTypeName", proxyControl.ContentTypeName); - } - else - { - base.InitializeRouteParameters(proxyControl); - } - } - - /// - /// Gets the default parameters mapper. - /// - /// The controller. - /// The default parameters mapper for the controller. - protected virtual IUrlParamsMapper GetDefaultParamsMapper(ControllerBase controller) - { - IUrlParamsMapper result = null; - result = result - .SetLast(this.GetInferredDetailActionParamsMapper(controller)) - .SetLast(this.GetInferredTaxonFilterMapper(controller, "ListByTaxon")) - .SetLast(this.GetInferredPagingMapper(controller, "Index")); - - // If no other mappers are added we skip the default one. - if (result != null) - result.SetLast(new DefaultUrlParamsMapper(controller)); - - return result; - } - - private IEnumerable GetProviderNames(ControllerBase controller, Type contentType) - { - var providerNameProperty = controller.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).FirstOrDefault(p => p.Name == "ProviderName" && p.PropertyType == typeof(string)); - - if (providerNameProperty != null) - { - return new string[1] { providerNameProperty.GetValue(controller, null) as string }; - } - else - { - var mappedManager = ManagerBase.GetMappedManager(contentType); - if (mappedManager != null) - { - return mappedManager.Providers.Select(p => p.Name); - } - else - { - return new string[0]; - } - } - } - - private IUrlParamsMapper GetInferredDetailActionParamsMapper(ControllerBase controller) - { - var controllerType = controller.GetType(); - IUrlParamsMapper result = null; - - var detailsAction = new ReflectedControllerDescriptor(controllerType).FindAction(controller.ControllerContext, DetailActionParamsMapper.DefaultActionName); - if (detailsAction != null) - { - var contentParam = detailsAction.GetParameters().FirstOrDefault(); - if (contentParam != null && contentParam.ParameterType.ImplementsInterface(typeof(IDataItem))) - { - Type contentType; - if (typeof(DynamicContent) == contentParam.ParameterType) - { - var dynamicContentType = this.GetDynamicContentType(controllerType); - contentType = dynamicContentType != null ? TypeResolutionService.ResolveType(dynamicContentType.GetFullTypeName(), throwOnError: false) : null; - } - else - { - contentType = contentParam.ParameterType; - } - - if (contentType != null) - { - var providerNames = this.GetProviderNames(controller, contentType); - foreach (var provider in providerNames) - { - var providerName = provider; - result = result.SetLast(new DetailActionParamsMapper(controller, contentType, () => providerName)); - } - } - } - } - - return result; - } - - private IUrlParamsMapper GetInferredTaxonFilterMapper(ControllerBase controller, string actionName) - { - var actionDescriptor = new ReflectedControllerDescriptor(controller.GetType()).FindAction(controller.ControllerContext, actionName); - - if (actionDescriptor == null || actionDescriptor.GetParameters().Length == 0) - return null; - - IUrlParamsMapper result = null; - if (actionDescriptor.GetParameters()[0].ParameterType == typeof(ITaxon)) - { - var taxonParamName = actionDescriptor.GetParameters()[0].ParameterName; - if (actionDescriptor.GetParameters()[1].ParameterType == typeof(int?)) - { - var pageParamName = actionDescriptor.GetParameters()[1].ParameterName; - result = new CustomActionParamsMapper(controller, () => "/{" + taxonParamName + ":category,tag}/{" + pageParamName + "}", actionName); - } - - result = result.SetLast(new CustomActionParamsMapper(controller, () => "/{" + taxonParamName + ":category,tag}", actionName)); - } - - return result; - } - - private IUrlParamsMapper GetInferredPagingMapper(ControllerBase controller, string actionName) - { - var actionDescriptor = new ReflectedControllerDescriptor(controller.GetType()).FindAction(controller.ControllerContext, actionName); - - if (actionDescriptor == null || actionDescriptor.GetParameters().Length == 0 || actionDescriptor.GetParameters()[0].ParameterType != typeof(int?)) - return null; - - return new CustomActionParamsMapper(controller, () => "/{" + actionDescriptor.GetParameters()[0].ParameterName + "}", actionName); - } - - private DynamicModuleType GetDynamicContentType(Type controllerType) - { - var moduleProvider = ModuleBuilderManager.GetManager().Provider; - var controllerName = FrontendManager.ControllerFactory.GetControllerName(controllerType); - var dynamicContentType = moduleProvider.GetDynamicModules().Where(m => m.Status == DynamicModuleStatus.Active) - .Join(moduleProvider.GetDynamicModuleTypes().Where(t => t.TypeName == controllerName), m => m.Id, t => t.ParentModuleId, (m, t) => t) - .FirstOrDefault(); - return dynamicContentType; - } - - /// - /// The controller name key - /// - public const string ControllerNameKey = "controller"; - } -} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/FeatherActionInvoker.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/FeatherActionInvoker.cs new file mode 100644 index 000000000..d960cf273 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/FeatherActionInvoker.cs @@ -0,0 +1,534 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Reflection; +using System.Threading; +using System.Web; +using System.Web.Configuration; +using System.Web.Mvc; +using System.Web.UI; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Configuration; +using Telerik.Sitefinity.DynamicModules; +using Telerik.Sitefinity.DynamicModules.Model; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Personalization; +using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing.Date; +using Telerik.Sitefinity.Localization; +using Telerik.Sitefinity.Model; +using Telerik.Sitefinity.Modules.Pages.Configuration; +using Telerik.Sitefinity.Mvc; +using Telerik.Sitefinity.Mvc.Proxy; +using Telerik.Sitefinity.Taxonomies; +using Telerik.Sitefinity.Taxonomies.Model; +using Telerik.Sitefinity.Utilities.TypeConverters; +using Telerik.Sitefinity.Web; +using Telerik.Sitefinity.Web.UI; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + /// + /// Extends by providing logic for custom routing. + /// + public class FeatherActionInvoker : Telerik.Sitefinity.Mvc.ControllerActionInvoker + { + /// + /// Gets the default parameters mapper. + /// + /// The controller. + /// The default parameters mapper for the controller. + internal IUrlParamsMapper GetDefaultParamsMapper(ControllerBase controller) + { + IUrlParamsMapper result = null; + result = result + .SetLast(this.GetInferredDetailActionParamsMapper(controller)) + .SetLast(this.GetInferredSuccessorsActionParamsMapper(controller)) + .SetLast(this.GetInferredTaxonFilterQueryParamsMapper(controller, "ListByTaxon")) + .SetLast(this.GetInferredTaxonFilterMapper(controller, "ListByTaxon")) + .SetLast(this.GetInferredClassificationFilterMapper(controller, "ListByTaxon")) + .SetLast(this.GetInferredDateFilterMapper(controller, "ListByDate")) + .SetLast(this.GetInferredPagingMapper(controller, "Index")); + + // If no other mappers are added we skip the default one. + if (result != null) + result.SetLast(new DefaultUrlParamsMapper(controller)); + + return result; + } + + /// + /// Gets the prefix parameters mapper. + /// + /// The controller. + /// + internal IUrlParamsMapper GetPrefixParamsMapper(ControllerBase controller) + { + IUrlParamsMapper result = null; + result = result + .SetLast(this.GetInferredSuccessorsActionParamsMapper(controller)) + .SetLast(this.GetInferredPagingMapper(controller, "Index")); + + // If no other mappers are added we skip the default one. + if (result != null) + result.SetLast(new DefaultUrlParamsMapper(controller)); + + return result; + } + + /// + protected override bool ShouldProcessRequest(MvcProxyBase proxyControl) + { + var shouldProcess = base.ShouldProcessRequest(proxyControl); + + var toolboxesConfig = Config.Get(); + shouldProcess &= toolboxesConfig != null; + + return shouldProcess; + } + + /// + protected override void InitializeRouteParameters(MvcProxyBase proxyControl) + { + var originalContext = this.Context.Request.RequestContext ?? proxyControl.Page.GetRequestContext(); + + this.SetControllerRouteParam(proxyControl); + + var controller = proxyControl.GetController(); + + if (!FrontendManager.AttributeRouting.HasAttributeRouting(controller.RouteData)) + { + var paramsMapper = this.GetDefaultParamsMapper(controller); + if (paramsMapper != null) + { + var originalParams = MvcRequestContextBuilder.GetRouteParams(originalContext); + var requestContext = proxyControl.RequestContext; + + var modelProperty = controller.GetType().GetProperty("Model"); + if (modelProperty != null) + { + var model = modelProperty.GetValue(controller, null); + var modelUrlKeyProperty = model == null ? null : model.GetType().GetProperty("UrlKeyPrefix"); + var modelUrlKeyPrefix = modelUrlKeyProperty == null ? null : (string)modelUrlKeyProperty.GetValue(model, null); + var expectedUrlKeyPrefix = string.IsNullOrEmpty(modelUrlKeyPrefix) ? null : "!" + modelUrlKeyPrefix; + var currentUrlKeyPrefix = originalParams == null ? null : originalParams.FirstOrDefault(p => p.StartsWith("!", StringComparison.OrdinalIgnoreCase)); + + if (expectedUrlKeyPrefix == currentUrlKeyPrefix) + { + paramsMapper.ResolveUrlParams(originalParams, requestContext, modelUrlKeyPrefix); + } + } + else + { + paramsMapper.ResolveUrlParams(originalParams, requestContext); + } + + if (!proxyControl.ContentTypeName.IsNullOrEmpty()) + controller.RouteData.Values.Add("contentTypeName", proxyControl.ContentTypeName); + } + else + { + proxyControl.RequestContext.RouteData.Values.Remove(FeatherActionInvoker.ControllerNameKey); + base.InitializeRouteParameters(proxyControl); + } + } + else + { + if (this.ShouldProcessRequest(controller)) + { + // in indexing mode, we only request pages, therefore there in no need to update data for relative routes + if (!proxyControl.IsIndexingMode()) + { + if (FrontendManager.AttributeRouting.UpdateRouteData(this.Context, controller.RouteData)) + { + RouteHelper.SetUrlParametersResolved(); + } + } + else + { + //// Attribute routing was successful. + RouteHelper.SetUrlParametersResolved(); + } + } + } + } + + /// + /// Logs exceptions thrown by the invocation of + /// + /// The proxy control. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + protected override void ExecuteController(MvcProxyBase proxyControl) + { + // Stop processing, personalized widgets are executed asynchronously + if (proxyControl is PersonalizedWidgetProxy) + return; + + var controller = proxyControl.GetController(); + if (proxyControl.IsIndexingMode() && controller.GetIndexRenderMode() == IndexRenderModes.NoOutput) + return; + + try + { + this.TryLoadTempData(controller); + base.ExecuteController(proxyControl); + } + catch (Exception ex) + { + this.HandleControllerException(ex); + } + finally + { + this.TrySaveTempData(controller); + } + } + + /// + /// Handles the exception that occurred when executing the controller. + /// + /// The exception. + protected virtual void HandleControllerException(Exception err) + { + // prevent sending sensitive security information to the client + var cryptoException = err as System.Security.Cryptography.CryptographicException; + if (cryptoException != null) + { + Thread.Sleep(0); // protect from timing attack + return; + } + + if (!(err is ThreadAbortException)) + if (Exceptions.HandleException(err, ExceptionPolicyName.IgnoreExceptions)) + throw err; + + this.Context.Response.Clear(); + + if (this.ShouldDisplayErrors()) + this.Context.Response.Write(Res.Get().ErrorExecutingController); + } + + /// + /// Determines whether errors should be displayed. + /// + /// True if errors should be displayed, False to fail silently. + protected virtual bool ShouldDisplayErrors() + { + var configuration = WebConfigurationManager.OpenWebConfiguration("~/Web.config"); + var customErrors = configuration.GetSection("system.web/customErrors") as CustomErrorsSection; + + if (customErrors == null) + return true; + + return customErrors.Mode == CustomErrorsMode.Off || (customErrors.Mode == CustomErrorsMode.RemoteOnly && HttpContext.Current.Request.IsLocal); + } + + internal static object GetModelProperty(ControllerBase controller, string propertyName) + { + object wrapper; + var modelProperty = controller.GetType().GetProperty("Model"); + + if (modelProperty != null) + { + wrapper = modelProperty.GetValue(controller, null); + } + else + { + wrapper = controller; + } + + var providerNameProperty = wrapper.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).FirstOrDefault(p => p.Name == propertyName); + + if (providerNameProperty != null) + { + return providerNameProperty.GetValue(wrapper, null); + } + + return null; + } + + private IUrlParamsMapper GetInferredDetailActionParamsMapper(ControllerBase controller) + { + var controllerType = controller.GetType(); + IUrlParamsMapper result = null; + + var detailsAction = new ReflectedControllerDescriptor(controllerType).FindAction(controller.ControllerContext, DetailActionParamsMapper.DefaultActionName); + if (detailsAction != null) + { + var contentParam = detailsAction.GetParameters().FirstOrDefault(); + if (contentParam != null && contentParam.ParameterType.ImplementsInterface(typeof(IDataItem))) + { + Type contentType; + if (typeof(DynamicContent) == contentParam.ParameterType) + { + var dynamicContentType = controller.GetDynamicContentType(); + contentType = dynamicContentType != null ? TypeResolutionService.ResolveType(dynamicContentType.GetFullTypeName(), throwOnError: false) : null; + } + else + { + contentType = contentParam.ParameterType; + } + + if (contentType != null) + { + var providerNames = GetModelProperty(controller, "ProviderName") as string; + result = result.SetLast(new DetailActionParamsMapper(controller, contentType, () => providerNames)); + } + } + } + + return result; + } + + private IUrlParamsMapper GetInferredSuccessorsActionParamsMapper(ControllerBase controller) + { + IUrlParamsMapper result = null; + var controllerType = controller.GetType(); + if (controllerType.ImplementsInterface(typeof(ICanFilterByParent))) + { + var successorsAction = new ReflectedControllerDescriptor(controllerType).FindAction(controller.ControllerContext, SuccessorsActionParamsMapper.DefaultActionName); + if (successorsAction != null) + { + ICanFilterByParent canFilterByParent = controller as ICanFilterByParent; + var parentContentTypes = canFilterByParent.GetParentTypes(); + if (parentContentTypes != null && parentContentTypes.Count() > 0) + { + var providerName = GetModelProperty(controller, "ProviderName") as string; + result = result.SetLast(new SuccessorsActionParamsMapper(controller, parentContentTypes, () => providerName)); + } + } + } + + return result; + } + + private IUrlParamsMapper GetInferredDateFilterMapper(ControllerBase controller, string actionName) + { + var actionDescriptor = new ReflectedControllerDescriptor(controller.GetType()).FindAction(controller.ControllerContext, actionName); + + if (actionDescriptor == null || actionDescriptor.GetParameters().Length == 0) + { + return null; + } + + return new DateUrlParamsMapper(controller, new DateUrlEvaluatorAdapter()); + } + + private IUrlParamsMapper GetInferredTaxonFilterQueryParamsMapper(ControllerBase controller, string actionName) + { + IUrlParamsMapper result = null; + + var actionDescriptor = new ReflectedControllerDescriptor(controller.GetType()).FindAction(controller.ControllerContext, actionName); + if (actionDescriptor == null || actionDescriptor.GetParameters().Length == 0) + { + return null; + } + + var queryParams = controller.ControllerContext.RequestContext.HttpContext.Request.QueryString; + if (actionDescriptor.GetParameters()[0].ParameterType == typeof(ITaxon) && queryParams.Count == 3) + { + if (queryParams.Keys.Contains("taxonomy")) + { + result = new TaxonomyUrlParamsMapper(controller, new TaxonUrlMapper(new TaxonUrlEvaluatorAdapter())); + } + } + + return result; + } + + private IUrlParamsMapper GetInferredTaxonFilterMapper(ControllerBase controller, string actionName) + { + var actionDescriptor = new ReflectedControllerDescriptor(controller.GetType()).FindAction(controller.ControllerContext, actionName); + + if (actionDescriptor == null || actionDescriptor.GetParameters().Length == 0) + return null; + + var contentType = GetModelProperty(controller, "ContentType") as Type; + if (contentType == null && controller is IDynamicContentWidget) + { + var dynamicType = controller.GetDynamicContentType(); + if (dynamicType != null) + { + contentType = TypeResolutionService.ResolveType(dynamicType.GetFullTypeName()); + } + } + + ISet taxonomiesForType = null; + if (contentType != null) + { + var properties = TypeDescriptor.GetProperties(contentType); + taxonomiesForType = properties.OfType().Select(x => x.TaxonomyId).ToHashSet(); + } + + if (taxonomiesForType != null && taxonomiesForType.Count == 0) + { + return null; + } + + IUrlParamsMapper result = null; + if (actionDescriptor.GetParameters()[0].ParameterType == typeof(ITaxon)) + { + string routeTemplate = GenerateRouteTemplate(taxonomiesForType); + var taxonParamName = actionDescriptor.GetParameters()[0].ParameterName; + if (actionDescriptor.GetParameters()[1].ParameterType == typeof(int?)) + { + var pageParamName = actionDescriptor.GetParameters()[1].ParameterName; + var urlParamNames = new string[] { FeatherActionInvoker.TaxonNamedParamter, FeatherActionInvoker.PagingNamedParameter }; + result = new CustomActionParamsMapper(controller, () => "/{" + taxonParamName + ":" + routeTemplate + "}/{" + pageParamName + ":int}", actionName, urlParamNames); + } + + var urlTaxonParamNames = new string[] { FeatherActionInvoker.TaxonNamedParamter }; + result = result.SetLast(new CustomActionParamsMapper(controller, () => "/{" + taxonParamName + ":" + routeTemplate + "}", actionName, urlTaxonParamNames)); + } + + return result; + } + + private string GenerateRouteTemplate(ISet taxonomiesForType) + { + string routeTemplate = string.Empty; + + var taxonomies = TaxonomyManager.GetTaxonomiesCache(); + + if (taxonomies.Count() > 0) + { + var taxonomyNames = new List(); + foreach (var taxonomy in taxonomies) + { + if (taxonomiesForType != null && !taxonomiesForType.Contains(taxonomy.Id)) + continue; + + if (taxonomy.Id == TaxonomyManager.TagsTaxonomyId) + { + taxonomyNames.Add("tag"); + } + else if (taxonomy.Id == TaxonomyManager.CategoriesTaxonomyId) + { + taxonomyNames.Add("category"); + } + else + { + taxonomyNames.Add(taxonomy.Name.ToLowerInvariant()); + } + } + routeTemplate = string.Join(",", taxonomyNames); + } + + return routeTemplate; + } + + private IUrlParamsMapper GetInferredClassificationFilterMapper(ControllerBase controller, string actionName) + { + var actionDescriptor = new ReflectedControllerDescriptor(controller.GetType()).FindAction(controller.ControllerContext, actionName); + + if (actionDescriptor == null || actionDescriptor.GetParameters().Length == 0) + return null; + + return new TaxonomyUrlParamsMapper(controller, new TaxonUrlMapper(new TaxonUrlEvaluatorAdapter())); + } + + private IUrlParamsMapper GetInferredPagingMapper(ControllerBase controller, string actionName) + { + var actionDescriptor = new ReflectedControllerDescriptor(controller.GetType()).FindAction(controller.ControllerContext, actionName); + + if (actionDescriptor == null || actionDescriptor.GetParameters().Length == 0 || actionDescriptor.GetParameters()[0].ParameterType != typeof(int?)) + return null; + + var urlParamNames = new string[] { FeatherActionInvoker.PagingNamedParameter }; + + return new CustomActionParamsMapper(controller, () => "/{" + actionDescriptor.GetParameters()[0].ParameterName + ":int}", actionName, urlParamNames); + } + + private void SetControllerRouteParam(MvcProxyBase proxyControl) + { + var requestContext = proxyControl.RequestContext; + + string controllerName; + var widgetProxy = proxyControl as MvcWidgetProxy; + if (widgetProxy != null && !string.IsNullOrEmpty(widgetProxy.WidgetName)) + { + controllerName = widgetProxy.WidgetName; + } + else + { + controllerName = SitefinityViewEngine.GetControllerName(proxyControl.GetController()); + } + + requestContext.RouteData.Values[FeatherActionInvoker.ControllerNameKey] = controllerName; + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + private void TrySaveTempData(Controller controller) + { + try + { + if (controller != null && controller.ControllerContext != null && controller.Session != null && !controller.ControllerContext.IsChildAction) + { + controller.TempData.Save(controller.ControllerContext, controller.TempDataProvider); + } + } + catch (Exception ex) + { + var exceptionMessage = string.Format( + "Failed to Save TempData. Class: {0}, Method: {1}, Exception {2}, Stack Trace {3}", + this.GetType().Name, + System.Reflection.MethodInfo.GetCurrentMethod().Name, + ex.Message, + ex.StackTrace); + + Log.Write(exceptionMessage, ConfigurationPolicy.ErrorLog); + } + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + private void TryLoadTempData(Controller controller) + { + try + { + if (controller != null && controller.ControllerContext != null && controller.Session != null && !controller.ControllerContext.IsChildAction) + { + // Saving the current temp data. + var oldTempData = new TempDataDictionary(); + foreach (var kv in controller.TempData) + { + oldTempData.Add(kv.Key, kv.Value); + } + + // Loading the temp data removes all current temp data. + controller.TempData.Load(controller.ControllerContext, controller.TempDataProvider); + + // Restoring the current temp data. + foreach (var kv in oldTempData) + { + controller.TempData[kv.Key] = kv.Value; + } + } + } + catch (Exception ex) + { + var exceptionMessage = string.Format( + "Failed to Load TempData. Class: {0}, Method: {1}, Exception {2}, Stack Trace {3}", + this.GetType().Name, + System.Reflection.MethodInfo.GetCurrentMethod().Name, + ex.Message, + ex.StackTrace); + + Log.Write(exceptionMessage, ConfigurationPolicy.ErrorLog); + } + } + + /// + /// The controller name key + /// + public const string ControllerNameKey = "controller"; + + /// + /// The name of the page route parameter + /// + internal const string PagingNamedParameter = "page"; + + /// + /// The name of the taxon route parameter + /// + internal const string TaxonNamedParamter = "taxon"; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/IUrlParamsMapper.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/IUrlParamsMapper.cs index caeb4d190..66edfc103 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/IUrlParamsMapper.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/IUrlParamsMapper.cs @@ -30,6 +30,14 @@ internal interface IUrlParamsMapper /// The URL parameters. /// The request context. void ResolveUrlParams(string[] urlParams, RequestContext requestContext); + + /// + /// Resolves the URL parameters. Should call RouteHelper.SetUrlParametersResolved if the mapping was successful. + /// + /// The URL parameters. + /// The request context. + /// The URL key prefix. + void ResolveUrlParams(string[] urlParams, RequestContext requestContext, string urlKeyPrefix); } internal static class UrlParamsMapperExtensions diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/IntParamResolver.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/IntParamResolver.cs new file mode 100644 index 000000000..1dd1af8c2 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/IntParamResolver.cs @@ -0,0 +1,25 @@ +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + /// + /// Instances of this class resolve integers. + /// + internal class IntParamResolver : RouteParamResolverBase + { + /// + protected override bool TryResolveParamInternal(string urlParam, out object value) + { + int intValue; + + if (int.TryParse(urlParam, out intValue)) + { + value = intValue; + return true; + } + else + { + value = null; + return false; + } + } + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcPageEditorRouteHandler.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcPageEditorRouteHandler.cs new file mode 100644 index 000000000..016e7fd00 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcPageEditorRouteHandler.cs @@ -0,0 +1,41 @@ +using System.Web; +using System.Web.Routing; +using System.Web.UI; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + /// + /// Represents an extended route handler for Sitefinity's page editor that injects MVC specific logic. + /// + public class MvcPageEditorRouteHandler : PageEditorRouteHandler + { + /// + /// Builds a handler for the specified request and page data. + /// + /// The request context. + /// The page data. + /// The handelr. + protected override IHttpHandler BuildHandler(RequestContext requestContext, IPageData pageData) + { + var handler = base.BuildHandler(requestContext, pageData); + new PageInitializer().Initialize(handler); + + var page = handler.GetPageHandler(); + if (page != null) + { + page.Init += this.MvcPageEditorRouteHandlerInit; + } + + return handler; + } + + private void MvcPageEditorRouteHandlerInit(object sender, System.EventArgs e) + { + var page = (Page)sender; + + page.Header.Controls.Add(new LiteralControl(new PageInitializer().GetInlineStyle())); + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcPageRouteHandler.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcPageRouteHandler.cs new file mode 100644 index 000000000..831e5bf4d --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcPageRouteHandler.cs @@ -0,0 +1,24 @@ +using System.Web; +using System.Web.Routing; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + /// + /// Extended route handler for Sitefinity pages that injects MVC specific logic. + /// + public class MvcPageRouteHandler : Telerik.Sitefinity.Web.PageRouteHandler + { + /// + /// Provides the object that processes the request. + /// + /// An object that encapsulates information about the request. + /// An object that processes the request. + protected override IHttpHandler BuildHttpHandler(RequestContext requestContext) + { + var handler = base.BuildHttpHandler(requestContext); + new PageInitializer().Initialize(handler); + + return handler; + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcTemplateEditorRouteHandler.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcTemplateEditorRouteHandler.cs new file mode 100644 index 000000000..d25764d08 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcTemplateEditorRouteHandler.cs @@ -0,0 +1,42 @@ +using System.Web; +using System.Web.Routing; +using System.Web.UI; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + /// + /// Extended version of the TemplateEditorRouteHandler that injects logic handling MVC layout files. + /// + public class MvcTemplateEditorRouteHandler : TemplateEditorRouteHandler + { + /// + /// Builds the handler. + /// + /// The request context. + /// The page data. + /// + protected override IHttpHandler BuildHandler(RequestContext requestContext, IPageData pageData) + { + var handler = base.BuildHandler(requestContext, pageData); + new PageInitializer().Initialize(handler); + + var page = handler.GetPageHandler(); + if (page != null) + { + page.Init += this.MvcTemplateEditorRouteHandlerInit; + } + + return handler; + } + + private void MvcTemplateEditorRouteHandlerInit(object sender, System.EventArgs e) + { + var page = (Page)sender; + + page.Header.Controls.Add(new LiteralControl(new PageInitializer().GetInlineStyle())); + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcVersioningRouteHandler.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcVersioningRouteHandler.cs new file mode 100644 index 000000000..5863ca384 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcVersioningRouteHandler.cs @@ -0,0 +1,25 @@ +using System.Web; +using System.Web.Routing; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + /// + /// Extended route handler for Sitefinity versioning that injects MVC specific logic. + /// + public class MvcVersioningRouteHandler : VersioningRouteHandler + { + /// + /// Provides the object that processes the request. + /// + /// An object that encapsulates information about the request. + /// An object that processes the request. + public override IHttpHandler GetHttpHandler(RequestContext requestContext) + { + var handler = base.GetHttpHandler(requestContext); + new PageInitializer().Initialize(handler); + + return handler; + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/PageRelativePathContextRegion.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/PageRelativePathContextRegion.cs new file mode 100644 index 000000000..a732308ad --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/PageRelativePathContextRegion.cs @@ -0,0 +1,68 @@ +using System; +using System.Web; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + /// + /// In the scope of the region the request path of the context is rewritten to omit the page node URL in order to get node-relative path. + /// + internal sealed class PageRelativePathContextRegion : IDisposable + { + /// + /// Initializes a new instance of the class. + /// + /// The context. + public PageRelativePathContextRegion(HttpContextBase context) + { + if (context == null) + throw new ArgumentNullException("context"); + + this.context = context; + this.originalPath = context.Request.AppRelativeCurrentExecutionFilePath; + var originalWithSlash = VirtualPathUtility.AppendTrailingSlash(this.originalPath); + + bool? isFrontendPageEdit = context.Items["IsFrontendPageEdit"] as bool?; + var currentNode = SiteMapBase.GetCurrentNode(); + if (currentNode != null && !(isFrontendPageEdit.HasValue && isFrontendPageEdit.Value)) + { + var nodeUrl = currentNode.Url.StartsWith("~/", StringComparison.Ordinal) ? RouteHelper.ResolveUrl(currentNode.Url, UrlResolveOptions.ApplicationRelative | UrlResolveOptions.AppendTrailingSlash) : currentNode.Url; + var comparisonNodeUrl = nodeUrl.Replace("~", string.Empty); + if (originalWithSlash.StartsWith(nodeUrl, StringComparison.OrdinalIgnoreCase)) + { + var newPath = originalWithSlash.Right(originalWithSlash.Length - nodeUrl.Length); + + this.context.RewritePath("~/" + newPath); + } + else if (SystemManager.CurrentContext.CurrentSite.Cultures.Length > 1 && originalWithSlash.StartsWith($"~/{SystemManager.CurrentContext.Culture}/", StringComparison.OrdinalIgnoreCase) && originalWithSlash.Contains(comparisonNodeUrl)) + { + var newPath = originalWithSlash.Right(originalWithSlash.Length - nodeUrl.Length - SystemManager.CurrentContext.Culture.Name.Length - 1); + + this.context.RewritePath("~/" + newPath); + } + else if (currentNode.IsHomePage() && + RouteHelper.ResolveUrl(SystemManager.CurrentContext.CurrentSite.GetUri().AbsolutePath, UrlResolveOptions.ApplicationRelative | UrlResolveOptions.AppendTrailingSlash) == originalWithSlash) + { + // The request is to the root of the site + this.context.RewritePath("~/"); + } + } + else + { + this.context.RewritePath("~/"); + } + } + + /// + /// Releases unmanaged and - optionally - managed resources. + /// + public void Dispose() + { + this.context.RewritePath(this.originalPath); + } + + private readonly HttpContextBase context; + private readonly string originalPath; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/RelativeDirectRouteProvider.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/RelativeDirectRouteProvider.cs new file mode 100644 index 000000000..f4a12a7e4 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/RelativeDirectRouteProvider.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web.Mvc; +using System.Web.Mvc.Routing; +using Telerik.Sitefinity.Mvc; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + /// + /// Direct route provider that extracts relative routes. + /// + internal sealed class RelativeDirectRouteProvider : DefaultDirectRouteProvider + { + /// Gets a set of route factories for the given action descriptor. + /// A set of route factories. + /// The action descriptor. + protected override IReadOnlyList GetActionRouteFactories(ActionDescriptor actionDescriptor) + { + var methodInfoActionDescriptor = actionDescriptor as IMethodInfoActionDescriptor; + if (methodInfoActionDescriptor != null && methodInfoActionDescriptor.MethodInfo != null && + actionDescriptor.ControllerDescriptor != null && methodInfoActionDescriptor.MethodInfo.DeclaringType != actionDescriptor.ControllerDescriptor.ControllerType) + { + return null; + } + + var customAttributes = actionDescriptor.GetCustomAttributes(false); + var relativeRouteAttributes = customAttributes.OfType().Select(r => r.DirectRouteFactory).ToList(); + + return relativeRouteAttributes; + } + + /// Gets route factories for the given controller descriptor. + /// A set of route factories. + /// The controller descriptor. + protected override IReadOnlyList GetControllerRouteFactories(ControllerDescriptor controllerDescriptor) + { + if (controllerDescriptor == null) + throw new ArgumentNullException("controllerDescriptor"); + + var customAttributes = controllerDescriptor.GetCustomAttributes(false); + var directRouteFactories = customAttributes.OfType().Select(r => r.DirectRouteFactory).ToList(); + return directRouteFactories; + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/RelativeRouteAttribute.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/RelativeRouteAttribute.cs new file mode 100644 index 000000000..6a9a8c66a --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/RelativeRouteAttribute.cs @@ -0,0 +1,96 @@ +using System; +using System.Web.Mvc; +using System.Web.Mvc.Routing; + +namespace Telerik.Sitefinity.Mvc +{ + /// + /// Place on a controller or action to expose it via a route that is relative to the current page. + /// + [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = false, AllowMultiple = true)] + public sealed class RelativeRouteAttribute : Attribute + { + /// + /// Gets or sets the name of the route. + /// + /// + /// The name of the route. + /// + public string Name + { + get + { + return this.wrappedAttribute.Name; + } + + set + { + this.wrappedAttribute.Name = value; + } + } + + /// + /// Gets the order the route is applied. + /// + /// + /// The order the route is applied. + /// + public int Order + { + get + { + return this.wrappedAttribute.Order; + } + } + + /// + /// Gets the pattern for the route to match. + /// + /// + /// The pattern to match. + /// + public string Template + { + get + { + return this.wrappedAttribute.Template; + } + } + + /// + /// Gets the direct route factory corresponding to this attribute. + /// + /// + /// The direct route factory. + /// + public IDirectRouteFactory DirectRouteFactory + { + get + { + return this.wrappedAttribute; + } + } + + /// + /// Initializes a new instance of the class. + /// + public RelativeRouteAttribute() : this(string.Empty) + { + } + + /// + /// Initializes a new instance of the class with the specified template. + /// + /// The pattern of the route to match. + /// template + public RelativeRouteAttribute(string template) + { + if (template == null) + throw new ArgumentNullException("template"); + + this.wrappedAttribute = new RouteAttribute(template); + } + + private readonly RouteAttribute wrappedAttribute; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/SuccessorsActionParamsMapper.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/SuccessorsActionParamsMapper.cs new file mode 100644 index 000000000..6a373c3df --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/SuccessorsActionParamsMapper.cs @@ -0,0 +1,148 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web.Mvc; +using System.Web.Routing; +using Telerik.Sitefinity.Frontend.Mvc.Helpers; +using Telerik.Sitefinity.Model; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + /// + /// Instances of this class resolve successor items by the URL. + /// + internal class SuccessorsActionParamsMapper : UrlParamsMapperBase + { + /// + /// Initializes a new instance of the class. + /// + /// The controller. + /// Parent types of the current type. + public SuccessorsActionParamsMapper(ControllerBase controller, IEnumerable parentTypes) + : this(controller, parentTypes, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The controller. + /// Parent types of the current type. + /// A function that returns provider name for the content. If null then default provider is used. + public SuccessorsActionParamsMapper(ControllerBase controller, IEnumerable parentTypes, Func providerNameResolver) + : this(controller, parentTypes, providerNameResolver, SuccessorsActionParamsMapper.DefaultActionName) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The controller. + /// Parent types of the current type. + /// A function that returns provider name for the content. If null then default provider is used. + /// Name of the action. + /// When the given controller does not contain a method corresponding to the action name. + public SuccessorsActionParamsMapper(ControllerBase controller, IEnumerable parentTypes, Func providerNameResolver, string actionName) + : base(controller) + { + if (parentTypes == null) + throw new ArgumentNullException("itemType"); + + this.actionName = actionName; + this.providerNameResolver = providerNameResolver; + + this.ActionMethod = new ReflectedControllerDescriptor(controller.GetType()).FindAction(controller.ControllerContext, actionName); + if (this.ActionMethod == null) + throw new ArgumentException("The controller {0} does not have action '{1}'.".Arrange(controller.GetType().Name, actionName)); + + this.ParentTypes = parentTypes; + } + + /// + protected override bool TryMatchUrl(string[] urlParams, RequestContext requestContext, string urlKeyPrefix) + { + return this.TryMatchUrl(urlParams, requestContext, true); + } + + /// + /// Adds the parent content item to route data. + /// + /// The request context. + /// The parent item. + /// Type of the item. + /// Whether to set the url parameters resolved + protected virtual void AddParentContentItemToRouteData(RequestContext requestContext, IDataItem parentItem, Type itemType, bool setUrlParametersResolved = true) + { + requestContext.RouteData.Values[UrlParamsMapperBase.ActionNameKey] = this.actionName; + + var parameters = this.ActionMethod.GetParameters(); + if (parameters.Length > 0 && parameters[0].ParameterType.IsAssignableFrom(itemType)) + { + requestContext.RouteData.Values[parameters[0].ParameterName] = parentItem; + } + + if (requestContext.HttpContext.Request["page"] != null) + requestContext.RouteData.Values["page"] = int.Parse(requestContext.HttpContext.Request["page"]); + + if (setUrlParametersResolved) + { + RouteHelper.SetUrlParametersResolved(); + } + } + + private bool TryMatchUrl(string[] urlParams, RequestContext requestContext, bool setUrlParametersResolved) + { + if (urlParams == null || urlParams.Length == 0) + return false; + + var url = RouteHelper.GetUrlParameterString(urlParams); + string redirectUrl; + var providerName = this.providerNameResolver != null ? this.providerNameResolver() : null; + var contentItemResolver = new ContentDataItemResolver(); + + foreach (var parentType in this.ParentTypes) + { + var item = contentItemResolver.GetItemByUrl(url, parentType, providerName, out redirectUrl); + + if (item != null) + { + this.AddParentContentItemToRouteData(requestContext, item, parentType, setUrlParametersResolved); + + return true; + } + } + + if (urlParams.Length > 1) + { + this.TryMatchUrl(urlParams.Take(urlParams.Length - 1).ToArray(), requestContext, false); + } + + return false; + } + + /// + /// Gets or sets the parent types. + /// + /// + /// The parent types. + /// + protected IEnumerable ParentTypes { get; set; } + + /// + /// Gets the action method. + /// + /// + /// The action method. + /// + protected ActionDescriptor ActionMethod { get; private set; } + + /// + /// The default details action name. + /// + public const string DefaultActionName = "Successors"; + + private string actionName; + private Func providerNameResolver; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/TaxonParamResolver.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/TaxonParamResolver.cs index 033ea9433..76454d370 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/TaxonParamResolver.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/TaxonParamResolver.cs @@ -17,18 +17,32 @@ internal class TaxonParamResolver : RouteParamResolverBase /// When taxonomy with the given name is not found. public TaxonParamResolver(string taxonomyName) { - this.taxonomy = TaxonomyManager.GetManager().GetTaxonomies().FirstOrDefault(t => t.Name == taxonomyName); + this.taxonomy = GetTaxonomy(taxonomyName); if (this.taxonomy == null) throw new ArgumentException("Taxonomy with name {0} was not found!".Arrange(taxonomyName)); } + private ITaxonomyProxy GetTaxonomy(string taxonomyName) + { + if (taxonomyName.Equals("category")) + { + taxonomyName = "Categories"; + } + else if (taxonomyName.Equals("tag")) + { + taxonomyName = "Tags"; + } + + return TaxonomyManager.GetTaxonomiesCache().FirstOrDefault(t => t.Name.Equals(taxonomyName, StringComparison.OrdinalIgnoreCase)); + } + /// /// Gets the taxonomy. /// /// /// The taxonomy. /// - protected Taxonomy Taxonomy + protected ITaxonomyProxy Taxonomy { get { @@ -39,10 +53,16 @@ protected Taxonomy Taxonomy /// protected override bool TryResolveParamInternal(string urlParam, out object value) { - value = this.Taxonomy.Taxa.FirstOrDefault(t => t.UrlName == urlParam); + if (urlParam == null) + { + value = null; + return false; + } + + value = TaxonomyManager.GetManager().GetTaxa().FirstOrDefault(t => t.TaxonomyId == this.Taxonomy.Id && t.UrlName == urlParam); return value != null; } - private Taxonomy taxonomy; + private ITaxonomyProxy taxonomy; } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/ITaxonUrlEvaluatorAdapter.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/ITaxonUrlEvaluatorAdapter.cs new file mode 100644 index 000000000..5ab5b8d00 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/ITaxonUrlEvaluatorAdapter.cs @@ -0,0 +1,9 @@ +using Telerik.Sitefinity.Taxonomies.Model; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + internal interface ITaxonUrlEvaluatorAdapter + { + bool TryGetTaxonFromUrl(string url, string urlKeyPrefix, out ITaxon taxon); + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlEvaluator.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlEvaluator.cs new file mode 100644 index 000000000..2574d2812 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlEvaluator.cs @@ -0,0 +1,40 @@ +using System; +using System.Web; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Taxonomies.Model; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + public static class TaxonUrlEvaluator + { + /// + /// Gets the taxon from query. + /// + /// The context. + /// + public static ITaxon GetTaxonFromQuery(HttpContextBase context) + { + return GetTaxonFromQuery(context, null); + } + + /// + /// Gets the taxon from query. + /// + /// The context. + /// The URL key prefix. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "1#")] + public static ITaxon GetTaxonFromQuery(HttpContextBase context, string urlKeyPrefix) + { + if (context == null || + context.Request == null) + { + return null; + } + + var taxonUrlEvaluatorAdapter = new TaxonUrlEvaluatorAdapter(); + + return taxonUrlEvaluatorAdapter.GetTaxonFromUrl(context.Request.RawUrl, UrlEvaluationMode.QueryString, urlKeyPrefix); + } + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlEvaluatorAdapter.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlEvaluatorAdapter.cs new file mode 100644 index 000000000..809f5ac5f --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlEvaluatorAdapter.cs @@ -0,0 +1,66 @@ +using System.Diagnostics.CodeAnalysis; +using Telerik.Sitefinity.Pages.Model; +using Telerik.Sitefinity.Taxonomies.Model; +using Telerik.Sitefinity.Web.UrlEvaluation; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + internal class TaxonUrlEvaluatorAdapter : ITaxonUrlEvaluatorAdapter + { + private readonly TaxonomyEvaluator taxonomyEvaluator; + + public TaxonUrlEvaluatorAdapter() + { + this.taxonomyEvaluator = this.GetDefaultEvaluator(); + } + + [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + public bool TryGetTaxonFromUrl(string url, string urlKeyPrefix, out ITaxon taxon) + { + taxon = this.GetTaxonFromUrl(url, UrlEvaluationMode.UrlPath, urlKeyPrefix); + + return taxon != null; + } + + [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + public ITaxon GetTaxonFromUrl(string url, UrlEvaluationMode mode, string urlPrefix = null) + { + if (this.taxonomyEvaluator == null) + { + return null; + } + + string taxonomyName; + string taxonName; + + this.taxonomyEvaluator.ParseTaxonomyParams(mode, url, urlPrefix, out taxonName, out taxonomyName); + + if (!string.IsNullOrEmpty(taxonName) && !string.IsNullOrEmpty(taxonomyName)) + { + try + { + return this.taxonomyEvaluator.GetTaxonByName(taxonomyName, taxonName); + } + catch + { + return null; + } + } + + return null; + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] + private TaxonomyEvaluator GetDefaultEvaluator() + { + try + { + return UrlEvaluator.GetEvaluator("Taxonomy") as TaxonomyEvaluator; + } + catch + { + return null; + } + } + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlMapper.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlMapper.cs new file mode 100644 index 000000000..29461396d --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlMapper.cs @@ -0,0 +1,154 @@ +using System; +using System.Linq; +using System.Web.Routing; +using Telerik.Sitefinity.Taxonomies.Model; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + /* + * Currently we treat the following url as valid taxon filter route: + * Pattern matching for flat taxon - /page/-in-fieldName/taxonomyName/taxa/[page] + * Pattern matching for hierarchical taxon - /page/-in-fieldName/taxonomyName/parent/[subParent..]/taxon + */ + + /// + /// Instances of this class tries to map Route Data parameters to a valid taxon instace. + /// + internal class TaxonUrlMapper + { + private readonly ITaxonUrlEvaluatorAdapter taxonomyEvaluator; + + public TaxonUrlMapper(ITaxonUrlEvaluatorAdapter taxonomyEvaluator) + { + if (taxonomyEvaluator == null) + { + throw new ArgumentNullException("taxonomyEvaluator"); + } + + this.taxonomyEvaluator = taxonomyEvaluator; + } + + /// + /// Tries to parce a valid taxon from the route data. + /// + /// The URL params. + /// The URL key prefix. + /// The taxon. + /// Index of the page. + /// The reqy. + /// + public bool TryMatch(string[] urlParams, string urlKeyPrefix, out ITaxon taxon, out int pageIndex, RequestContext requestContext = null) + { + taxon = null; + pageIndex = 1; + + if (urlParams == null || urlParams.Length < 3) + { + if (requestContext == null) + { + return false; + } + + taxon = TaxonUrlEvaluator.GetTaxonFromQuery(requestContext.HttpContext, null); + + if (urlParams != null && taxon != null) + { + this.TryGetPageIndex(urlParams, out pageIndex, taxon.Name); + } + + return taxon != null; + } + + string url = string.Join(@"/", urlParams); + + if (!this.taxonomyEvaluator.TryGetTaxonFromUrl(url, urlKeyPrefix, out taxon)) + { + return false; + } + + bool hasPageIndex = this.TryGetPageIndex(urlParams, out pageIndex, taxon.Name); + + if (!this.IsFlatTaxon(taxon)) + { + return true; + } + + return this.CheckForValidFlatTaxonUrl(urlParams, hasPageIndex); + } + + /// + /// Determines whether [is flat taxon] [the specified taxon]. + /// + /// The taxon. + /// + private bool IsFlatTaxon(ITaxon taxon) + { + return taxon is FlatTaxon; + } + + /// + /// Checks for valid flat taxon URL. + /// + /// The URL params. + /// Index of the is previous page. + /// + private bool CheckForValidFlatTaxonUrl(string[] urlParams, bool isPreviousPageIndex) + { + if (urlParams.Length < 2) + { + return false; + } + + ITaxon taxon; + int pageIndex; + + bool hasPageIndex = this.TryGetPageIndex(urlParams, out pageIndex); + + string[] urlSegments = urlParams.Take(urlParams.Length - 1).ToArray(); + + string url = string.Join(@"/", urlSegments); + + bool hasTaxon = this.taxonomyEvaluator.TryGetTaxonFromUrl(url, null, out taxon); + + if (!hasPageIndex && hasTaxon) + { + return false; + } + else if (isPreviousPageIndex && !hasPageIndex && hasTaxon) + { + return false; + } + else if (!hasPageIndex && !hasTaxon) + { + return true; + } + + return this.CheckForValidFlatTaxonUrl(urlSegments, hasPageIndex); + } + + /// + /// Tries the index of the get last page. + /// + /// The URL params. + /// Index of the page. + /// The taxon which is filtered. + /// + private bool TryGetPageIndex(string[] urlParams, out int pageIndex, string taxonName = null) + { + string last = urlParams.LastOrDefault(); + + if (int.TryParse(last, out pageIndex)) + { + if (last.Equals(taxonName)) + { + pageIndex = 0; + return false; + } + + return true; + } + + return false; + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonomyUrlParamsMapper.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonomyUrlParamsMapper.cs new file mode 100644 index 000000000..2c22ea648 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonomyUrlParamsMapper.cs @@ -0,0 +1,69 @@ +using System.Reflection; +using System.Web.Mvc; +using System.Web.Routing; +using Telerik.Sitefinity.Taxonomies.Model; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing +{ + /// + /// Instances of this class map URL parameters to Route Data following a provided route template and action name. + /// + internal class TaxonomyUrlParamsMapper : UrlParamsMapperBase + { + /// + /// Initializes a new instance of the class. + /// + /// The controller. + /// The taxon URL evaluator. + /// Name of the action. + public TaxonomyUrlParamsMapper(ControllerBase controller, TaxonUrlMapper taxonUrlEvaluator, string actionName = TaxonomyUrlParamsMapper.DefaultActionName) : base(controller) + { + this.actionName = actionName; + this.taxonUrlEvaluator = taxonUrlEvaluator; + this.actionMethod = controller.GetType().GetMethod(this.actionName, BindingFlags.Instance | BindingFlags.Public); + } + + /// + protected override bool TryMatchUrl(string[] urlParams, RequestContext requestContext, string urlKeyPrefix) + { + ITaxon taxon; + int pageIndex; + + if (!this.taxonUrlEvaluator.TryMatch(urlParams, urlKeyPrefix, out taxon, out pageIndex, requestContext)) + { + return false; + } + + this.SetControllerActionParams(requestContext, taxon, pageIndex); + + this.Controller.ViewBag.UrlParams = urlParams; + + RouteHelper.SetUrlParametersResolved(); + + return true; + } + + private void SetControllerActionParams(RequestContext requestContext, ITaxon taxon, int pageIndex) + { + requestContext.RouteData.Values[UrlParamsMapperBase.ActionNameKey] = this.actionName; + + foreach (ParameterInfo paramInfo in this.actionMethod.GetParameters()) + { + if (paramInfo.ParameterType == typeof(ITaxon)) + { + requestContext.RouteData.Values[paramInfo.Name] = taxon; + } + else if (paramInfo.ParameterType == typeof(int?) && pageIndex > 0) + { + requestContext.RouteData.Values[paramInfo.Name] = pageIndex; + } + } + } + + private readonly string actionName; + private readonly MethodInfo actionMethod; + private const string DefaultActionName = "ListByTaxon"; + private readonly TaxonUrlMapper taxonUrlEvaluator; + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/UrlParamsMapperBase.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/UrlParamsMapperBase.cs index 4b6a2ac17..1e1ee98c7 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/UrlParamsMapperBase.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/UrlParamsMapperBase.cs @@ -5,7 +5,7 @@ using System.Web.Mvc; using System.Web.Routing; using Telerik.Sitefinity.Abstractions; -using Telerik.Sitefinity.Web; +using Telerik.Sitefinity.Configuration; namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing { @@ -23,6 +23,20 @@ public UrlParamsMapperBase(ControllerBase controller) this.Controller = controller; } + /// + /// Gets a value indicating whether to require parameter naming in the widget routings. + /// + /// + /// true if the routes will work only with named params (e.g /tag/sofia/page/2); otherwise, false when the route will be /sofia/2. + /// + public static bool UseNamedParametersRouting + { + get + { + return Config.Get().UseNamedParametersRouting; + } + } + /// public IUrlParamsMapper Next { @@ -39,10 +53,16 @@ public IUrlParamsMapper SetNext(IUrlParamsMapper nextResolver) /// public void ResolveUrlParams(string[] urlParams, RequestContext requestContext) { - var isMatch = this.TryMatchUrl(urlParams, requestContext); + this.ResolveUrlParams(urlParams, requestContext, null); + } + + /// + public void ResolveUrlParams(string[] urlParams, RequestContext requestContext, string urlKeyPrefix) + { + var isMatch = this.TryMatchUrl(urlParams, requestContext, urlKeyPrefix); if (!isMatch && this.Next != null) - this.Next.ResolveUrlParams(urlParams, requestContext); + this.Next.ResolveUrlParams(urlParams, requestContext, urlKeyPrefix); } /// @@ -59,22 +79,30 @@ public void ResolveUrlParams(string[] urlParams, RequestContext requestContext) /// The action method. /// The meta parameters. /// The URL parameters. + /// The URL parameter names. /// - protected virtual IList MapParams(MethodInfo actionMethod, string[] metaParams, string[] urlParams) + protected virtual IList MapParams(MethodInfo actionMethod, string[] metaParams, string[] urlParams, string[] urlParamNames) { - if (metaParams.Length != urlParams.Length) + var useNamedParams = UrlParamsMapperBase.UseNamedParametersRouting; + if (!useNamedParams && (metaParams.Length != urlParams.Length || metaParams.Length != urlParamNames.Length)) + return null; + if (useNamedParams && ((2 * metaParams.Length) != urlParams.Length || metaParams.Length != urlParamNames.Length)) return null; var parameterInfos = new List(); - for (int i = 0; i < urlParams.Length; i++) + + for (int i = 0; i < urlParamNames.Length; i++) { + string currentParam = useNamedParams ? this.MapNamedParam(urlParams, urlParamNames[i], i) : urlParams[i]; + if (metaParams[i].Length > 2 && metaParams[i].First() == '{' && metaParams[i].Last() == '}') { var routeParam = metaParams[i].Sub(1, metaParams[i].Length - 2); - if (!this.TryResolveRouteParam(actionMethod, routeParam, urlParams[i], parameterInfos)) + routeParam = useNamedParams ? this.MapNamedRouteParam(urlParams, urlParamNames[i], i, routeParam) : routeParam; + if (!this.TryResolveRouteParam(actionMethod, routeParam, currentParam, parameterInfos)) return null; } - else if (!string.Equals(metaParams[i], urlParams[i], StringComparison.OrdinalIgnoreCase)) + else if (!string.Equals(metaParams[i], currentParam, StringComparison.OrdinalIgnoreCase)) { return null; } @@ -83,6 +111,78 @@ protected virtual IList MapParams(MethodInfo actionMethod, strin return parameterInfos; } + /// + /// Maps the URL parameter to a value from the provided URL template + /// + /// The URL parameters. + /// The URL parameter name. + /// The index of the named parameter in the URL. + /// + protected virtual string MapNamedParam(string[] urlParams, string urlParamName, int paramNameIndex) + { + string currentParam; + var urlParamActualIndex = 2 * paramNameIndex; + if (urlParamName != FeatherActionInvoker.TaxonNamedParamter) + { + var namedParamIndex = Array.IndexOf(urlParams, urlParamName); + if (namedParamIndex == -1 || urlParams.Length < namedParamIndex) + return null; + + currentParam = urlParams[namedParamIndex + 1]; + } + else if (urlParamName == FeatherActionInvoker.TaxonNamedParamter && urlParams.Length > (urlParamActualIndex + 1)) + { + // in this case, in the url will be presented the name of the taxonomy, ex. tag/tag1/page/2 ; category/cat1/page/2 + currentParam = urlParams[urlParamActualIndex + 1]; + var taxonomyName = urlParams[urlParamActualIndex]; + + if (taxonomyName.ToLowerInvariant() == "categories") + taxonomyName = "category"; + if (taxonomyName.ToLowerInvariant() == "tags") + taxonomyName = "tag"; + + var isResolverRegistered = ObjectFactory.IsTypeRegistered(taxonomyName.ToLowerInvariant()); + if (!isResolverRegistered) + return null; + } + else + return null; + + return currentParam; + } + + /// + /// Maps the classification URL parameter to a value from the provided URL template + /// + /// The URL parameters. + /// The URL parameter name. + /// The index of the named parameter in the URL. + /// The value of the route param from meta params. + /// + protected virtual string MapNamedRouteParam(string[] urlParams, string urlParamName, int paramNameIndex, string routeParam) + { + var urlParamActualIndex = 2 * paramNameIndex; + if (routeParam.IndexOf(":") > 0 && urlParamName == FeatherActionInvoker.TaxonNamedParamter && urlParams.Length > (urlParamActualIndex + 1)) + { + // in this case, in the url will be presented the name of the taxonomy, ex. tag/tag1/page/2 ; category/cat1/page/2 + var taxonomyName = urlParams[urlParamActualIndex]; + + if (taxonomyName.ToLowerInvariant() == "categories") + taxonomyName = "category"; + if (taxonomyName.ToLowerInvariant() == "tags") + taxonomyName = "tag"; + + var isResolverRegistered = ObjectFactory.IsTypeRegistered(taxonomyName.ToLowerInvariant()); + if (!isResolverRegistered) + return null; + + var parts = routeParam.Split(':'); + return parts[0] + ":" + taxonomyName; + } + + return routeParam; + } + /// /// Tries to resolve route parameters and map them to specific part of the url. /// @@ -92,7 +192,7 @@ protected virtual IList MapParams(MethodInfo actionMethod, strin /// The action method. /// The route parameter. /// The URL parameter. - /// The parameter map. + /// The parameter info. /// protected bool TryResolveRouteParam(MethodInfo actionMethod, string routeParam, string urlParam, IList parameterInfos) { @@ -155,8 +255,9 @@ protected bool TryResolveRouteParam(MethodInfo actionMethod, string routeParam, /// /// The URL parameters. /// The request context. + /// The URL key prefix. /// true if resolving was successful. In this case does not fallback to next mappers. Else returns false - protected abstract bool TryMatchUrl(string[] urlParams, RequestContext requestContext); + protected abstract bool TryMatchUrl(string[] urlParams, RequestContext requestContext, string urlKeyPrefix); /// /// The action name key for the RouteData values. diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/UrlSegmentInfo.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/UrlSegmentInfo.cs index c4d94bdfe..c8e1edc65 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/UrlSegmentInfo.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/UrlSegmentInfo.cs @@ -8,7 +8,7 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing /// /// This class represents information about single segment from the URL template. /// - public class UrlSegmentInfo + internal class UrlSegmentInfo { /// /// Initializes a new instance of the class. diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/ComponentsDependencyResolver.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/ComponentsDependencyResolver.cs new file mode 100644 index 000000000..9bf711db4 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/ComponentsDependencyResolver.cs @@ -0,0 +1,280 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using System.Web.Script.Serialization; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Abstractions.VirtualPath; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Utilities.HtmlParsing; + +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + /// + /// This class handles frontend components by mapping them to scripts and extracting them from markup. + /// + internal static class ComponentsDependencyResolver + { + /// + /// Gets the scripts. + /// + /// The components. + /// The scripts. + /// + public static IList GetScripts(IEnumerable components, IEnumerable scripts) + { + if (components == null) + { + components = new List(); + } + + if (scripts == null) + { + scripts = new List(); + } + + var originalScripts = scripts.ToList(); + + if (!components.Any()) + { + return originalScripts; + } + + var dependencyScripts = new List(); + + foreach (var comp in components) + { + dependencyScripts.AddRange(ComponentsDependencyResolver.GetComponentDependencies(comp, DependencyType.Scripts)); + } + + return ComponentsDependencyResolver.OrderScripts(dependencyScripts, originalScripts); + } + + /// + /// Gets the modules where components are defined. + /// + /// The components. + /// + public static IList GetModules(IEnumerable components) + { + if (components == null) + { + components = new List(); + } + + var modules = new List(); + + foreach (var comp in components) + { + modules.AddRange(ComponentsDependencyResolver.GetComponentDependencies(comp, DependencyType.Modules)); + } + + return modules; + } + + /// + /// Gets the modules by scripts. + /// + /// The scripts. + /// + public static IEnumerable GetModulesByScripts(IEnumerable scripts) + { + var modules = new List(); + foreach (var script in scripts) + { + var components = ComponentsDependencyResolver.ComponentsDefinitionsDictionary.Value + .Where(component => component.Value.Scripts != null && component.Value.Scripts.Contains(script)); + + if (components.Count() == 1 && components.Single().Value.AngularModules != null) + modules.AddRange(components.Single().Value.AngularModules); + } + + return modules.Distinct(); + } + + /// + /// Extracts the components. + /// + /// The file stream. + /// + public static IList ExtractComponents(Stream fileStream) + { + var candidateComponents = new HashSet(); + using (var reader = new StreamReader(fileStream)) + { + var readerString = reader.ReadToEnd(); + // Removing the @* Comments *@ + readerString = Regex.Replace(readerString, @"@\*([^\*@]*)\*@", string.Empty); + using (HtmlParser parser = new HtmlParser(readerString)) + { + HtmlChunk chunk = null; + parser.SetChunkHashMode(false); + parser.AutoExtractBetweenTagsOnly = false; + parser.CompressWhiteSpaceBeforeTag = false; + parser.KeepRawHTML = true; + parser.AutoKeepComments = false; + + while ((chunk = parser.ParseNext()) != null) + { + if (chunk.Type == HtmlChunkType.OpenTag) + { + //// Angular directives can be tag name (E) + var tagName = chunk.TagName.ToLower(); + + //// The parser can't handle tag names containing '-' + if (string.IsNullOrEmpty(tagName)) + { + var match = Regex.Match(chunk.Html, @"<\W*([a-zA-Z_-]+)").Groups[1]; + if (match.Success) + tagName = match.Value.ToLower(); + } + + candidateComponents.Add(tagName); + + for (int i = 0; i < chunk.Attributes.Length; i++) + { + //// The html parser has no more attributes + if (chunk.Values[i] == null) + break; + + //// Angular directives can be class attribute value (C) + if (chunk.Attributes[i].ToLower() == "class") + candidateComponents.Add(chunk.Values[i].ToLower()); + else + //// Angular directives can be attribute name (A) + candidateComponents.Add(chunk.Attributes[i].ToLower()); + } + } + } + } + } + + candidateComponents.IntersectWith(ComponentsDependencyResolver.AvailableComponents.Value.Keys); + + return candidateComponents.Select(key => ComponentsDependencyResolver.AvailableComponents.Value[key]).ToList(); + } + + /// + /// Defines dependencies for the components. + /// + public enum DependencyType + { + Scripts, + Modules + } + + private static IList OrderScripts(IList dependencyScripts, IEnumerable originalScripts) + { + var scripts = dependencyScripts.Concat(originalScripts).Distinct().ToList(); + + if (scripts.Any(x => x.Contains("sf-list-selector"))) + { + scripts.Insert(0, "client-components/selectors/common/sf-list-selector.js"); + } + + scripts.Insert(0, "client-components/selectors/common/sf-selectors.js"); + scripts.Insert(0, "client-components/selectors/common/sf-services.js"); + + if (scripts.Any(x => x.Contains("sf-fields"))) + { + scripts.Insert(0, "client-components/fields/sf-fields.js"); + } + + var mvcScripts = scripts.Where(x => x.IndexOf("Mvc/Scripts/", 0, StringComparison.Ordinal) >= 0).ToList(); + foreach (var mvcScript in mvcScripts) + { + scripts.Insert(0, mvcScript); + } + + var angularScripts = scripts.Where(x => x.IndexOf("angular", 0, StringComparison.OrdinalIgnoreCase) >= 0).ToList(); + foreach (var angularScript in angularScripts) + { + scripts.Insert(0, angularScript); + } + + return scripts.Distinct().ToList(); + } + + private static IEnumerable GetComponentDependencies(string component, DependencyType dependencyType) + { + var allDependencies = new List(); + + if (!string.IsNullOrEmpty(component) && ComponentsDependencyResolver.ComponentsDefinitionsDictionary.Value.ContainsKey(component)) + { + var componentDefinitionObject = ComponentsDependencyResolver.ComponentsDefinitionsDictionary.Value[component]; + + if (dependencyType == DependencyType.Scripts) + { + if (componentDefinitionObject.Scripts != null) + { + allDependencies.AddRange(componentDefinitionObject.Scripts); + } + } + else + { + if (componentDefinitionObject.AngularModules != null) + { + allDependencies.AddRange(componentDefinitionObject.AngularModules); + } + } + + if (componentDefinitionObject.Components != null && dependencyType == DependencyType.Scripts) + { + foreach (var comp in componentDefinitionObject.Components) + { + allDependencies.AddRange(ComponentsDependencyResolver.GetComponentDependencies(comp, dependencyType)); + } + } + } + else + { + Log.Write(string.Format(System.Globalization.CultureInfo.InvariantCulture, "The component {0} could not be resolved", component)); + } + + return allDependencies.Distinct(); + } + + private static Dictionary InitializeComponentsDefinitions() + { + var assemblyPath = FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(ComponentsDependencyResolver).Assembly); + var filename = "client-components/components-definitions.json"; + + var fileStream = VirtualPathManager.OpenFile("~/" + assemblyPath + filename); + + using (var streamReader = new StreamReader(fileStream)) + { + var text = streamReader.ReadToEnd(); + return (new JavaScriptSerializer()).Deserialize>(text); + } + } + + private static Dictionary InitializeAvailableComponents() + { + var availableComponents = new Dictionary(); + + var knownComponentsNamingMismatches = new Dictionary() + { + { "sf-expander", "expander" }, + { "sf-style-dropdown", "style-dropdown" }, + }; + + foreach (var component in ComponentsDependencyResolver.ComponentsDefinitionsDictionary.Value.Keys) + { + if (knownComponentsNamingMismatches.ContainsKey(component)) + availableComponents.Add(knownComponentsNamingMismatches[component], component); + else + availableComponents.Add(component, component); + } + + return availableComponents; + } + + private static readonly Lazy> ComponentsDefinitionsDictionary = + new Lazy>(ComponentsDependencyResolver.InitializeComponentsDefinitions, true); + + private static readonly Lazy> AvailableComponents = + new Lazy>(ComponentsDependencyResolver.InitializeAvailableComponents, true); + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/ContentDetailsViewModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/ContentDetailsViewModel.cs new file mode 100644 index 000000000..e5310e302 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/ContentDetailsViewModel.cs @@ -0,0 +1,46 @@ +using System; + +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + /// + /// View model for views that display the details of a single content item. + /// + public class ContentDetailsViewModel + { + /// + /// Gets or sets the type of content that is loaded. + /// + public Type ContentType { get; set; } + + /// + /// Gets or sets the name of the provider. + /// + /// The name of the provider. + public string ProviderName { get; set; } + + /// + /// Gets or sets the CSS class that will be applied on the wrapper div of the widget. + /// + /// + /// The CSS class. + /// + public string CssClass { get; set; } + + /// + /// Gets or sets the item. + /// + /// + /// The detail news. + /// + public ItemViewModel Item { get; set; } + + /// + /// Gets or sets a value indicating whether to enable social sharing. + /// + /// + /// true if should enable social sharing; otherwise, false. + /// + [Obsolete("Social sharing module has been removed. This property is no longer used.")] + public bool EnableSocialSharing { get; set; } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/ContentListViewModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/ContentListViewModel.cs new file mode 100644 index 000000000..15f55174b --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/ContentListViewModel.cs @@ -0,0 +1,69 @@ +using System; +using System.Collections.Generic; + +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + /// + /// View model for views that display a list of content items. + /// + public class ContentListViewModel + { + /// + /// Gets or sets the name of the provider. + /// + /// The name of the provider. + public string ProviderName { get; set; } + + /// + /// Gets or sets the type of content that is loaded. + /// + public Type ContentType { get; set; } + + /// + /// Gets or sets the CSS class that will be applied on the wrapping element of the widget. + /// + /// + /// The CSS class. + /// + public string CssClass { get; set; } + + /// + /// Gets or sets the URL key prefix. + /// + /// The URL key prefix. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] + public virtual string UrlKeyPrefix { get; set; } + + /// + /// Gets an enumerable of the items that should be displayed. + /// + /// + /// The items. + /// + public IEnumerable Items { get; set; } + + /// + /// Gets or sets the total pages count. + /// + /// + /// The total pages count. + /// + public int? TotalPagesCount { get; set; } + + /// + /// Gets or sets the current page. + /// + /// + /// The current page. + /// + public int CurrentPage { get; set; } + + /// + /// Gets or sets a value indicating whether to show pager. + /// + /// + /// true to show pager; otherwise, false. + /// + public bool ShowPager { get; set; } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/ContentModelBase.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/ContentModelBase.cs new file mode 100644 index 000000000..03f4b8b42 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/ContentModelBase.cs @@ -0,0 +1,959 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Web.Mvc; +using ServiceStack.Text; +using Telerik.Sitefinity.ContentLocations; +using Telerik.Sitefinity.Data; +using Telerik.Sitefinity.Data.Linq.Dynamic; +using Telerik.Sitefinity.DynamicModules.Model; +using Telerik.Sitefinity.GenericContent.Model; +using Telerik.Sitefinity.Lifecycle; +using Telerik.Sitefinity.Model; +using Telerik.Sitefinity.Modules; +using Telerik.Sitefinity.RelatedData; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Taxonomies; +using Telerik.Sitefinity.Taxonomies.Model; +using Telerik.Sitefinity.Web.Model; +using Telerik.Sitefinity.Web.UI.ContentUI.Enums; + +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + /// + /// A base class of models that contain logic for querying content. + /// + public abstract class ContentModelBase : IContentLocatableView + { + #region Properties + + /// + /// Gets or sets the type of content that is loaded. + /// + public virtual Type ContentType { get; set; } + + /// + /// Gets or sets the CSS class that will be applied on the wrapping element of the widget when it is in List view. + /// + /// + /// The CSS class. + /// + public virtual string ListCssClass { get; set; } + + /// + /// Gets or sets the CSS class that will be applied on the wrapper div of the widget when it is in Details view. + /// + /// + /// The CSS class. + /// + public virtual string DetailCssClass { get; set; } + + /// + /// Gets the list of items to be displayed inside the widget when option "Selected items" is enabled. + /// + /// + /// The selected item ids. + /// + public virtual string SerializedSelectedItemsIds + { + get + { + return this.serializedSelectedItemsIds; + } + + set + { + if (this.serializedSelectedItemsIds != value) + { + this.serializedSelectedItemsIds = value; + if (!this.serializedSelectedItemsIds.IsNullOrEmpty()) + { + this.selectedItemsIds = JsonSerializer.DeserializeFromString>(this.serializedSelectedItemsIds); + } + } + } + } + + /// + /// Gets or sets a value indicating whether to enable social sharing. + /// + /// + /// true if should enable social sharing; otherwise, false. + /// + [Obsolete("Social sharing module has been removed. This property is no longer used.")] + public virtual bool EnableSocialSharing { get; set; } + + /// + /// Gets or sets the name of the provider. + /// + /// The name of the provider. + public virtual string ProviderName { get; set; } + + /// + /// Gets or sets which items to be displayed in the list view. + /// + /// The page display mode. + public virtual SelectionMode SelectionMode { get; set; } + + /// + /// Gets or sets a value indicating whether to divide items in the list. + /// + /// + /// The display mode. + /// + public virtual ListDisplayMode DisplayMode { get; set; } + + /// + /// Gets or sets the items count per page. + /// + /// + /// The items per page. + /// + public virtual int? ItemsPerPage + { + get + { + return this.itemsPerPage; + } + + set + { + this.itemsPerPage = value; + } + } + + /// + /// Gets or sets the items limit count. + /// + /// + /// The items limit. + /// + public virtual int? LimitCount + { + get + { + return this.limitCount; + } + + set + { + this.limitCount = value; + } + } + + /// + /// Gets or sets the sort expression. + /// + /// + /// The sort expression. + /// + public virtual string SortExpression + { + get + { + return this.sortExpression; + } + + set + { + this.sortExpression = value; + } + } + + /// + /// Gets or sets the additional filter expression. + /// + /// + /// The filter expression. + /// + public virtual string FilterExpression { get; set; } + + /// + /// Gets or sets the serialized additional filters. + /// + /// + /// The serialized additional filters. + /// + public virtual string SerializedAdditionalFilters { get; set; } + + /// + /// Gets or sets the serialized date filters. + /// + /// + /// The serialized date filters. + /// + public virtual string SerializedDateFilters { get; set; } + + /// + /// Gets or sets the group logical operator used for filtering. + /// + /// + /// The group logical operator used for filtering. + /// + public virtual LogicalOperator SelectionGroupLogicalOperator { get; set; } + + /// + /// Gets or sets a value indicating whether the canonical URL tag should be added to the page when the canonical meta tag should be added to the page. + /// If the value is not set, the settings from SystemConfig -> ContentLocationsSettings -> DisableCanonicalURLs will be used. + /// + /// The disable canonical URLs. + public virtual bool? DisableCanonicalUrlMetaTag { get; set; } + + /// + /// Gets or sets the type of the parent item. + /// + /// + /// The type of the parent item. + /// + public virtual string RelatedItemType { get; set; } + + /// + /// Gets or sets the name of the parent item provider. + /// + /// + /// The name of the parent item provider. + /// + public virtual string RelatedItemProviderName { get; set; } + + /// + /// Gets or sets the name of the field. + /// + /// + /// The name of the field. + /// + public virtual string RelatedFieldName { get; set; } + + /// + /// Gets or sets the relation type of the items that will be display - children or parent. + /// + /// + /// The relation type of the items that will be display - children or parent. + /// + public virtual RelationDirection RelationTypeToDisplay { get; set; } + + /// + /// Gets or sets the URL key prefix. + /// + /// The URL key prefix. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] + public virtual string UrlKeyPrefix { get; set; } + + /// + /// Gets or sets the display mode of the content view. + /// + /// + /// Note that this enumeration differs from the FieldDisplayMode. + /// + public virtual ContentViewDisplayMode ContentViewDisplayMode { get; set; } + + /// + /// Gets or sets a value indicating if the logical operator should be updated. + /// + /// + /// true if logical operator should be updated; otherwise, false. + /// + protected virtual bool RefreshLogicalOperator + { + get + { + return this.refreshLogicalOperator; + } + + set + { + this.refreshLogicalOperator = value; + } + } + #endregion + + #region Public methods + + /// + /// Gets the information for all of the content types that a control is able to show. + /// + public virtual IEnumerable GetLocations() + { + var location = new ContentLocationInfo(); + location.ContentType = this.ContentType; + location.ProviderName = this.GetManager().Provider.Name; + + switch (this.ContentViewDisplayMode) + { + case ContentViewDisplayMode.Detail: + location.Filters.Add(this.CompileSingleItemFilterExpression(location.ContentType)); ; + + return new[] { location }; + case ContentViewDisplayMode.Automatic: + if (this.SelectionMode == SelectionMode.SelectedItems && string.IsNullOrEmpty(this.FilterExpression)) + { + var masterAndLiveIdsList = this.GetMasterAndLiveIdsFromSelection(); + location.Filters.Add(new ItemsSelectionLocationFilter(masterAndLiveIdsList.Select(x => x.ToString()))); + } + else + { + var filterExpression = this.CompileFilterExpression(); + if (!string.IsNullOrEmpty(filterExpression)) + { + location.Filters.Add(new BasicContentLocationFilter(filterExpression)); + } + } + break; + default: + return null; + } + + return new[] { location }; + } + + /// + /// Creates a view model for use in list views. + /// + /// The taxon filter. + /// The page. + /// A view model for use in list views. + /// 'page' argument has to be at least 1.;page + public virtual ContentListViewModel CreateListViewModel(ITaxon taxonFilter, int page) + { + if (page < 1) + throw new ArgumentException("'page' argument has to be at least 1.", "page"); + + var viewModel = this.CreateListViewModelInstance(); + viewModel.UrlKeyPrefix = this.UrlKeyPrefix; + var query = this.GetItemsQuery(); + if (query == null) + return viewModel; + + if (taxonFilter != null) + { + var taxonomy = taxonFilter.Taxonomy.RootTaxonomy ?? taxonFilter.Taxonomy; + + string taxonomyField; + + if (this.TryGetTaxonomyFieldName(taxonomy.Id, out taxonomyField)) + { + var filter = string.Format(CultureInfo.InvariantCulture, "{0}.Contains({{{1}}})", taxonomyField, taxonFilter.Id); + query = query.Where(filter); + } + } + + this.PopulateListViewModel(page, query, viewModel); + + return viewModel; + } + + /// + /// Creates a view model for use in list views filtered by related item. + /// + /// Item that is related to the resulting items + /// The page. + /// A view model for use in list views. + /// 'page' argument has to be at least 1.;page + public virtual ContentListViewModel CreateListViewModelByRelatedItem(IDataItem relatedItem, int page) + { + if (page < 1) + throw new ArgumentException("'page' argument has to be at least 1.", "page"); + + if (relatedItem == null) + throw new ArgumentNullException("relatedItem"); + + int? totalCount = 0; + var query = this.GetRelatedItems(relatedItem, page, ref totalCount); + + var viewModel = this.CreateListViewModelInstance(); + + viewModel.Items = query.ToArray().Select(item => this.CreateItemViewModelInstance(item)).ToArray(); + + if (this.ItemsPerPage != 0) + viewModel.TotalPagesCount = (totalCount + this.ItemsPerPage - 1) / this.ItemsPerPage; + + viewModel.CurrentPage = page; + viewModel.ProviderName = this.ProviderName; + viewModel.ContentType = this.ContentType; + viewModel.CssClass = this.ListCssClass; + viewModel.ShowPager = this.DisplayMode == ListDisplayMode.Paging && viewModel.TotalPagesCount.HasValue && viewModel.TotalPagesCount > 1; + + return viewModel; + } + + /// + /// Creates the ListView model by date filter. + /// + /// The start date from the date filter. + /// The end date from the date filter. + /// The page. + /// A list view model containing all descendant items from the given parent. + public virtual ContentListViewModel CreateListViewModelByDate(DateTime from, DateTime to, int page) + { + if (page < 1) + { + throw new ArgumentException("'page' argument has to be at least 1.", "page"); + } + + var viewModel = this.CreateListViewModelInstance(); + + var query = this.GetItemsQuery(); + if (query == null) + { + return viewModel; + } + + query = query.Where("(PublicationDate >= @0 && PublicationDate <= @1)", from, to); + + this.PopulateListViewModel(page, query, viewModel); + + return viewModel; + } + + /// + /// Creates the details view model. + /// + /// The item. + /// A view model for use in detail views. + public virtual ContentDetailsViewModel CreateDetailsViewModel(IDataItem item) + { + var viewModel = this.CreateDetailsViewModelInstance(); + + viewModel.CssClass = this.DetailCssClass; + viewModel.Item = this.CreateItemViewModelInstance(item); + viewModel.ContentType = this.ContentType; + viewModel.ProviderName = this.ProviderName; + + return viewModel; + } + + /// + /// Gets a collection of . + /// The represents a key for which cached items could be subscribed for + /// notification. + /// When notified, all cached objects with dependency on the provided keys will expire. + /// + /// View model that will be used for displaying the data. + /// + /// The . + /// + public virtual IList GetKeysOfDependentObjects(ContentListViewModel viewModel) + { + if (this.ContentType != null) + { + var contentResolvedType = this.ContentType; + var result = new List(1); + var manager = this.GetManager(); + var provider = manager != null ? manager.Provider : null; + string applicationName = provider != null ? provider.ApplicationName : string.Empty; + + result.AddRange(OutputCacheDependencyHelper.GetPublishedContentCacheDependencyKeys(contentResolvedType, applicationName)); + + this.AddCommonDependencies(result, this.ContentType); + + return result; + } + else + { + return new List(0); + } + } + + /// + /// Gets a collection of . + /// The represents a key for which cached items could be subscribed for + /// notification. + /// When notified, all cached objects with dependency on the provided keys will expire. + /// + /// View model that will be used for displaying the data. + /// + /// The . + /// + public virtual IList GetKeysOfDependentObjects(ContentDetailsViewModel viewModel) + { + if (this.ContentType != null) + { + var contentResolvedType = this.ContentType; + var result = new List(1); + if (viewModel.Item != null && viewModel.Item.Fields.Id != Guid.Empty) + { + result.AddRange(OutputCacheDependencyHelper.GetPublishedContentCacheDependencyKeys(contentResolvedType, viewModel.Item.Fields.Id)); + } + + this.AddCommonDependencies(result, this.ContentType, viewModel.Item); + + return result; + } + else + { + return new List(0); + } + } + + #endregion + + #region Protected methods + + /// + /// Gets an active query for all items. + /// + /// The query. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] + protected abstract IQueryable GetItemsQuery(); + + /// + /// Applies the list settings. + /// + /// The page. + /// The items query. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#")] + protected virtual IEnumerable ApplyListSettings(int page, IQueryable query, out int? totalPages) + { + if (page < 1) + throw new ArgumentException("'page' argument has to be at least 1.", "page"); + + int? itemsToSkip = (page - 1) * this.ItemsPerPage; + itemsToSkip = this.DisplayMode == ListDisplayMode.Paging && this.ContentViewDisplayMode != ContentViewDisplayMode.Detail ? ((page - 1) * this.ItemsPerPage) : null; + int? totalCount = 0; + int? take = null; + + if (this.DisplayMode == ListDisplayMode.Limit) + { + take = this.LimitCount; + } + else if (this.DisplayMode == ListDisplayMode.Paging) + { + take = this.ItemsPerPage; + } + + IList result = new List(); + + query = this.UpdateExpression(query, itemsToSkip, take, ref totalCount); + + var queryResult = this.FetchItems(query); + queryResult.SetRelatedDataSourceContext(); + + TaxonomyApplicationState.SetTaxonomyDataSourceContext(queryResult); + + foreach (var item in queryResult) + { + result.Add(this.CreateItemViewModelInstance(item)); + } + + if (this.itemsPerPage.HasValue && this.itemsPerPage.Value > 0) + { + totalPages = (totalCount.Value + this.itemsPerPage.Value - 1) / this.ItemsPerPage.Value; + totalPages = this.DisplayMode == ListDisplayMode.Paging ? totalPages : null; + } + else + { + totalPages = 1; + } + + return result; + } + + /// + /// Fetches the items from a queryable. + /// + /// The queryable. + /// Fetched items. + protected virtual IEnumerable FetchItems(IQueryable query) + { + var queryResult = query.ToArray(); + return queryResult; + } + + /// + /// Creates a blank instance of a list view model. + /// + /// The list view model. + protected virtual ContentListViewModel CreateListViewModelInstance() + { + return new ContentListViewModel(); + } + + /// + /// Creates a blank instance of a details view model. + /// + /// The details view model. + protected virtual ContentDetailsViewModel CreateDetailsViewModelInstance() + { + return new ContentDetailsViewModel(); + } + + /// + /// Creates an instance of the item view model by given data item. + /// + /// The item. + /// + protected virtual ItemViewModel CreateItemViewModelInstance(IDataItem item) + { + return new ItemViewModel(item); + } + + /// + /// Generates single item filter for specified content location + /// + /// The single item filter. + protected virtual ContentLocationSingleItemFilter CompileSingleItemFilterExpression(Type itemType) + { + if (!typeof(Content).IsAssignableFrom(itemType) && !typeof(DynamicContent).IsAssignableFrom(itemType)) + { + throw new ArgumentException("The type must be Content or Dynamic content"); + } + + var selectedItemGuid = this.selectedItemsIds.Select(id => new Guid(id)).SingleOrDefault(); + return ContentLocatableViewExtensions.GetSingleItemFilter(selectedItemGuid, itemType, this.GetManager()); + } + + /// + /// Compiles a filter expression based on the widget settings. + /// + /// Filter expression that will be applied on the query. + protected virtual string CompileFilterExpression() + { + var elements = new List(); + + if (this.SelectionMode == SelectionMode.FilteredItems) + { + if (!this.SerializedAdditionalFilters.IsNullOrEmpty()) + { + var additionalFilters = JsonSerializer.DeserializeFromString(this.SerializedAdditionalFilters); + if (additionalFilters.QueryItems != null && additionalFilters.QueryItems.Length > 0) + { + if (this.RefreshLogicalOperator) + { + this.RefreshQueryGroupLogicalOperator(additionalFilters.GetZeroLevelItems()); + } + + var queryExpression = Telerik.Sitefinity.Data.QueryBuilder.LinqTranslator.ToDynamicLinq(additionalFilters); + elements.Add(queryExpression); + } + } + } + else if (this.SelectionMode == SelectionMode.SelectedItems) + { + var selectedItemsFilterExpression = this.GetSelectedItemsFilterExpression(); + if (!selectedItemsFilterExpression.IsNullOrEmpty()) + { + elements.Add(selectedItemsFilterExpression); + } + } + + if (!this.FilterExpression.IsNullOrEmpty()) + { + elements.Add(this.FilterExpression); + } + + return string.Join(" AND ", elements.Select(el => "(" + el + ")")); + } + + /// + /// Populates the list ViewModel. + /// + /// The current page. + /// The query. + /// The view model. + protected virtual void PopulateListViewModel(int page, IQueryable query, ContentListViewModel viewModel) + { + int? totalPages = null; + if (this.SelectionMode == Models.SelectionMode.SelectedItems && (this.selectedItemsIds.Count == 0 || string.IsNullOrEmpty(this.GetSelectedItemsFilterExpression()))) + { + viewModel.Items = Enumerable.Empty(); + } + else + { + viewModel.Items = this.ApplyListSettings(page, query, out totalPages); + } + + this.SetViewModelProperties(viewModel, page, totalPages); + } + + /// + /// Sets the view model properties. + /// + /// The view model. + /// The page. + /// The total pages. + protected virtual void SetViewModelProperties(ContentListViewModel viewModel, int page, int? totalPages) + { + viewModel.CurrentPage = page; + viewModel.TotalPagesCount = totalPages; + viewModel.ProviderName = this.ProviderName; + viewModel.ContentType = this.ContentType; + viewModel.CssClass = this.ListCssClass; + viewModel.ShowPager = this.DisplayMode == ListDisplayMode.Paging && totalPages.HasValue && totalPages > 1; + } + + /// + /// Gets a manager instance for the model. + /// + /// The manager. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ContentType")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] + protected virtual IManager GetManager() + { + if (this.ContentType == null) + throw new InvalidOperationException("Cannot resolve manager because ContentType is not set."); + + return ManagerBase.GetMappedManager(this.ContentType, this.ProviderName); + } + + /// + /// Updates the expression. + /// + /// The query. + /// The skip. + /// The take. + /// The total count. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "3#")] + protected virtual IQueryable UpdateExpression(IQueryable query, int? skip, int? take, ref int? totalCount) + { + var compiledFilterExpression = this.CompileFilterExpression(); + compiledFilterExpression = this.AddLiveFilterExpression(compiledFilterExpression); + compiledFilterExpression = this.AdaptMultilingualFilterExpression(compiledFilterExpression); + + query = this.SetExpression( + query, + compiledFilterExpression, + this.SortExpression, + skip, + take, + ref totalCount); + + return query; + } + + /// + /// Appends the lifecycle conditions to the filter expression in order to get only live items. + /// + /// The filter expression. + /// Filter expression for live items. + protected virtual string AddLiveFilterExpression(string filterExpression) + { + if (filterExpression.IsNullOrEmpty()) + { + filterExpression = "Visible = true AND Status = Live"; + } + else + { + filterExpression = filterExpression + " AND Visible = true AND Status = Live"; + } + + return filterExpression; + } + + /// + /// Adapts a filter expression in multilingual. + /// + /// The filter expression. + /// Multilingual filter expression. + protected virtual string AdaptMultilingualFilterExpression(string filterExpression) + { + CultureInfo uiCulture; + if (SystemManager.CurrentContext.AppSettings.Multilingual) + { + uiCulture = Telerik.Sitefinity.Services.SystemManager.CurrentContext.Culture; + } + else + { + uiCulture = null; + } + + // the filter is adapted to the implementation of ILifecycleDataItemGeneric, so the culture is taken in advance when filtering published items. + return ContentHelper.AdaptMultilingualFilterExpressionRaw(filterExpression, uiCulture); + } + + /// + /// Modifies the given query with the given filter, sort expression and paging. + /// + /// The query. + /// The filter expression. + /// The sort expression. + /// The items to skip. + /// The items to take. + /// The total count. + /// Resulting filtered query. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Expr"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "5#")] + protected virtual IQueryable SetExpression(IQueryable query, string filterExpression, string sortExpr, int? itemsToSkip, int? itemsToTake, ref int? totalCount) + where TItem : IDataItem + { + if (sortExpr == "AsSetManually") + { + query = DataProviderBase.SetExpressions( + query, + filterExpression, + string.Empty, + null, + null, + ref totalCount); + + query = query.OfType() + .Select(x => new + { + item = x, + orderIndex = this.selectedItemsIds.IndexOf(x.OriginalContentId.ToString()) >= 0 ? + this.selectedItemsIds.IndexOf(x.OriginalContentId.ToString()) : + this.selectedItemsIds.IndexOf(x.Id.ToString()) + }) + .OrderBy(x => x.orderIndex) + .Select(x => x.item) + .OfType(); + + if (itemsToSkip.HasValue && itemsToSkip.Value > 0) + { + query = query.Skip(itemsToSkip.Value); + } + + if (itemsToTake.HasValue && itemsToTake.Value > 0) + { + query = query.Take(itemsToTake.Value); + } + } + else + { + try + { + query = DataProviderBase.SetExpressions( + query, + filterExpression, + sortExpr, + itemsToSkip, + itemsToTake, + ref totalCount); + } + catch (MemberAccessException) + { + this.SortExpression = DefaultSortExpression; + query = DataProviderBase.SetExpressions( + query, + filterExpression, + this.SortExpression, + itemsToSkip, + itemsToTake, + ref totalCount); + } + } + + return query; + } + + /// + /// Refreshes query with the group logical operator. + /// + /// The query items. + protected void RefreshQueryGroupLogicalOperator(IEnumerable queryItems) + { + foreach (var item in queryItems) + { + if (item.Join == this.SelectionGroupLogicalOperator.ToString()) + break; + + item.Join = this.SelectionGroupLogicalOperator.ToString(); + } + } + #endregion + + #region Private methods + + /// + /// Tries to get the name of the taxonomy field. + /// + /// The taxonomy id. + /// The taxonomy field. + /// + private bool TryGetTaxonomyFieldName(Guid taxonomyId, out string taxonomyField) + { + taxonomyField = string.Empty; + + var taxonomyPropertyDescriptor = FieldHelper.GetFields(this.ContentType) + .OfType() + .FirstOrDefault(t => t.TaxonomyId == taxonomyId); + + if (taxonomyPropertyDescriptor != null) + { + taxonomyField = taxonomyPropertyDescriptor.Name; + } + + return taxonomyPropertyDescriptor != null; + } + + /// + /// Gets the selected items filter expression + /// + /// The selected items filter expression. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Telerik.Sitefinity", "SF1002:AvoidToListOnIEnumerable")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "It would add too much risk now to change this to property and would not bring much value to code quality and maintenance.")] + protected virtual string GetSelectedItemsFilterExpression() + { + var masterAndLiveIds = this.GetMasterAndLiveIdsFromSelection(); + + var selectedItemConditions = masterAndLiveIds.Select(id => "Id = {0} OR OriginalContentId = {0}".Arrange(id.ToString("D"))); + var selectedItemsFilterExpression = string.Join(" OR ", selectedItemConditions); + + return selectedItemsFilterExpression; + } + + /// + /// Adds common dependencies to the list. + /// + /// + /// + /// + protected virtual void AddCommonDependencies(IList keys, Type contentType, ItemViewModel item = null) + { + if (contentType.ImplementsInterface(typeof(ICommentable))) + keys.Add(new CacheDependencyKey() { Type = typeof(Sitefinity.Services.Comments.IThread) }); + } + + private IEnumerable GetMasterAndLiveIdsFromSelection() + { + var selectedItemGuids = this.selectedItemsIds.Select(id => new Guid(id)); + + var masterIds = this.GetItemsQuery() + .OfType() + .Where(c => selectedItemGuids.Contains(c.Id) || selectedItemGuids.Contains(c.OriginalContentId)) + .Select(n => n.OriginalContentId != Guid.Empty ? n.OriginalContentId : n.Id); + + var liveIds = this.GetItemsQuery() + .OfType() + .Where(c => (selectedItemGuids.Contains(c.Id) || selectedItemGuids.Contains(c.OriginalContentId)) && c.Status == ContentLifecycleStatus.Live) + .Select(n => n.Id); + + var result = new HashSet(masterIds.Union(liveIds)); + + return result; + } + + private IQueryable GetRelatedItems(IDataItem relatedItem, int page, ref int? totalCount) + { + var manager = this.GetManager(); + var relatedDataSource = manager.Provider as IRelatedDataSource; + + if (relatedDataSource == null) + return Enumerable.Empty().AsQueryable(); + + //// Тhe filter is adapted to the implementation of ILifecycleDataItemGeneric, so the culture is taken in advance when filtering published items. + var filterExpression = ContentHelper.AdaptMultilingualFilterExpression(this.FilterExpression); + int? skip = (page - 1) * this.ItemsPerPage; + + var relatedItems = relatedDataSource.GetRelatedItems(this.RelatedItemType, this.RelatedItemProviderName, relatedItem.Id, this.RelatedFieldName, this.ContentType, ContentLifecycleStatus.Live, filterExpression, this.SortExpression, skip, this.ItemsPerPage, ref totalCount, this.RelationTypeToDisplay) + .OfType(); + + return relatedItems; + } + + #endregion + + #region Private fields and constants + + private const string DefaultSortExpression = "PublicationDate DESC"; + + private int? itemsPerPage = 20; + private int? limitCount = 20; + private bool refreshLogicalOperator = true; + private string sortExpression = DefaultSortExpression; + private string serializedSelectedItemsIds; + private IList selectedItemsIds = new List(); + + #endregion + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerModel.cs index 9d9d1e112..2e389e23f 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerModel.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerModel.cs @@ -1,20 +1,24 @@ using System; using System.Collections.Generic; -using System.Diagnostics.Contracts; using System.IO; using System.Linq; using System.Web.Script.Serialization; +using System.Web.UI; using Telerik.Sitefinity.Abstractions.VirtualPath; using Telerik.Sitefinity.Frontend.Mvc.Controllers; using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; using Telerik.Sitefinity.Frontend.Resources; - +using Telerik.Sitefinity.Modules; +using Telerik.Sitefinity.Modules.Forms; +using Telerik.Sitefinity.Modules.Pages; +using Telerik.Sitefinity.Pages.Model; + namespace Telerik.Sitefinity.Frontend.Mvc.Models { /// /// This class is used as a model for the designer controller. /// - public class DesignerModel : IDesignerModel + internal class DesignerModel : IDesignerModel { /// /// Initializes a new instance of the class. @@ -22,32 +26,54 @@ public class DesignerModel : IDesignerModel /// The views that are available to the controller. /// The locations where view files can be found. /// Name of the widget that is being edited. + /// Id of the control that is edited. /// Name of the preselected view if there is one. Otherwise use null. - public DesignerModel(IEnumerable views, IEnumerable viewLocations, string widgetName, string preselectedView) + /// Map of the view file location for each view. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] + public DesignerModel(IEnumerable views, IEnumerable viewLocations, string widgetName, Guid controlId, string preselectedView, Dictionary viewFilesMappings) + : this(views, viewLocations, widgetName, controlId, preselectedView, viewFilesMappings, DesignMediaType.Page) { - if (preselectedView.IsNullOrEmpty()) - { - this.views = views.Where(this.IsDesignerView).Select(this.ExtractViewName); - } - else - { - this.views = new[] { preselectedView }; - } - - var viewConfigs = this.views - .Select(v => new KeyValuePair(v, this.GetViewConfig(v, viewLocations))) - .Where(c => c.Value != null); - - if (preselectedView.IsNullOrEmpty()) - { - this.views = this.views.Where(v => !viewConfigs.Any(vc => vc.Key == v) || viewConfigs.Single(vc => vc.Key == v).Value.Hidden == false).ToList(); - viewConfigs = viewConfigs.Where(c => !c.Value.Hidden); - } + + } - this.PopulateScriptReferences(widgetName, viewConfigs); + /// + /// Initializes a new instance of the class. + /// + /// The views that are available to the controller. + /// The locations where view files can be found. + /// Name of the widget that is being edited. + /// Id of the control that is edited. + /// Name of the preselected view if there is one. Otherwise use null. + /// Map of the view file location for each view. + /// The type of the design media. + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] + public DesignerModel(IEnumerable views, IEnumerable viewLocations, string widgetName, Guid controlId, string preselectedView, Dictionary viewFilesMappings, DesignMediaType mediaType) + { + this.Caption = widgetName; + + var formatedViewsDictionary = this.GetViews(views, preselectedView); + var viewConfigs = this.GetViewConfigs(formatedViewsDictionary, viewLocations, viewFilesMappings); + + if (string.IsNullOrEmpty(preselectedView)) + { + this.views = formatedViewsDictionary.Values.Where(v => !viewConfigs.Any(vc => vc.Key == v) || viewConfigs.Single(vc => vc.Key == v).Value.Hidden == false).ToArray(); + viewConfigs = viewConfigs.Where(c => !c.Value.Hidden).ToList(); + } + else + { + this.views = formatedViewsDictionary.Values; + } + + // If no configs have set priority and at least one config is generated - set its priority to 1. + if (!viewConfigs.Any(c => c.Value.Priority != 0) && viewConfigs.Any(c => c.Value.IsGenerated)) + viewConfigs.FirstOrDefault(c => c.Value.IsGenerated).Value.Priority = 1; + + this.PopulateDependencies(widgetName, viewConfigs); this.defaultView = viewConfigs.OrderByDescending(c => c.Value.Priority).Select(c => c.Key).FirstOrDefault(); - } + + this.Control = this.LoadControl(controlId, mediaType); + } /// public virtual IEnumerable Views @@ -65,6 +91,20 @@ public virtual IEnumerable ScriptReferences { return this.scriptReferences; } + } + + /// + public virtual IEnumerable ModuleDependencies + { + get + { + return this.moduleDependencies; + } + + private set + { + this.moduleDependencies = value; + } } /// @@ -76,11 +116,17 @@ public virtual string DefaultView } } + /// + public Control Control { get; set; } + + /// + public string Caption { get; set; } + /// /// Determines whether the given file represents a designer view. /// /// The filename. - protected virtual bool IsDesignerView(string filename) + protected bool IsDesignerView(string filename) { return filename != null && filename.StartsWith(DesignerModel.DesignerViewPrefix, StringComparison.Ordinal); } @@ -89,16 +135,20 @@ protected virtual bool IsDesignerView(string filename) /// Extracts the name of the view. /// /// The filename. - protected virtual string ExtractViewName(string filename) + protected string ExtractViewName(string filename) { if (filename == null) throw new ArgumentNullException("filename"); - var parts = filename.Split('.'); + var parts = filename.Split('.'); + if (filename.EndsWith(".cshtml", StringComparison.Ordinal)) + { + parts = parts.Take(parts.Length - 1).ToArray(); + } if (parts.Length > 2) { - return string.Join(".", parts.Skip(1).Take(parts.Length - 2)); + return string.Join(".", parts.Skip(1).Take(parts.Length - 1)); } if (parts.Length == 2) @@ -110,33 +160,41 @@ protected virtual string ExtractViewName(string filename) } /// - /// Populates the script references. + /// Populates the script references and dependent modules. /// /// Name of the widget. /// The view configs. - protected virtual void PopulateScriptReferences(string widgetName, IEnumerable> viewConfigs) + protected void PopulateDependencies(string widgetName, IEnumerable> viewConfigs) { var packagesManager = new PackageManager(); var packageName = packagesManager.GetCurrentPackage(); var designerWidgetName = FrontendManager.ControllerFactory.GetControllerName(typeof(DesignerController)); - var viewScriptReferences = new List(this.Views.Count()); - - foreach (var view in this.Views) - { - var scriptFileName = this.GetViewScriptFileName(view); - var scriptPath = this.GetScriptPath(scriptFileName, widgetName, packageName); - if (VirtualPathManager.FileExists(scriptPath)) - { - viewScriptReferences.Add(this.GetScriptReferencePath(widgetName, scriptFileName)); - } - else - { - scriptPath = this.GetScriptPath(scriptFileName, designerWidgetName, packageName); - if (VirtualPathManager.FileExists(scriptPath)) - viewScriptReferences.Add(this.GetScriptReferencePath(designerWidgetName, scriptFileName)); - } + var viewScriptReferences = new List(this.views.Count()); + + foreach (var view in this.views) + { + var scriptFileName = this.GetViewScriptFileName(view); + var scriptPath = this.GetScriptPath(scriptFileName, widgetName, packageName); + if (VirtualPathManager.FileExists(scriptPath)) + { + viewScriptReferences.Add(this.GetScriptReferencePath(widgetName, scriptFileName)); + } + else + { + scriptPath = this.GetScriptPath(scriptFileName, designerWidgetName, packageName); + + if (VirtualPathManager.FileExists(scriptPath)) + { + viewScriptReferences.Add(this.GetScriptReferencePath(designerWidgetName, scriptFileName)); + } + else + { + var viewConfig = viewConfigs.Where(v => v.Key == view).SingleOrDefault(); + this.ModuleDependencies = this.ModuleDependencies.Concat(ComponentsDependencyResolver.GetModules(viewConfig.Value.Components)).Distinct(); + } + } } var configuredScriptReferences = viewConfigs @@ -146,14 +204,14 @@ protected virtual void PopulateScriptReferences(string widgetName, IEnumerable /// Gets the name of the script file for a given view. /// /// The view. /// File name of the client script file for a given view. - protected virtual string GetViewScriptFileName(string view) + protected string GetViewScriptFileName(string view) { if (string.IsNullOrEmpty(view)) throw new ArgumentNullException("view"); @@ -167,7 +225,7 @@ protected virtual string GetViewScriptFileName(string view) /// The view. /// Locations where view files can be found. /// Config for the given view if such config exists. - protected virtual DesignerViewConfigModel GetViewConfig(string view, IEnumerable viewLocations) + protected DesignerViewConfigModel GetViewConfig(string view, IEnumerable viewLocations) { if (view == null) throw new ArgumentNullException("view"); @@ -185,13 +243,130 @@ protected virtual DesignerViewConfigModel GetViewConfig(string view, IEnumerable using (var streamReader = new StreamReader(fileStream)) { - var text = streamReader.ReadToEnd(); - return new JavaScriptSerializer().Deserialize(text); + var text = streamReader.ReadToEnd(); + var designerViewConfigModel = new JavaScriptSerializer().Deserialize(text); + + this.PopulateModulesForScripts(designerViewConfigModel.Scripts); + this.PopulateComponentsScriptReferences(designerViewConfigModel); + + return designerViewConfigModel; } } } return null; + } + + /// + /// Generates the view configuration if its missing from the file system. + /// + /// The view. + /// Locations where view files can be found. + /// Map of the view file location for each view. + /// Config for the given view. + protected DesignerViewConfigModel GenerateViewConfig(string view, IEnumerable viewLocations, Dictionary viewFilesMappings) + { + var viewFilePath = this.GetViewFilePath(view, viewLocations, viewFilesMappings); + if (!string.IsNullOrEmpty(viewFilePath)) + { + using (var fileStream = VirtualPathManager.OpenFile(viewFilePath)) + { + var components = ComponentsDependencyResolver.ExtractComponents(fileStream); + var scripts = ComponentsDependencyResolver.GetScripts(components, null); + + // If view that exists has been parsed and no components are used in it - no point in cycling trough the other views + return new DesignerViewConfigModel() { Scripts = scripts, Components = components, IsGenerated = true }; + } + } + + return null; + } + + private string GetViewFilePath(string view, IEnumerable viewLocations, Dictionary viewFilesMappings) + { + // If view file mapping exists return it + if (viewFilesMappings != null && viewFilesMappings.ContainsKey(view)) + return viewFilesMappings[view]; + + // Search all locations for the view + IEnumerable viewExtensions = new string[] { "aspx", "ascx", "master", "cshtml", "vbhtml" }; + foreach (var viewLocation in viewLocations) + { + foreach (var viewExtension in viewExtensions) + { + var expectedViewFileName = string.Format("{0}{1}{2}.{3}", viewLocation, DesignerViewPrefix, view, viewExtension); + if (VirtualPathManager.FileExists(expectedViewFileName)) + { + return expectedViewFileName; + } + } + } + + return null; + } + + private IDictionary GetViews(IEnumerable rawViewNames, string preselectedView) + { + if (string.IsNullOrEmpty(preselectedView)) + return rawViewNames.Where(this.IsDesignerView).ToDictionary(v => v, this.ExtractViewName); + else + return new Dictionary() { { preselectedView, preselectedView } }; + } + + private IList> GetViewConfigs(IDictionary formatedViewsDictionary, IEnumerable viewLocations, Dictionary viewFilesMappings) + { + var designerViewFilesMappings = new Dictionary(); + if (viewFilesMappings != null) + { + foreach (var kv in formatedViewsDictionary) + { + if (viewFilesMappings.ContainsKey(kv.Key)) + designerViewFilesMappings[kv.Value] = viewFilesMappings[kv.Key]; + } + } + + var viewConfigs = new List>(); + + foreach (var kv in formatedViewsDictionary) + { + var config = this.GetViewConfig(kv.Value, viewLocations); + if (config == null) + config = this.GenerateViewConfig(kv.Value, viewLocations, designerViewFilesMappings); + + if (config != null) + viewConfigs.Add(new KeyValuePair(kv.Value, config)); + } + + return viewConfigs; + } + + private void PopulateModulesForScripts(IEnumerable scripts) + { + if (scripts == null || scripts.Count() == 0) + { + return; + } + + var modules = ComponentsDependencyResolver.GetModulesByScripts(scripts); + this.ModuleDependencies = this.ModuleDependencies.Concat(modules); + } + + private void PopulateComponentsScriptReferences(DesignerViewConfigModel designerViewConfigModel) + { + if (designerViewConfigModel == null) + { + return; + } + + if (designerViewConfigModel.Components != null && designerViewConfigModel.Components.Count > 0) + { + if (designerViewConfigModel.Scripts == null) + { + designerViewConfigModel.Scripts = new List(); + } + + designerViewConfigModel.Scripts = ComponentsDependencyResolver.GetScripts(designerViewConfigModel.Components, designerViewConfigModel.Scripts); + } } private string GetScriptReferencePath(string widgetName, string scriptFileName) @@ -211,12 +386,46 @@ private string GetScriptPath(string scriptFileName, string widgetName, string pa return scriptVirtualPath; } + private Control LoadControl(Guid controlId, DesignMediaType designMediaType) + { + if (controlId != Guid.Empty) + { + var manager = this.GetControlManager(designMediaType); + var objectData = manager.GetControl(controlId); + + var controlData = objectData as ControlData; + if (controlData != null && !controlData.Caption.IsNullOrEmpty()) + { + this.Caption = controlData.Caption; + } + + return manager.LoadControl(objectData); + } + else + { + return null; + } + } + + private IControlManager GetControlManager(DesignMediaType designMediaType) + { + if (designMediaType == DesignMediaType.Form) + { + return FormsManager.GetManager(); + } + else + { + return PageManager.GetManager(); + } + } + private const string DesignerViewPrefix = "DesignerView."; private const string ScriptPrefix = "designerview-"; private const string DesignerScriptsPath = "Mvc/Scripts"; private IEnumerable views; - private IEnumerable scriptReferences; + private IEnumerable scriptReferences; + private IEnumerable moduleDependencies = new List(); private string defaultView; } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerViewConfigModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerViewConfigModel.cs index a8774cdcc..f529a48e0 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerViewConfigModel.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerViewConfigModel.cs @@ -7,7 +7,7 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Models /// This class represents a JSON configuration for designer views. /// [DataContract] - public class DesignerViewConfigModel + internal class DesignerViewConfigModel { /// /// Gets or sets the priority. @@ -34,6 +34,24 @@ public class DesignerViewConfigModel /// The scripts. /// [DataMember(Name = "scripts")] - public IList Scripts { get; set; } + public IList Scripts { get; set; } + + /// + /// Gets or sets the components. + /// + /// + /// The components. + /// + [DataMember(Name = "components")] + public IList Components { get; set; } + + /// + /// Gets or sets a value indicating whether this instance is auto generated. + /// + /// + /// true if this instance is generated; otherwise, false. + /// + [IgnoreDataMember] + public bool IsGenerated { get; set; } } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/DynamicDataItemFieldAccessor.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/DynamicDataItemFieldAccessor.cs new file mode 100644 index 000000000..2d8f91588 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/DynamicDataItemFieldAccessor.cs @@ -0,0 +1,154 @@ +using System; +using System.ComponentModel; +using System.Dynamic; +using System.Linq; +using Newtonsoft.Json; +using Telerik.OpenAccess.Metadata; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Descriptors; +using Telerik.Sitefinity.DynamicModules.Model; +using Telerik.Sitefinity.Model; +using Telerik.Sitefinity.Modules; +using Telerik.Sitefinity.Modules.GenericContent; +using Telerik.Sitefinity.Utilities.HtmlParsing; +using Telerik.Sitefinity.Web.UI.Fields.Model; + +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + /// + /// Instances of this class are used to access fields of data items dynamically. + /// + public class DynamicDataItemFieldAccessor : DynamicObject + { + /// + /// Initializes a new instance of the class. + /// + /// The data item. + public DynamicDataItemFieldAccessor(ItemViewModel itemViewModel) + : base() + { + this.item = itemViewModel; + + if (this.item.DataItem is IDeferredHtmlFilterContainer deferredFilterContainer) + { + deferredFilterContainer.MarkForDefferedFiltering(); + } + } + + /// + /// Provides the implementation for operations that get member values. Classes derived from the class can override this method to specify dynamic behavior for operations such as getting a value for a property. + /// + /// Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member on which the dynamic operation is performed. For example, for the Console.WriteLine(sampleObject.SampleProperty) statement, where sampleObject is an instance of the class derived from the class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive. + /// The result of the get operation. For example, if the method is called for a property, you can assign the property value to . + /// + /// true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a run-time exception is thrown.) + /// + public override bool TryGetMember(GetMemberBinder binder, out object result) + { + if (binder == null) + throw new ArgumentNullException("binder"); + + var name = binder.Name; + result = this.GetMemberValue(name); + + return TypeDescriptor.GetProperties(this.item.DataItem)[name] != null; + } + + /// + /// Gets the member value. + /// + /// Name of the field. + /// The value of the member. + public object GetMemberValue(string fieldName) + { + var propInfo = TypeDescriptor.GetProperties(this.item.DataItem)[fieldName]; + if (propInfo != null) + { + var relatedDataInfo = propInfo as RelatedDataPropertyDescriptor; + if (relatedDataInfo == null) + { + var value = propInfo.GetValue(this.item.DataItem); + var fieldType = propInfo.GetFieldType(); + if (fieldType != null) + { + if(fieldType == UserFriendlyDataType.LongText) + { + var stringValue = this.GetAppropriateStringValue(value); + if (!(this.item.DataItem is IDeferredHtmlFilterContainer)) + { + stringValue = HtmlFilterProvider.ApplyFilters(stringValue); + } + return stringValue; + } + else if(fieldType == UserFriendlyDataType.Link) + { + var stringValue = this.GetAppropriateStringValue(value); + return this.ResolveLinkFieldLinks(stringValue); + } + } + + return value; + } + else + { + if (relatedDataInfo.MetaField.AllowMultipleRelations) + { + return this.item.RelatedItems(fieldName); + } + else + { + return this.item.RelatedItem(fieldName); + } + } + } + else + { + return null; + } + } + + private string GetAppropriateStringValue(object value) + { + string stringValue = value as Lstring; + if (stringValue != null) + { + return stringValue; + } + + return value as string; + } + + private string ResolveLinkFieldLinks(string stringValue) + { + var linkFields = string.Empty; + + var json = JsonConvert.DeserializeObject(stringValue); + if (json != null) + { + foreach (var linkModel in json.Where(lm => !string.IsNullOrEmpty(lm.Sfref))) + { + string hrefAnchor = $""; + string resolved = new DynamicLinksParser().Apply(hrefAnchor); + + using (HtmlParser parser = new HtmlParser(resolved)) + { + parser.SetChunkHashMode(false); + parser.AutoExtractBetweenTagsOnly = false; + parser.KeepRawHTML = true; + + var chunk = parser.ParseNext(); + + linkModel.Href = chunk.GetParamValue("href"); + linkModel.Sfref = chunk.GetParamValue("sfref"); + } + } + + linkFields = JsonConvert.SerializeObject(json); + } + + return linkFields; + } + + private readonly ItemViewModel item; + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/GridDesignerModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/GridDesignerModel.cs new file mode 100644 index 000000000..278d024d8 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/GridDesignerModel.cs @@ -0,0 +1,64 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + internal class GridDesignerModel : IGridDesignerModel + { + /// + /// Initializes a new instance of the class. + /// + /// Title of the grid. + /// The control identifier. + public GridDesignerModel(string gridTitle, string controlId) + { + this.GridTitle = gridTitle; + this.ControlId = controlId; + } + + /// + /// Gets or sets the grid title. + /// + /// + /// The grid title. + /// + public string GridTitle + { + get; + set; + } + + /// + /// Gets the control identifier. + /// + /// + /// The control identifier. + /// + public string ControlId + { + get; + set; + } + + /// + /// Gets the grid update service URL. + /// + /// + /// The grid update service URL. + /// + /// + public string GridUpdateServiceUrl + { + get + { + return RouteHelper.ResolveUrl(GridDesignerModel.GridUpdateUrlFormat, UrlResolveOptions.Rooted); + } + } + + private const string GridUpdateUrlFormat = "/Sitefinity/Services/Pages/ZoneEditorService.svc/Layout/Style/{0}/{1}/{2}/"; + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/IDesignerModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/IDesignerModel.cs index de43c910c..b02afae0e 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Models/IDesignerModel.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/IDesignerModel.cs @@ -1,4 +1,5 @@ using System.Collections.Generic; +using System.Web.UI; namespace Telerik.Sitefinity.Frontend.Mvc.Models { @@ -17,9 +18,30 @@ public interface IDesignerModel /// IEnumerable ScriptReferences { get; } + /// + /// Gets the angular module dependencies where all used client components are defined. + /// + /// + /// The module dependencies. + /// + IEnumerable ModuleDependencies { get; } + /// /// Gets the default view. /// string DefaultView { get; } + + /// + /// Gets the control that is being edited. + /// + Control Control { get; } + + /// + /// Gets the caption of the designer. + /// + /// + /// The caption. + /// + string Caption { get; } } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/IGridDesignerModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/IGridDesignerModel.cs new file mode 100644 index 000000000..abca145bc --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/IGridDesignerModel.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Web.UI; + +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + /// + /// This interface is used as a model for the GridDesignerController. + /// + public interface IGridDesignerModel + { + /// + /// Gets or sets the grid title. + /// + /// + /// The grid title. + /// + string GridTitle { get; set; } + + /// + /// Gets the control identifier. + /// + /// + /// The control identifier. + /// + string ControlId { get; set; } + + /// + /// Gets the grid update service URL. + /// + /// + /// The grid update service URL. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] + string GridUpdateServiceUrl { get; } + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/IPersonalizationDesignerModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/IPersonalizationDesignerModel.cs new file mode 100644 index 000000000..31c97c823 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/IPersonalizationDesignerModel.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Web.UI; + +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + /// + /// This interface is used as a model for the PersonalizationDesignerController. + /// + public interface IPersonalizationDesignerModel + { + /// + /// Gets or sets the grid title. + /// + /// + /// The grid title. + /// + string Title { get; set; } + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/ItemViewModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/ItemViewModel.cs new file mode 100644 index 000000000..922281249 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/ItemViewModel.cs @@ -0,0 +1,517 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Web.Script.Serialization; +using Telerik.Sitefinity.Data; +using Telerik.Sitefinity.Descriptors; +using Telerik.Sitefinity.DynamicModules.Builder.Model; +using Telerik.Sitefinity.GeoLocations.Model; +using Telerik.Sitefinity.Localization; +using Telerik.Sitefinity.Locations.Configuration; +using Telerik.Sitefinity.Model; +using Telerik.Sitefinity.Model.ContentLinks; +using Telerik.Sitefinity.RelatedData; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Taxonomies; +using Telerik.Sitefinity.Taxonomies.Model; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + /// + /// This class represents view model for items. + /// + /// + /// It is used in Master/detail widgets. + /// + public class ItemViewModel + { + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The item. + public ItemViewModel(IDataItem item) + { + this.DataItem = item; + this.Fields = new DynamicDataItemFieldAccessor(this); + } + + #endregion + + #region Public Properties + + /// + /// Gets the data item that is represented by this view model. + /// + /// + /// The data item. + /// + public IDataItem DataItem { get; private set; } + + /// + /// Gets a property that accesses fields of the data item that is represented by this view model. + /// + public dynamic Fields { get; private set; } + + /// + /// Gets the default URL. + /// + /// + /// The default URL. + /// + [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] + public string DefaultUrl + { + get + { + if (this.DataItem != null) + return this.DataItem.GetDefaultUrl(); + else + return null; + } + } + + /// + /// Gets the value of the identifier field for the item. + /// + /// identifier is its Title. + /// + /// The identifier value. + /// + public object Identifier + { + get + { + if (this.DataItem != null) + { + var field = RelatedDataHelper.GetRelatedTypeIdentifierField(this.DataItem.GetType().FullName); + return this.Fields.GetMemberValue(field); + } + else + { + return null; + } + } + } + + #endregion + + #region Public methods + + /// + /// Serializes to JSON. + /// + /// Name of the field. + /// + public virtual string SerializeToJson(string fieldName) + { + var cahcedResultKey = this.FieldCacheKey("SerializeToJson", fieldName); + + object cachedResult; + if (this.cachedFieldValues.TryGetValue(cahcedResultKey, out cachedResult)) + return cachedResult as string; + + var fieldValue = this.Fields.GetMemberValue(fieldName); + var serializedValue = new JavaScriptSerializer().Serialize(fieldValue); + this.cachedFieldValues[cahcedResultKey] = serializedValue; + + return serializedValue; + } + + #region Address field + + /// + /// Gets the address value string depending on the provided format. + /// + /// Name of the field. + /// The address format. + /// + public virtual string GetAddressString(string fieldName, string format) + { + var cahcedResultKey = this.FieldCacheKey("GetAddressString", fieldName); + + object cachedResult; + if (this.cachedFieldValues.TryGetValue(cahcedResultKey, out cachedResult)) + return cachedResult as string; + + string result = string.Empty; + var fieldValue = this.Fields.GetMemberValue(fieldName) as Address; + + if (fieldValue != null && !format.IsNullOrEmpty()) + { + var street = string.Empty; + if (!string.IsNullOrEmpty(fieldValue.Street)) + { + street = fieldValue.Street + ","; + } + + result = format.Replace("#=Street#", street); + + var zip = string.Empty; + if (!string.IsNullOrEmpty(fieldValue.Zip)) + { + zip = fieldValue.Zip + ","; + } + + result = result.Replace("#=Zip#", zip); + + var city = string.Empty; + if (!string.IsNullOrEmpty(fieldValue.City)) + { + city = fieldValue.City + ","; + } + + result = result.Replace("#=City#", city); + + var country = Telerik.Sitefinity.Configuration.Config.Get().Countries[fieldValue.CountryCode]; + string countryName = string.Empty; + var state = string.Empty; + if (country != null) + { + countryName = country.Name; + if (!fieldValue.StateCode.IsNullOrEmpty() && + (fieldValue.CountryCode == "CA" || fieldValue.CountryCode == "US")) + { + var stateData = Telerik.Sitefinity.Configuration.Config.Get().Countries[fieldValue.CountryCode] + .StatesProvinces[fieldValue.StateCode]; + if (stateData != null) + { + state = stateData.Name; + } + } + } + + result = result.Replace("#=Country#", countryName); + result = result.Replace("#=State#", state); + } + + this.cachedFieldValues[cahcedResultKey] = result; + + return result; + } + + #endregion + + #region DateTime field + + /// + /// Gets formatted date time value. + /// + /// Name of the field. + /// The field format. + /// + public virtual string GetDateTime(string fieldName, string format) + { + var dateTimeValue = (DateTime)this.Fields.GetMemberValue(fieldName); + + if (dateTimeValue == default(DateTime)) + return null; + + var formattedDate = dateTimeValue.ToSitefinityUITime().ToString(format); + + return formattedDate; + } + + #endregion + + #region Price field + + /// + /// Gets formatted date time value. + /// + /// Name of the field. + /// The field format. + /// + public virtual string GetPrice(string fieldName, string format) + { + var fieldValue = this.Fields.GetMemberValue(fieldName); + if (fieldValue == null) + return null; + + var formattedValue = fieldValue.ToString(format); + + return formattedValue; + } + + #endregion + + #region Yes/No field + + /// + /// Gets field value as Yes/No string. + /// + /// Name of the field. + /// + public virtual string GetBool(string fieldName) + { + var boolValue = (bool)this.Fields.GetMemberValue(fieldName); + + return boolValue ? Res.Get().Yes : Res.Get().No; + } + + #endregion + + #region Choice fields + + /// + /// Gets the multiple choice value string. + /// + /// The multi choice values. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "multi")] + public virtual string GetMultipleChoiceValueString(string fieldName) + { + var multiChoiceValues = this.Fields.GetMemberValue(fieldName) as IEnumerable; + if (multiChoiceValues == null) + return null; + + StringBuilder sb = new StringBuilder(); + + foreach (object val in multiChoiceValues) + { + sb.Append(val.ToString()); + sb.Append(", "); + } + + if (sb.Length > 1) + sb.Remove(sb.Length - 2, 2); + + return sb.ToString(); + } + + #endregion + + #region Taxon fields + + /// + /// Gets the flat taxons. + /// + /// Name of the field. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Taxons")] + public virtual IList GetFlatTaxons(string fieldName) + { + var cahcedResultKey = this.FieldCacheKey("GetFlatTaxonNames", fieldName); + object cachedResult; + if (this.cachedFieldValues.TryGetValue(cahcedResultKey, out cachedResult)) + return cachedResult as IList; + + var taxa = TaxonomyApplicationState.GetTaxa(this.DataItem, fieldName); + + this.cachedFieldValues[cahcedResultKey] = taxa; + + return taxa; + } + + /// + /// Gets the list of hierarchical taxons. + /// + /// Name of the field. + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Taxons")] + public virtual IList GetHierarchicalTaxons(string fieldName) + { + var cahcedResultKey = this.FieldCacheKey("GetHierarchicalTaxonNames", fieldName); + object cachedResult; + if (this.cachedFieldValues.TryGetValue(cahcedResultKey, out cachedResult)) + return cachedResult as IList; + + var taxa = TaxonomyApplicationState.GetTaxa(this.DataItem, fieldName); + + this.cachedFieldValues[cahcedResultKey] = taxa; + + return taxa; + } + + /// + /// Gets the flat taxon. + /// + /// Name of the field. + /// + public virtual FlatTaxon GetFlatTaxon(string fieldName) + { + var taxon = this.GetFlatTaxons(fieldName).FirstOrDefault(); + + return taxon; + } + + /// + /// Gets the hierarchical taxon. + /// + /// Name of the field. + /// + public virtual HierarchicalTaxon GetHierarchicalTaxon(string fieldName) + { + var taxon = this.GetHierarchicalTaxons(fieldName).FirstOrDefault(); + + return taxon; + } + + #endregion + + #region Related data fileds + + /// + /// Gets related items. + /// + /// Name of the field. + /// + public virtual IEnumerable RelatedItems(string fieldName) + { + var cahcedResultKey = this.FieldCacheKey("RelatedItems", fieldName); + object cachedResult; + if (this.cachedFieldValues.TryGetValue(cahcedResultKey, out cachedResult)) + return cachedResult as IEnumerable; + + IEnumerable result; + + IEnumerable relatedItems; + if (!this.TryGetResultFromRelatedDataPropertyDescriptor>(fieldName, out relatedItems)) + { + relatedItems = this.DataItem.GetRelatedItems(fieldName); + } + + if (relatedItems != null) + result = relatedItems.ToArray().Select(item => new ItemViewModel(item)).ToArray(); + else + result = null; + + AddCacheDependenciesForRelatedItems(relatedItems); + this.cachedFieldValues[cahcedResultKey] = result; + + return result; + } + + /// + /// Gets the related item when single. + /// + /// Name of the field. + /// + public virtual ItemViewModel RelatedItem(string fieldName) + { + var cahcedResultKey = this.FieldCacheKey("RelatedItem", fieldName); + object cachedResult; + if (this.cachedFieldValues.TryGetValue(cahcedResultKey, out cachedResult)) + return cachedResult as ItemViewModel; + + ItemViewModel result; + IDataItem relatedItem; + if (this.TryGetResultFromRelatedDataPropertyDescriptor(fieldName, out relatedItem)) + { + result = relatedItem == null ? null : new ItemViewModel(relatedItem); + AddCacheDependenciesForRelatedItems(new []{ relatedItem }); + } + else + { + var relatedItems = this.DataItem.GetRelatedItems(fieldName); + AddCacheDependenciesForRelatedItems(relatedItems); + + if (relatedItems != null) + result = relatedItems.ToArray().Select(item => new ItemViewModel(item)).FirstOrDefault(); + else + result = null; + } + + this.cachedFieldValues[cahcedResultKey] = result; + + return result; + } + + private bool TryGetResultFromRelatedDataPropertyDescriptor(string fieldName, out T param) + { + param = default(T); + var propInfo = TypeDescriptor.GetProperties(this.DataItem)[fieldName]; + var relatedDataPropertyDescriptor = propInfo as RelatedDataPropertyDescriptor; + if (relatedDataPropertyDescriptor != null) + { + var result = relatedDataPropertyDescriptor.GetValue(this.DataItem); + if (result != null && typeof(T).IsAssignableFrom(result.GetType())) + { + param = (T)result; + } + + return true; + } + + return false; + } + #endregion + + #endregion + + #region Private members + + /// + /// Gets the cache key for . + /// + /// Name of the method. + /// Name of the field. + /// + private string FieldCacheKey(string methodName, string fieldName) + { + return methodName + ":" + fieldName; + } + + /// + /// Contains the cached field values. + /// + private Dictionary cachedFieldValues = new Dictionary(); + + private static void AddCacheDependenciesForRelatedItems(IEnumerable relatedItems) + { + if (relatedItems == null || !relatedItems.Any() || (relatedItems.Count() == 1 && relatedItems.First() == null)) + { + return; + } + + var cacheDependencyKeys = new List(); + var itemType = relatedItems.First().GetType(); + if (relatedItems.Count() > 10) + { + var appName = ""; + var provider = relatedItems.First().Provider as DataProviderBase; + if (provider != null) + { + appName = provider.ApplicationName; + } + + cacheDependencyKeys.AddRange(OutputCacheDependencyHelper.GetPublishedContentCacheDependencyKeys(itemType, appName)); + } + else + { + foreach (var relatedItem in relatedItems) + { + cacheDependencyKeys.AddRange(OutputCacheDependencyHelper.GetPublishedContentCacheDependencyKeys(itemType, relatedItem.Id)); + } + } + + AddCacheDependencyKeys(cacheDependencyKeys); + } + + private static void AddCacheDependencyKeys(IList cacheDependencyKeys) + { + var current = SystemManager.CurrentHttpContext.Items[PageCacheDependencyKeys.PageData] as IList; + if (current != null) + { + foreach (var cacheDependencyKey in cacheDependencyKeys) + { + current.Add(cacheDependencyKey); + } + } + else + { + current = cacheDependencyKeys; + } + + SystemManager.CurrentHttpContext.Items[PageCacheDependencyKeys.PageData] = current; + } + + #endregion + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/ListDisplayMode.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/ListDisplayMode.cs new file mode 100644 index 000000000..441ef7aac --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/ListDisplayMode.cs @@ -0,0 +1,26 @@ +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + /// + /// The rendering options for the lists. + /// + /// + /// Each option describes different options for dividing items in the list. + /// + public enum ListDisplayMode + { + /// + /// Display list divided on pages. + /// + Paging, + + /// + /// Display only limited number of items. + /// + Limit, + + /// + /// Display all items. + /// + All + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/LogicalOperator.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/LogicalOperator.cs new file mode 100644 index 000000000..2ef2fd61e --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/LogicalOperator.cs @@ -0,0 +1,21 @@ +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + /// + /// The logical operators for constructing filter expressions. + /// + /// + /// Each option describes different logical operator. + /// + public enum LogicalOperator + { + /// + /// AND logical operator. + /// + AND, + + /// + /// OR logical operator. + /// + OR + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/PersonalizationDesignerModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/PersonalizationDesignerModel.cs new file mode 100644 index 000000000..c95a54400 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/PersonalizationDesignerModel.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + /// + /// This class is used as a model for the personalization designer controller. + /// + internal class PersonalizationDesignerModel : IPersonalizationDesignerModel + { + /// + /// Initializes a new instance of the class. + /// + public PersonalizationDesignerModel() + { + } + + /// + /// Gets or sets the personalization dialog title. + /// + /// + /// The dialog title. + /// + public string Title + { + get; + set; + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/ScriptDependencyConfigModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/ScriptDependencyConfigModel.cs new file mode 100644 index 000000000..5ea80f9f0 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/ScriptDependencyConfigModel.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; + +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + /// + /// This class represents a JSON configuration for component definitions. + /// + internal class ScriptDependencyConfigModel + { + /// + /// Gets or sets the scripts. + /// + /// + /// the scripts. + /// + [DataMember(Name = "scripts")] + public IEnumerable Scripts { get; set; } + + /// + /// Gets or sets the components. + /// + /// + /// the components. + /// + [DataMember(Name = "components")] + public IEnumerable Components { get; set; } + + /// + /// Gets or sets the angular modules. + /// + /// + /// The angular modules. + /// + [DataMember(Name = "angularModules")] + public IEnumerable AngularModules { get; set; } + } +} \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/SelectionMode.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/SelectionMode.cs new file mode 100644 index 000000000..dc81015d7 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/SelectionMode.cs @@ -0,0 +1,26 @@ +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + /// + /// The rendering options for a widget. + /// + /// + /// Each option describes different selection of items that will be included while rendering a widget. + /// + public enum SelectionMode + { + /// + /// Refers to all items. + /// + AllItems, + + /// + /// Refers to custom selection of items. + /// + SelectedItems, + + /// + /// Refers to filtered items based on a custom criteria. + /// + FilteredItems + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/ServerContext.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/ServerContext.cs new file mode 100644 index 000000000..0158f3285 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/ServerContext.cs @@ -0,0 +1,87 @@ +using ServiceStack.Text; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using Telerik.Sitefinity.Abstractions; +using Telerik.Sitefinity.Frontend.Resources; +using Telerik.Sitefinity.Licensing; +using Telerik.Sitefinity.Modules.Libraries; +using Telerik.Sitefinity.Modules.Libraries.BlobStorage; +using Telerik.Sitefinity.Security.Claims; +using Telerik.Sitefinity.Services; +using Telerik.Sitefinity.Web; + +namespace Telerik.Sitefinity.Frontend.Mvc.Models +{ + [EditorBrowsable(EditorBrowsableState.Never)] + public class ServerContext + { + public string ApplicationPath + { + get { return RouteHelper.ResolveUrl("~/", UrlResolveOptions.Rooted); } + } + + public string CurrentPackage + { + get { return new PackageManager().GetCurrentPackage() ?? string.Empty; } + } + + public string FrontendLanguages + { + get + { + var appSettings = SystemManager.CurrentContext.AppSettings; + var languages = appSettings.DefinedFrontendLanguages.Select(l => l.Name); + + var serialziedLanguages = JsonSerializer.SerializeToString(languages); + + return serialziedLanguages; + } + } + + public string CurrentFrontendRootNodeId + { + get { return SiteInitializer.CurrentFrontendRootNodeId.ToString(); } + } + + public string CurrentUserId + { + get + { + var identity = ClaimsManager.GetCurrentIdentity(); + var id = identity == null ? Guid.Empty : identity.UserId; + + return id.ToString(); + } + } + + public string CurrentSiteId + { + get { return SystemManager.CurrentContext.CurrentSite.Id.ToString(); } + } + + public string IsMultisiteMode + { + get { return true.ToString(); } + } + + public string[] DamSupportedMediaTypes + { + get + { + IEnumerable damSupportedMediaTypes = Enumerable.Empty(); + if (LicenseState.CheckIsModuleLicensed(LibrariesModule.DamIntegrationModuleId)) + { + var provider = BlobStorageManager.GetManager().StaticProviders.OfType().FirstOrDefault(); + if (provider != null) + { + damSupportedMediaTypes = provider.GetSupportedMediaTypes().Select(x => x.FullName); + } + } + + return damSupportedMediaTypes.ToArray(); + } + } + } +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-resource.js b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-resource.js index 76150b54c..feb633824 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-resource.js +++ b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-resource.js @@ -1,16 +1,16 @@ /** - * @license AngularJS v1.2.23-build.379+sha.cb18343 - * (c) 2010-2014 Google, Inc. http://angularjs.org + * @license AngularJS v1.8.2 + * (c) 2010-2020 Google LLC. http://angularjs.org * License: MIT */ -(function(window, angular, undefined) {'use strict'; +(function(window, angular) {'use strict'; var $resourceMinErr = angular.$$minErr('$resource'); // Helper functions and regex to lookup a dotted path on an object // stopping at undefined/null. The path must be composed of ASCII // identifiers (just like $parse) -var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$][0-9a-zA-Z_$]*)+$/; +var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/; function isValidDottedPath(path) { return (path != null && path !== '' && path !== 'hasOwnProperty' && @@ -22,7 +22,7 @@ function lookupDottedPath(obj, path) { throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path); } var keys = path.split('.'); - for (var i = 0, ii = keys.length; i < ii && obj !== undefined; i++) { + for (var i = 0, ii = keys.length; i < ii && angular.isDefined(obj); i++) { var key = keys[i]; obj = (obj !== null) ? obj[key] : undefined; } @@ -35,7 +35,7 @@ function lookupDottedPath(obj, path) { function shallowClearAndCopy(src, dst) { dst = dst || {}; - angular.forEach(dst, function(value, key){ + angular.forEach(dst, function(value, key) { delete dst[key]; }); @@ -53,21 +53,33 @@ function shallowClearAndCopy(src, dst) { * @name ngResource * @description * - * # ngResource - * * The `ngResource` module provides interaction support with RESTful services * via the $resource service. * + * See {@link ngResource.$resourceProvider} and {@link ngResource.$resource} for usage. + */ + +/** + * @ngdoc provider + * @name $resourceProvider * - *
+ * @description + * + * Use `$resourceProvider` to change the default behavior of the {@link ngResource.$resource} + * service. + * + * ## Dependencies + * Requires the {@link ngResource } module to be installed. * - * See {@link ngResource.$resource `$resource`} for usage. */ /** * @ngdoc service * @name $resource * @requires $http + * @requires ng.$log + * @requires $q + * @requires ng.$timeout * * @description * A factory which creates a resource object that lets you interact with @@ -78,7 +90,19 @@ function shallowClearAndCopy(src, dst) { * * Requires the {@link ngResource `ngResource`} module to be installed. * - * @param {string} url A parametrized URL template with parameters prefixed by `:` as in + * By default, trailing slashes will be stripped from the calculated URLs, + * which can pose problems with server backends that do not expect that + * behavior. This can be disabled by configuring the `$resourceProvider` like + * this: + * + * ```js + app.config(['$resourceProvider', function($resourceProvider) { + // Don't strip trailing slashes from calculated URLs + $resourceProvider.defaults.stripTrailingSlashes = false; + }]); + * ``` + * + * @param {string} url A parameterized URL template with parameters prefixed by `:` as in * `/user/:username`. If you are using a URL with a port number (e.g. * `http://example.com:8080/api`), it will be respected. * @@ -90,27 +114,36 @@ function shallowClearAndCopy(src, dst) { * can escape it with `/\.`. * * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in - * `actions` methods. If any of the parameter value is a function, it will be executed every time - * when a param value needs to be obtained for a request (unless the param was overridden). + * `actions` methods. If a parameter value is a function, it will be called every time + * a param value needs to be obtained for a request (unless the param was overridden). The + * function will be passed the current data value as an argument. * * Each key value in the parameter object is first bound to url template if present and then any * excess keys are appended to the url search query after the `?`. * - * Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in + * Given a template `/path/:verb` and parameter `{verb: 'greet', salutation: 'Hello'}` results in * URL `/path/greet?salutation=Hello`. * - * If the parameter value is prefixed with `@` then the value for that parameter will be extracted - * from the corresponding property on the `data` object (provided when calling an action method). For - * example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of `someParam` - * will be `data.someProp`. + * If the parameter value is prefixed with `@`, then the value for that parameter will be + * extracted from the corresponding property on the `data` object (provided when calling actions + * with a request body). + * For example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of + * `someParam` will be `data.someProp`. + * Note that the parameter will be ignored, when calling a "GET" action method (i.e. an action + * method that does not accept a request body). + * + * @param {Object.=} actions Hash with declaration of custom actions that will be available + * in addition to the default set of resource actions (see below). If a custom action has the same + * key as a default action (e.g. `save`), then the default action will be *overwritten*, and not + * extended. * - * @param {Object.=} actions Hash with declaration of custom action that should extend - * the default set of resource actions. The declaration should be created in the format of {@link - * ng.$http#usage_parameters $http.config}: + * The declaration should be created in the format of {@link ng.$http#usage $http.config}: * - * {action1: {method:?, params:?, isArray:?, headers:?, ...}, - * action2: {method:?, params:?, isArray:?, headers:?, ...}, - * ...} + * { + * action1: {method:?, params:?, isArray:?, headers:?, ...}, + * action2: {method:?, params:?, isArray:?, headers:?, ...}, + * ... + * } * * Where: * @@ -119,60 +152,96 @@ function shallowClearAndCopy(src, dst) { * - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`, * `DELETE`, `JSONP`, etc). * - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of - * the parameter value is a function, it will be executed every time when a param value needs to - * be obtained for a request (unless the param was overridden). - * - **`url`** – {string} – action specific `url` override. The url templating is supported just + * the parameter value is a function, it will be called every time when a param value needs to + * be obtained for a request (unless the param was overridden). The function will be passed the + * current data value as an argument. + * - **`url`** – {string} – Action specific `url` override. The url templating is supported just * like for the resource-level urls. * - **`isArray`** – {boolean=} – If true then the returned object for this action is an array, * see `returns` section. * - **`transformRequest`** – * `{function(data, headersGetter)|Array.}` – - * transform function or an array of such functions. The transform function takes the http + * Transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. + * By default, transformRequest will contain one function that checks if the request data is + * an object and serializes it using `angular.toJson`. To prevent this behavior, set + * `transformRequest` to an empty array: `transformRequest: []` * - **`transformResponse`** – - * `{function(data, headersGetter)|Array.}` – - * transform function or an array of such functions. The transform function takes the http - * response body and headers and returns its transformed (typically deserialized) version. - * - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the - * GET request, otherwise if a cache instance built with - * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for - * caching. - * - **`timeout`** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} that - * should abort the request when resolved. - * - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the + * `{function(data, headersGetter, status)|Array.}` – + * Transform function or an array of such functions. The transform function takes the HTTP + * response body, headers and status and returns its transformed (typically deserialized) + * version. + * By default, transformResponse will contain one function that checks if the response looks + * like a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior, + * set `transformResponse` to an empty array: `transformResponse: []` + * - **`cache`** – `{boolean|Cache}` – A boolean value or object created with + * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response. + * See {@link $http#caching $http Caching} for more information. + * - **`timeout`** – `{number}` – Timeout in milliseconds.
+ * **Note:** In contrast to {@link ng.$http#usage $http.config}, {@link ng.$q promises} are + * **not** supported in `$resource`, because the same value would be used for multiple requests. + * If you are looking for a way to cancel requests, you should use the `cancellable` option. + * - **`cancellable`** – `{boolean}` – If true, the request made by a "non-instance" call will be + * cancelled (if not already completed) by calling `$cancelRequest()` on the call's return + * value. Calling `$cancelRequest()` for a non-cancellable or an already completed/cancelled + * request will have no effect. + * - **`withCredentials`** – `{boolean}` – Whether to set the `withCredentials` flag on the * XHR object. See - * [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5) + * [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials) * for more information. - * - **`responseType`** - `{string}` - see - * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). - * - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods - - * `response` and `responseError`. Both `response` and `responseError` interceptors get called - * with `http response` object. See {@link ng.$http $http interceptors}. + * - **`responseType`** – `{string}` – See + * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType). + * - **`interceptor`** – `{Object=}` – The interceptor object has four optional methods - + * `request`, `requestError`, `response`, and `responseError`. See + * {@link ng.$http#interceptors $http interceptors} for details. Note that + * `request`/`requestError` interceptors are applied before calling `$http`, thus before any + * global `$http` interceptors. Also, rejecting or throwing an error inside the `request` + * interceptor will result in calling the `responseError` interceptor. + * The resource instance or collection is available on the `resource` property of the + * `http response` object passed to `response`/`responseError` interceptors. + * Keep in mind that the associated promise will be resolved with the value returned by the + * response interceptors. Make sure you return an appropriate value and not the `response` + * object passed as input. For reference, the default `response` interceptor (which gets applied + * if you don't specify a custom one) returns `response.resource`.
+ * See {@link ngResource.$resource#using-interceptors below} for an example of using + * interceptors in `$resource`. + * - **`hasBody`** – `{boolean}` – If true, then the request will have a body. + * If not specified, then only POST, PUT and PATCH requests will have a body. * + * @param {Object} options Hash with custom settings that should extend the + * default `$resourceProvider` behavior. The supported options are: + * + * - **`stripTrailingSlashes`** – {boolean} – If true then the trailing + * slashes from any calculated URL will be stripped. (Defaults to true.) + * - **`cancellable`** – {boolean} – If true, the request made by a "non-instance" call will be + * cancelled (if not already completed) by calling `$cancelRequest()` on the call's return value. + * This can be overwritten per action. (Defaults to false.) * * @returns {Object} A resource "class" object with methods for the default set of resource actions * optionally extended with custom `actions`. The default set contains these actions: * ```js - * { 'get': {method:'GET'}, - * 'save': {method:'POST'}, - * 'query': {method:'GET', isArray:true}, - * 'remove': {method:'DELETE'}, - * 'delete': {method:'DELETE'} }; + * { + * 'get': {method: 'GET'}, + * 'save': {method: 'POST'}, + * 'query': {method: 'GET', isArray: true}, + * 'remove': {method: 'DELETE'}, + * 'delete': {method: 'DELETE'} + * } * ``` * - * Calling these methods invoke an {@link ng.$http} with the specified http method, - * destination and parameters. When the data is returned from the server then the object is an - * instance of the resource class. The actions `save`, `remove` and `delete` are available on it - * as methods with the `$` prefix. This allows you to easily perform CRUD operations (create, - * read, update, delete) on server-side data like this: + * Calling these methods invoke {@link ng.$http} with the specified http method, destination and + * parameters. When the data is returned from the server then the object is an instance of the + * resource class. The actions `save`, `remove` and `delete` are available on it as methods with + * the `$` prefix. This allows you to easily perform CRUD operations (create, read, update, + * delete) on server-side data like this: * ```js - * var User = $resource('/user/:userId', {userId:'@id'}); - * var user = User.get({userId:123}, function() { + * var User = $resource('/user/:userId', {userId: '@id'}); + * User.get({userId: 123}).$promise.then(function(user) { * user.abc = true; * user.$save(); * }); * ``` * - * It is important to realize that invoking a $resource object method immediately returns an + * It is important to realize that invoking a `$resource` object method immediately returns an * empty reference (object or array depending on `isArray`). Once the data is returned from the * server the existing reference is populated with the actual data. This is a useful trick since * usually the resource is assigned to a model which is then rendered by the view. Having an empty @@ -183,439 +252,660 @@ function shallowClearAndCopy(src, dst) { * The action methods on the class object or instance object can be invoked with the following * parameters: * - * - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])` - * - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])` - * - non-GET instance actions: `instance.$action([parameters], [success], [error])` + * - "class" actions without a body: `Resource.action([parameters], [success], [error])` + * - "class" actions with a body: `Resource.action([parameters], postData, [success], [error])` + * - instance actions: `instance.$action([parameters], [success], [error])` + * * - * Success callback is called with (value, responseHeaders) arguments. Error callback is called - * with (httpResponse) argument. + * When calling instance methods, the instance itself is used as the request body (if the action + * should have a body). By default, only actions using `POST`, `PUT` or `PATCH` have request + * bodies, but you can use the `hasBody` configuration option to specify whether an action + * should have a body or not (regardless of its HTTP method). * - * Class actions return empty instance (with additional properties below). - * Instance actions return promise of the action. * - * The Resource instances and collection have these additional properties: + * Success callback is called with (value (Object|Array), responseHeaders (Function), + * status (number), statusText (string)) arguments, where `value` is the populated resource + * instance or collection object. The error callback is called with (httpResponse) argument. * - * - `$promise`: the {@link ng.$q promise} of the original server interaction that created this + * Class actions return an empty instance (with the additional properties listed below). + * Instance actions return a promise for the operation. + * + * The Resource instances and collections have these additional properties: + * + * - `$promise`: The {@link ng.$q promise} of the original server interaction that created this * instance or collection. * * On success, the promise is resolved with the same resource instance or collection object, - * updated with data from server. This makes it easy to use in - * {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view + * updated with data from server. This makes it easy to use in the + * {@link ngRoute.$routeProvider `resolve` section of `$routeProvider.when()`} to defer view * rendering until the resource(s) are loaded. * - * On failure, the promise is resolved with the {@link ng.$http http response} object, without - * the `resource` property. + * On failure, the promise is rejected with the {@link ng.$http http response} object. * * If an interceptor object was provided, the promise will instead be resolved with the value - * returned by the interceptor. + * returned by the response interceptor (on success) or responceError interceptor (on failure). * * - `$resolved`: `true` after first server interaction is completed (either with success or * rejection), `false` before that. Knowing if the Resource has been resolved is useful in - * data-binding. + * data-binding. If there is a response/responseError interceptor and it returns a promise, + * `$resolved` will wait for that too. + * + * The Resource instances and collections have these additional methods: + * + * - `$cancelRequest`: If there is a cancellable, pending request related to the instance or + * collection, calling this method will abort the request. + * + * The Resource instances have these additional methods: + * + * - `toJSON`: It returns a simple object without any of the extra properties added as part of + * the Resource API. This object can be serialized through {@link angular.toJson} safely + * without attaching AngularJS-specific fields. Notice that `JSON.stringify` (and + * `angular.toJson`) automatically use this method when serializing a Resource instance + * (see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#toJSON%28%29_behavior)). * * @example * - * # Credit card resource + * ### Basic usage * - * ```js - // Define CreditCard class - var CreditCard = $resource('/user/:userId/card/:cardId', - {userId:123, cardId:'@id'}, { - charge: {method:'POST', params:{charge:true}} - }); + ```js + // Define a CreditCard class + var CreditCard = $resource('/users/:userId/cards/:cardId', + {userId: 123, cardId: '@id'}, { + charge: {method: 'POST', params: {charge: true}} + }); // We can retrieve a collection from the server - var cards = CreditCard.query(function() { - // GET: /user/123/card - // server returns: [ {id:456, number:'1234', name:'Smith'} ]; + var cards = CreditCard.query(); + // GET: /users/123/cards + // server returns: [{id: 456, number: '1234', name: 'Smith'}] + // Wait for the request to complete + cards.$promise.then(function() { var card = cards[0]; - // each item is an instance of CreditCard + + // Each item is an instance of CreditCard expect(card instanceof CreditCard).toEqual(true); - card.name = "J. Smith"; - // non GET methods are mapped onto the instances + + // Non-GET methods are mapped onto the instances + card.name = 'J. Smith'; card.$save(); - // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'} - // server returns: {id:456, number:'1234', name: 'J. Smith'}; + // POST: /users/123/cards/456 {id: 456, number: '1234', name: 'J. Smith'} + // server returns: {id: 456, number: '1234', name: 'J. Smith'} - // our custom method is mapped as well. - card.$charge({amount:9.99}); - // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'} + // Our custom method is mapped as well (since it uses POST) + card.$charge({amount: 9.99}); + // POST: /users/123/cards/456?amount=9.99&charge=true {id: 456, number: '1234', name: 'J. Smith'} }); - // we can create an instance as well - var newCard = new CreditCard({number:'0123'}); - newCard.name = "Mike Smith"; - newCard.$save(); - // POST: /user/123/card {number:'0123', name:'Mike Smith'} - // server returns: {id:789, number:'0123', name: 'Mike Smith'}; - expect(newCard.id).toEqual(789); - * ``` + // We can create an instance as well + var newCard = new CreditCard({number: '0123'}); + newCard.name = 'Mike Smith'; + + var savePromise = newCard.$save(); + // POST: /users/123/cards {number: '0123', name: 'Mike Smith'} + // server returns: {id: 789, number: '0123', name: 'Mike Smith'} + + savePromise.then(function() { + // Once the promise is resolved, the created instance + // is populated with the data returned by the server + expect(newCard.id).toEqual(789); + }); + ``` + * + * The object returned from a call to `$resource` is a resource "class" which has one "static" + * method for each action in the definition. * - * The object returned from this function execution is a resource "class" which has "static" method - * for each action in the definition. + * Calling these methods invokes `$http` on the `url` template with the given HTTP `method`, + * `params` and `headers`. + * + * @example + * + * ### Accessing the response * - * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and - * `headers`. * When the data is returned from the server then the object is an instance of the resource type and * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD * operations (create, read, update, delete) on server-side data. - + * ```js - var User = $resource('/user/:userId', {userId:'@id'}); - User.get({userId:123}, function(user) { + var User = $resource('/users/:userId', {userId: '@id'}); + User.get({userId: 123}).$promise.then(function(user) { user.abc = true; user.$save(); }); ``` * - * It's worth noting that the success callback for `get`, `query` and other methods gets passed - * in the response that came from the server as well as $http header getter function, so one - * could rewrite the above example and get access to http headers as: + * It's worth noting that the success callback for `get`, `query` and other methods gets called with + * the resource instance (populated with the data that came from the server) as well as an `$http` + * header getter function, the HTTP status code and the response status text. So one could rewrite + * the above example and get access to HTTP headers as follows: * ```js - var User = $resource('/user/:userId', {userId:'@id'}); - User.get({userId:123}, function(u, getResponseHeaders){ - u.abc = true; - u.$save(function(u, putResponseHeaders) { - //u => saved user object - //putResponseHeaders => $http header getter + var User = $resource('/users/:userId', {userId: '@id'}); + User.get({userId: 123}, function(user, getResponseHeaders) { + user.abc = true; + user.$save(function(user, putResponseHeaders) { + // `user` => saved `User` object + // `putResponseHeaders` => `$http` header getter }); }); ``` * - * You can also access the raw `$http` promise via the `$promise` property on the object returned + * @example + * + * ### Creating custom actions + * + * In this example we create a custom method on our resource to make a PUT request: * + ```js + var app = angular.module('app', ['ngResource']); + + // Some APIs expect a PUT request in the format URL/object/ID + // Here we are creating an 'update' method + app.factory('Notes', ['$resource', function($resource) { + return $resource('/notes/:id', {id: '@id'}, { + update: {method: 'PUT'} + }); + }]); + + // In our controller we get the ID from the URL using `$location` + app.controller('NotesCtrl', ['$location', 'Notes', function($location, Notes) { + // First, retrieve the corresponding `Note` object from the server + // (Assuming a URL of the form `.../notes?id=XYZ`) + var noteId = $location.search().id; + var note = Notes.get({id: noteId}); + + note.$promise.then(function() { + note.content = 'Hello, world!'; + + // Now call `update` to save the changes on the server + Notes.update(note); + // This will PUT /notes/ID with the note object as the request payload + + // Since `update` is a non-GET method, it will also be available on the instance + // (prefixed with `$`), so we could replace the `Note.update()` call with: + //note.$update(); + }); + }]); ``` - var User = $resource('/user/:userId', {userId:'@id'}); - User.get({userId:123}) - .$promise.then(function(user) { - $scope.user = user; - }); + * + * @example + * + * ### Cancelling requests + * + * If an action's configuration specifies that it is cancellable, you can cancel the request related + * to an instance or collection (as long as it is a result of a "non-instance" call): + * + ```js + // ...defining the `Hotel` resource... + var Hotel = $resource('/api/hotels/:id', {id: '@id'}, { + // Let's make the `query()` method cancellable + query: {method: 'get', isArray: true, cancellable: true} + }); + + // ...somewhere in the PlanVacationController... + ... + this.onDestinationChanged = function onDestinationChanged(destination) { + // We don't care about any pending request for hotels + // in a different destination any more + if (this.availableHotels) { + this.availableHotels.$cancelRequest(); + } + + // Let's query for hotels in `destination` + // (calls: /api/hotels?location=) + this.availableHotels = Hotel.query({location: destination}); + }; ``` + * + * @example + * + * ### Using interceptors + * + * You can use interceptors to transform the request or response, perform additional operations, and + * modify the returned instance/collection. The following example, uses `request` and `response` + * interceptors to augment the returned instance with additional info: + * + ```js + var Thing = $resource('/api/things/:id', {id: '@id'}, { + save: { + method: 'POST', + interceptor: { + request: function(config) { + // Before the request is sent out, store a timestamp on the request config + config.requestTimestamp = Date.now(); + return config; + }, + response: function(response) { + // Get the instance from the response object + var instance = response.resource; + + // Augment the instance with a custom `saveLatency` property, computed as the time + // between sending the request and receiving the response. + instance.saveLatency = Date.now() - response.config.requestTimestamp; + + // Return the instance + return instance; + } + } + } + }); - * # Creating a custom 'PUT' request - * In this example we create a custom method on our resource to make a PUT request - * ```js - * var app = angular.module('app', ['ngResource', 'ngRoute']); - * - * // Some APIs expect a PUT request in the format URL/object/ID - * // Here we are creating an 'update' method - * app.factory('Notes', ['$resource', function($resource) { - * return $resource('/notes/:id', null, - * { - * 'update': { method:'PUT' } - * }); - * }]); - * - * // In our controller we get the ID from the URL using ngRoute and $routeParams - * // We pass in $routeParams and our Notes factory along with $scope - * app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes', - function($scope, $routeParams, Notes) { - * // First get a note object from the factory - * var note = Notes.get({ id:$routeParams.id }); - * $id = note.id; - * - * // Now call update passing in the ID first then the object you are updating - * Notes.update({ id:$id }, note); - * - * // This will PUT /notes/ID with the note object in the request payload - * }]); - * ``` + Thing.save({foo: 'bar'}).$promise.then(function(thing) { + console.log('That thing was saved in ' + thing.saveLatency + 'ms.'); + }); + ``` + * */ angular.module('ngResource', ['ng']). - factory('$resource', ['$http', '$q', function($http, $q) { - - var DEFAULT_ACTIONS = { - 'get': {method:'GET'}, - 'save': {method:'POST'}, - 'query': {method:'GET', isArray:true}, - 'remove': {method:'DELETE'}, - 'delete': {method:'DELETE'} - }; - var noop = angular.noop, - forEach = angular.forEach, - extend = angular.extend, - copy = angular.copy, - isFunction = angular.isFunction; - - /** - * We need our custom method because encodeURIComponent is too aggressive and doesn't follow - * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path - * segments: - * segment = *pchar - * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - * pct-encoded = "%" HEXDIG HEXDIG - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" - * / "*" / "+" / "," / ";" / "=" - */ - function encodeUriSegment(val) { - return encodeUriQuery(val, true). - replace(/%26/gi, '&'). - replace(/%3D/gi, '='). - replace(/%2B/gi, '+'); - } + info({ angularVersion: '1.8.2' }). + provider('$resource', function ResourceProvider() { + var PROTOCOL_AND_IPV6_REGEX = /^https?:\/\/\[[^\]]*][^/]*/; + var provider = this; /** - * This method is intended for encoding *key* or *value* parts of query component. We need a - * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't - * have to be encoded per http://tools.ietf.org/html/rfc3986: - * query = *( pchar / "/" / "?" ) - * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * pct-encoded = "%" HEXDIG HEXDIG - * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" - * / "*" / "+" / "," / ";" / "=" + * @ngdoc property + * @name $resourceProvider#defaults + * @description + * Object containing default options used when creating `$resource` instances. + * + * The default values satisfy a wide range of usecases, but you may choose to overwrite any of + * them to further customize your instances. The available properties are: + * + * - **stripTrailingSlashes** – `{boolean}` – If true, then the trailing slashes from any + * calculated URL will be stripped.
+ * (Defaults to true.) + * - **cancellable** – `{boolean}` – If true, the request made by a "non-instance" call will be + * cancelled (if not already completed) by calling `$cancelRequest()` on the call's return + * value. For more details, see {@link ngResource.$resource}. This can be overwritten per + * resource class or action.
+ * (Defaults to false.) + * - **actions** - `{Object.}` - A hash with default actions declarations. Actions are + * high-level methods corresponding to RESTful actions/methods on resources. An action may + * specify what HTTP method to use, what URL to hit, if the return value will be a single + * object or a collection (array) of objects etc. For more details, see + * {@link ngResource.$resource}. The actions can also be enhanced or overwritten per resource + * class.
+ * The default actions are: + * ```js + * { + * get: {method: 'GET'}, + * save: {method: 'POST'}, + * query: {method: 'GET', isArray: true}, + * remove: {method: 'DELETE'}, + * delete: {method: 'DELETE'} + * } + * ``` + * + * #### Example + * + * For example, you can specify a new `update` action that uses the `PUT` HTTP verb: + * + * ```js + * angular. + * module('myApp'). + * config(['$resourceProvider', function ($resourceProvider) { + * $resourceProvider.defaults.actions.update = { + * method: 'PUT' + * }; + * }]); + * ``` + * + * Or you can even overwrite the whole `actions` list and specify your own: + * + * ```js + * angular. + * module('myApp'). + * config(['$resourceProvider', function ($resourceProvider) { + * $resourceProvider.defaults.actions = { + * create: {method: 'POST'}, + * get: {method: 'GET'}, + * getAll: {method: 'GET', isArray:true}, + * update: {method: 'PUT'}, + * delete: {method: 'DELETE'} + * }; + * }); + * ``` + * */ - function encodeUriQuery(val, pctEncodeSpaces) { - return encodeURIComponent(val). - replace(/%40/gi, '@'). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); - } + this.defaults = { + // Strip slashes by default + stripTrailingSlashes: true, + + // Make non-instance requests cancellable (via `$cancelRequest()`) + cancellable: false, + + // Default actions configuration + actions: { + 'get': {method: 'GET'}, + 'save': {method: 'POST'}, + 'query': {method: 'GET', isArray: true}, + 'remove': {method: 'DELETE'}, + 'delete': {method: 'DELETE'} + } + }; - function Route(template, defaults) { - this.template = template; - this.defaults = defaults || {}; - this.urlParams = {}; - } + this.$get = ['$http', '$log', '$q', '$timeout', function($http, $log, $q, $timeout) { + + var noop = angular.noop, + forEach = angular.forEach, + extend = angular.extend, + copy = angular.copy, + isArray = angular.isArray, + isDefined = angular.isDefined, + isFunction = angular.isFunction, + isNumber = angular.isNumber, + encodeUriQuery = angular.$$encodeUriQuery, + encodeUriSegment = angular.$$encodeUriSegment; + + function Route(template, defaults) { + this.template = template; + this.defaults = extend({}, provider.defaults, defaults); + this.urlParams = {}; + } - Route.prototype = { - setUrlParams: function(config, params, actionUrl) { - var self = this, + Route.prototype = { + setUrlParams: function(config, params, actionUrl) { + var self = this, url = actionUrl || self.template, val, - encodedVal; + encodedVal, + protocolAndIpv6 = ''; - var urlParams = self.urlParams = {}; - forEach(url.split(/\W/), function(param){ - if (param === 'hasOwnProperty') { - throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name."); - } - if (!(new RegExp("^\\d+$").test(param)) && param && - (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) { - urlParams[param] = true; - } - }); - url = url.replace(/\\:/g, ':'); - - params = params || {}; - forEach(self.urlParams, function(_, urlParam){ - val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; - if (angular.isDefined(val) && val !== null) { - encodedVal = encodeUriSegment(val); - url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) { - return encodedVal + p1; - }); - } else { - url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match, - leadingSlashes, tail) { - if (tail.charAt(0) == '/') { - return tail; + var urlParams = self.urlParams = Object.create(null); + forEach(url.split(/\W/), function(param) { + if (param === 'hasOwnProperty') { + throw $resourceMinErr('badname', 'hasOwnProperty is not a valid parameter name.'); + } + if (!(new RegExp('^\\d+$').test(param)) && param && + (new RegExp('(^|[^\\\\]):' + param + '(\\W|$)').test(url))) { + urlParams[param] = { + isQueryParamValue: (new RegExp('\\?.*=:' + param + '(?:\\W|$)')).test(url) + }; + } + }); + url = url.replace(/\\:/g, ':'); + url = url.replace(PROTOCOL_AND_IPV6_REGEX, function(match) { + protocolAndIpv6 = match; + return ''; + }); + + params = params || {}; + forEach(self.urlParams, function(paramInfo, urlParam) { + val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam]; + if (isDefined(val) && val !== null) { + if (paramInfo.isQueryParamValue) { + encodedVal = encodeUriQuery(val, true); } else { - return leadingSlashes + tail; + encodedVal = encodeUriSegment(val); } - }); + url = url.replace(new RegExp(':' + urlParam + '(\\W|$)', 'g'), function(match, p1) { + return encodedVal + p1; + }); + } else { + url = url.replace(new RegExp('(/?):' + urlParam + '(\\W|$)', 'g'), function(match, + leadingSlashes, tail) { + if (tail.charAt(0) === '/') { + return tail; + } else { + return leadingSlashes + tail; + } + }); + } + }); + + // strip trailing slashes and set the url (unless this behavior is specifically disabled) + if (self.defaults.stripTrailingSlashes) { + url = url.replace(/\/+$/, '') || '/'; } - }); - // strip trailing slashes and set the url - url = url.replace(/\/+$/, '') || '/'; - // then replace collapse `/.` if found in the last URL path segment before the query - // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x` - url = url.replace(/\/\.(?=\w+($|\?))/, '.'); - // replace escaped `/\.` with `/.` - config.url = url.replace(/\/\\\./, '/.'); + // Collapse `/.` if found in the last URL path segment before the query. + // E.g. `http://url.com/id/.format?q=x` becomes `http://url.com/id.format?q=x`. + url = url.replace(/\/\.(?=\w+($|\?))/, '.'); + // Replace escaped `/\.` with `/.`. + // (If `\.` comes from a param value, it will be encoded as `%5C.`.) + config.url = protocolAndIpv6 + url.replace(/\/(\\|%5C)\./, '/.'); - // set params - delegate param encoding to $http - forEach(params, function(value, key){ - if (!self.urlParams[key]) { - config.params = config.params || {}; - config.params[key] = value; - } - }); - } - }; + // set params - delegate param encoding to $http + forEach(params, function(value, key) { + if (!self.urlParams[key]) { + config.params = config.params || {}; + config.params[key] = value; + } + }); + } + }; - function resourceFactory(url, paramDefaults, actions) { - var route = new Route(url); + function resourceFactory(url, paramDefaults, actions, options) { + var route = new Route(url, options); - actions = extend({}, DEFAULT_ACTIONS, actions); + actions = extend({}, provider.defaults.actions, actions); - function extractParams(data, actionParams){ - var ids = {}; - actionParams = extend({}, paramDefaults, actionParams); - forEach(actionParams, function(value, key){ - if (isFunction(value)) { value = value(); } - ids[key] = value && value.charAt && value.charAt(0) == '@' ? - lookupDottedPath(data, value.substr(1)) : value; - }); - return ids; - } + function extractParams(data, actionParams) { + var ids = {}; + actionParams = extend({}, paramDefaults, actionParams); + forEach(actionParams, function(value, key) { + if (isFunction(value)) { value = value(data); } + ids[key] = value && value.charAt && value.charAt(0) === '@' ? + lookupDottedPath(data, value.substr(1)) : value; + }); + return ids; + } + + function defaultResponseInterceptor(response) { + return response.resource; + } + + function Resource(value) { + shallowClearAndCopy(value || {}, this); + } + + Resource.prototype.toJSON = function() { + var data = extend({}, this); + delete data.$promise; + delete data.$resolved; + delete data.$cancelRequest; + return data; + }; - function defaultResponseInterceptor(response) { - return response.resource; - } + forEach(actions, function(action, name) { + var hasBody = action.hasBody === true || (action.hasBody !== false && /^(POST|PUT|PATCH)$/i.test(action.method)); + var numericTimeout = action.timeout; + var cancellable = isDefined(action.cancellable) ? + action.cancellable : route.defaults.cancellable; + + if (numericTimeout && !isNumber(numericTimeout)) { + $log.debug('ngResource:\n' + + ' Only numeric values are allowed as `timeout`.\n' + + ' Promises are not supported in $resource, because the same value would ' + + 'be used for multiple requests. If you are looking for a way to cancel ' + + 'requests, you should use the `cancellable` option.'); + delete action.timeout; + numericTimeout = null; + } - function Resource(value){ - shallowClearAndCopy(value || {}, this); - } + Resource[name] = function(a1, a2, a3, a4) { + var params = {}, data, onSuccess, onError; + + switch (arguments.length) { + case 4: + onError = a4; + onSuccess = a3; + // falls through + case 3: + case 2: + if (isFunction(a2)) { + if (isFunction(a1)) { + onSuccess = a1; + onError = a2; + break; + } - forEach(actions, function(action, name) { - var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method); - - Resource[name] = function(a1, a2, a3, a4) { - var params = {}, data, success, error; - - /* jshint -W086 */ /* (purposefully fall through case statements) */ - switch(arguments.length) { - case 4: - error = a4; - success = a3; - //fallthrough - case 3: - case 2: - if (isFunction(a2)) { - if (isFunction(a1)) { - success = a1; - error = a2; + onSuccess = a2; + onError = a3; + // falls through + } else { + params = a1; + data = a2; + onSuccess = a3; + break; + } + // falls through + case 1: + if (isFunction(a1)) onSuccess = a1; + else if (hasBody) data = a1; + else params = a1; break; - } - - success = a2; - error = a3; - //fallthrough - } else { - params = a1; - data = a2; - success = a3; - break; + case 0: break; + default: + throw $resourceMinErr('badargs', + 'Expected up to 4 arguments [params, data, success, error], got {0} arguments', + arguments.length); } - case 1: - if (isFunction(a1)) success = a1; - else if (hasBody) data = a1; - else params = a1; - break; - case 0: break; - default: - throw $resourceMinErr('badargs', - "Expected up to 4 arguments [params, data, success, error], got {0} arguments", - arguments.length); - } - /* jshint +W086 */ /* (purposefully fall through case statements) */ - - var isInstanceCall = this instanceof Resource; - var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data)); - var httpConfig = {}; - var responseInterceptor = action.interceptor && action.interceptor.response || - defaultResponseInterceptor; - var responseErrorInterceptor = action.interceptor && action.interceptor.responseError || - undefined; - - forEach(action, function(value, key) { - if (key != 'params' && key != 'isArray' && key != 'interceptor') { - httpConfig[key] = copy(value); - } - }); - if (hasBody) httpConfig.data = data; - route.setUrlParams(httpConfig, - extend({}, extractParams(data, action.params || {}), params), - action.url); - - var promise = $http(httpConfig).then(function (response) { - var data = response.data, - promise = value.$promise; - - if (data) { - // Need to convert action.isArray to boolean in case it is undefined - // jshint -W018 - if (angular.isArray(data) !== (!!action.isArray)) { - throw $resourceMinErr('badcfg', - 'Error in resource configuration. Expected ' + - 'response to contain an {0} but got an {1}', - action.isArray ? 'array' : 'object', - angular.isArray(data) ? 'array' : 'object'); + var isInstanceCall = this instanceof Resource; + var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data)); + var httpConfig = {}; + var requestInterceptor = action.interceptor && action.interceptor.request || undefined; + var requestErrorInterceptor = action.interceptor && action.interceptor.requestError || + undefined; + var responseInterceptor = action.interceptor && action.interceptor.response || + defaultResponseInterceptor; + var responseErrorInterceptor = action.interceptor && action.interceptor.responseError || + $q.reject; + var successCallback = onSuccess ? function(val) { + onSuccess(val, response.headers, response.status, response.statusText); + } : undefined; + var errorCallback = onError || undefined; + var timeoutDeferred; + var numericTimeoutPromise; + var response; + + forEach(action, function(value, key) { + switch (key) { + default: + httpConfig[key] = copy(value); + break; + case 'params': + case 'isArray': + case 'interceptor': + case 'cancellable': + break; } - // jshint +W018 - if (action.isArray) { - value.length = 0; - forEach(data, function (item) { - if (typeof item === "object") { - value.push(new Resource(item)); - } else { - // Valid JSON values may be string literals, and these should not be converted - // into objects. These items will not have access to the Resource prototype - // methods, but unfortunately there - value.push(item); - } - }); - } else { - shallowClearAndCopy(data, value); - value.$promise = promise; + }); + + if (!isInstanceCall && cancellable) { + timeoutDeferred = $q.defer(); + httpConfig.timeout = timeoutDeferred.promise; + + if (numericTimeout) { + numericTimeoutPromise = $timeout(timeoutDeferred.resolve, numericTimeout); } } - value.$resolved = true; + if (hasBody) httpConfig.data = data; + route.setUrlParams(httpConfig, + extend({}, extractParams(data, action.params || {}), params), + action.url); + + // Start the promise chain + var promise = $q. + resolve(httpConfig). + then(requestInterceptor). + catch(requestErrorInterceptor). + then($http); + + promise = promise.then(function(resp) { + var data = resp.data; + + if (data) { + // Need to convert action.isArray to boolean in case it is undefined + if (isArray(data) !== (!!action.isArray)) { + throw $resourceMinErr('badcfg', + 'Error in resource configuration for action `{0}`. Expected response to ' + + 'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object', + isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url); + } + if (action.isArray) { + value.length = 0; + forEach(data, function(item) { + if (typeof item === 'object') { + value.push(new Resource(item)); + } else { + // Valid JSON values may be string literals, and these should not be converted + // into objects. These items will not have access to the Resource prototype + // methods, but unfortunately there + value.push(item); + } + }); + } else { + var promise = value.$promise; // Save the promise + shallowClearAndCopy(data, value); + value.$promise = promise; // Restore the promise + } + } - response.resource = value; + resp.resource = value; + response = resp; + return responseInterceptor(resp); + }, function(rejectionOrResponse) { + rejectionOrResponse.resource = value; + response = rejectionOrResponse; + return responseErrorInterceptor(rejectionOrResponse); + }); - return response; - }, function(response) { - value.$resolved = true; + promise = promise['finally'](function() { + value.$resolved = true; + if (!isInstanceCall && cancellable) { + value.$cancelRequest = noop; + $timeout.cancel(numericTimeoutPromise); + timeoutDeferred = numericTimeoutPromise = httpConfig.timeout = null; + } + }); - (error||noop)(response); + // Run the `success`/`error` callbacks, but do not let them affect the returned promise. + promise.then(successCallback, errorCallback); - return $q.reject(response); - }); + if (!isInstanceCall) { + // we are creating instance / collection + // - set the initial promise + // - return the instance / collection + value.$promise = promise; + value.$resolved = false; + if (cancellable) value.$cancelRequest = cancelRequest; - promise = promise.then( - function(response) { - var value = responseInterceptor(response); - (success||noop)(value, response.headers); - return value; - }, - responseErrorInterceptor); - - if (!isInstanceCall) { - // we are creating instance / collection - // - set the initial promise - // - return the instance / collection - value.$promise = promise; - value.$resolved = false; - - return value; - } + return value; + } - // instance call - return promise; - }; + // instance call + return promise; + function cancelRequest(value) { + promise.catch(noop); + if (timeoutDeferred !== null) { + timeoutDeferred.resolve(value); + } + } + }; - Resource.prototype['$' + name] = function(params, success, error) { - if (isFunction(params)) { - error = success; success = params; params = {}; - } - var result = Resource[name].call(this, params, this, success, error); - return result.$promise || result; - }; - }); - Resource.bind = function(additionalParamDefaults){ - return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); - }; + Resource.prototype['$' + name] = function(params, success, error) { + if (isFunction(params)) { + error = success; success = params; params = {}; + } + var result = Resource[name].call(this, params, this, success, error); + return result.$promise || result; + }; + }); - return Resource; - } + return Resource; + } - return resourceFactory; - }]); + return resourceFactory; + }]; + }); })(window, window.angular); diff --git a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-resource.min.js b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-resource.min.js index cf7729224..6bd87c051 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-resource.min.js +++ b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-resource.min.js @@ -1,13 +1,15 @@ /* - AngularJS v1.2.23-build.379+sha.cb18343 - (c) 2010-2014 Google, Inc. http://angularjs.org + AngularJS v1.8.2 + (c) 2010-2020 Google LLC. http://angularjs.org License: MIT */ -(function(H,a,A){'use strict';function D(p,g){g=g||{};a.forEach(g,function(a,c){delete g[c]});for(var c in p)!p.hasOwnProperty(c)||"$"===c.charAt(0)&&"$"===c.charAt(1)||(g[c]=p[c]);return g}var v=a.$$minErr("$resource"),C=/^(\.[a-zA-Z_$][0-9a-zA-Z_$]*)+$/;a.module("ngResource",["ng"]).factory("$resource",["$http","$q",function(p,g){function c(a,c){this.template=a;this.defaults=c||{};this.urlParams={}}function t(n,w,l){function r(h,d){var e={};d=x({},w,d);s(d,function(b,d){u(b)&&(b=b());var k;if(b&& -b.charAt&&"@"==b.charAt(0)){k=h;var a=b.substr(1);if(null==a||""===a||"hasOwnProperty"===a||!C.test("."+a))throw v("badmember",a);for(var a=a.split("."),f=0,c=a.length;f */ - /* global -ngRouteModule */ -var ngRouteModule = angular.module('ngRoute', ['ng']). - provider('$route', $RouteProvider); +/* global -ngRouteModule */ +var ngRouteModule = angular. + module('ngRoute', []). + info({ angularVersion: '1.8.2' }). + provider('$route', $RouteProvider). + // Ensure `$route` will be instantiated in time to capture the initial `$locationChangeSuccess` + // event (unless explicitly disabled). This is necessary in case `ngView` is included in an + // asynchronously loaded template. + run(instantiateRoute); +var $routeMinErr = angular.$$minErr('ngRoute'); +var isEagerInstantiationEnabled; + /** * @ngdoc provider * @name $routeProvider - * @function + * @this * * @description * * Used for configuring routes. * * ## Example - * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. + * See {@link ngRoute.$route#examples $route} for an example of configuring and using `ngRoute`. * * ## Dependencies * Requires the {@link ngRoute `ngRoute`} module to be installed. */ -function $RouteProvider(){ +function $RouteProvider() { + isArray = angular.isArray; + isObject = angular.isObject; + isDefined = angular.isDefined; + noop = angular.noop; + function inherit(parent, extra) { - return angular.extend(new (angular.extend(function() {}, {prototype:parent}))(), extra); + return angular.extend(Object.create(parent), extra); } var routes = {}; @@ -75,12 +167,12 @@ function $RouteProvider(){ * * Object properties: * - * - `controller` – `{(string|function()=}` – Controller fn that should be associated with + * - `controller` – `{(string|Function)=}` – Controller fn that should be associated with * newly created scope or the name of a {@link angular.Module#controller registered * controller} if passed as a string. - * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be - * published to scope under the `controllerAs` name. - * - `template` – `{string=|function()=}` – html template as a string or a function that + * - `controllerAs` – `{string=}` – An identifier name for a reference to the controller. + * If present, the controller will be published to scope under the `controllerAs` name. + * - `template` – `{(string|Function)=}` – html template as a string or a function that * returns an html template as a string which should be used by {@link * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. * This property takes precedence over `templateUrl`. @@ -90,7 +182,9 @@ function $RouteProvider(){ * - `{Array.}` - route parameters extracted from the current * `$location.path()` by applying the current route * - * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html + * One of `template` or `templateUrl` is required. + * + * - `templateUrl` – `{(string|Function)=}` – path or function that returns a path to an html * template that should be used by {@link ngRoute.directive:ngView ngView}. * * If `templateUrl` is a function, it will be called with the following parameters: @@ -98,25 +192,39 @@ function $RouteProvider(){ * - `{Array.}` - route parameters extracted from the current * `$location.path()` by applying the current route * - * - `resolve` - `{Object.=}` - An optional map of dependencies which should + * One of `templateUrl` or `template` is required. + * + * - `resolve` - `{Object.=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, the router * will wait for them all to be resolved or one to be rejected before the controller is * instantiated. * If all the promises are resolved successfully, the values of the resolved promises are * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is * fired. If any of the promises are rejected the - * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object - * is: + * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. + * For easier access to the resolved dependencies from the template, the `resolve` map will + * be available on the scope of the route, under `$resolve` (by default) or a custom name + * specified by the `resolveAs` property (see below). This can be particularly useful, when + * working with {@link angular.Module#component components} as route templates.
+ *
+ * **Note:** If your scope already contains a property with this name, it will be hidden + * or overwritten. Make sure, you specify an appropriate name for this property, that + * does not collide with other properties on the scope. + *
+ * The map object is: * * - `key` – `{string}`: a name of a dependency to be injected into the controller. - * - `factory` - `{string|function}`: If `string` then it is an alias for a service. + * - `factory` - `{string|Function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link auto.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is * resolved before its value is injected into the controller. Be aware that * `ngRoute.$routeParams` will still refer to the previous route within these resolve * functions. Use `$route.current.params` to access the new route parameters, instead. * - * - `redirectTo` – {(string|function())=} – value to update + * - `resolveAs` - `{string=}` - The name under which the `resolve` map will be available on + * the scope of the route. If omitted, defaults to `$resolve`. + * + * - `redirectTo` – `{(string|Function)=}` – value to update * {@link ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: @@ -127,15 +235,50 @@ function $RouteProvider(){ * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used - * to update `$location.path()` and `$location.search()`. + * to update `$location.url()`. If the function throws an error, no further processing will + * take place and the {@link ngRoute.$route#$routeChangeError $routeChangeError} event will + * be fired. * - * - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()` + * Routes that specify `redirectTo` will not have their controllers, template functions + * or resolves called, the `$location` will be changed to the redirect url and route + * processing will stop. The exception to this is if the `redirectTo` is a function that + * returns `undefined`. In this case the route transition occurs as though there was no + * redirection. + * + * - `resolveRedirectTo` – `{Function=}` – a function that will (eventually) return the value + * to update {@link ng.$location $location} URL with and trigger route redirection. In + * contrast to `redirectTo`, dependencies can be injected into `resolveRedirectTo` and the + * return value can be either a string or a promise that will be resolved to a string. + * + * Similar to `redirectTo`, if the return value is `undefined` (or a promise that gets + * resolved to `undefined`), no redirection takes place and the route transition occurs as + * though there was no redirection. + * + * If the function throws an error or the returned promise gets rejected, no further + * processing will take place and the + * {@link ngRoute.$route#$routeChangeError $routeChangeError} event will be fired. + * + * `redirectTo` takes precedence over `resolveRedirectTo`, so specifying both on the same + * route definition, will cause the latter to be ignored. + * + * - `[reloadOnUrl=true]` - `{boolean=}` - reload route when any part of the URL changes + * (including the path) even if the new URL maps to the same route. + * + * If the option is set to `false` and the URL in the browser changes, but the new URL maps + * to the same route, then a `$routeUpdate` event is broadcasted on the root scope (without + * reloading the route). + * + * - `[reloadOnSearch=true]` - `{boolean=}` - reload route when only `$location.search()` * or `$location.hash()` changes. * - * If the option is set to `false` and url in the browser changes, then - * `$routeUpdate` event is broadcasted on the root scope. + * If the option is set to `false` and the URL in the browser changes, then a `$routeUpdate` + * event is broadcasted on the root scope (without reloading the route). * - * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive + *
+ * **Note:** This option has no effect if `reloadOnUrl` is set to `false`. + *
+ * + * - `[caseInsensitiveMatch=false]` - `{boolean=}` - match routes without being case sensitive * * If the option is set to `true`, then the particular route can be matched without being * case sensitive @@ -146,67 +289,48 @@ function $RouteProvider(){ * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { + //copy original route object to preserve params inherited from proto chain + var routeCopy = shallowCopy(route); + if (angular.isUndefined(routeCopy.reloadOnUrl)) { + routeCopy.reloadOnUrl = true; + } + if (angular.isUndefined(routeCopy.reloadOnSearch)) { + routeCopy.reloadOnSearch = true; + } + if (angular.isUndefined(routeCopy.caseInsensitiveMatch)) { + routeCopy.caseInsensitiveMatch = this.caseInsensitiveMatch; + } routes[path] = angular.extend( - {reloadOnSearch: true}, - route, - path && pathRegExp(path, route) + routeCopy, + {originalPath: path}, + path && routeToRegExp(path, routeCopy) ); // create redirection for trailing slashes if (path) { - var redirectPath = (path[path.length-1] == '/') - ? path.substr(0, path.length-1) - : path +'/'; + var redirectPath = (path[path.length - 1] === '/') + ? path.substr(0, path.length - 1) + : path + '/'; routes[redirectPath] = angular.extend( - {redirectTo: path}, - pathRegExp(redirectPath, route) + {originalPath: path, redirectTo: path}, + routeToRegExp(redirectPath, routeCopy) ); } return this; }; - /** - * @param path {string} path - * @param opts {Object} options - * @return {?Object} - * - * @description - * Normalizes the given path, returning a regular expression - * and the original path. - * - * Inspired by pathRexp in visionmedia/express/lib/utils.js. - */ - function pathRegExp(path, opts) { - var insensitive = opts.caseInsensitiveMatch, - ret = { - originalPath: path, - regexp: path - }, - keys = ret.keys = []; - - path = path - .replace(/([().])/g, '\\$1') - .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option){ - var optional = option === '?' ? option : null; - var star = option === '*' ? option : null; - keys.push({ name: key, optional: !!optional }); - slash = slash || ''; - return '' - + (optional ? '' : slash) - + '(?:' - + (optional ? slash : '') - + (star && '(.+?)' || '([^/]+)') - + (optional || '') - + ')' - + (optional || ''); - }) - .replace(/([\/$\*])/g, '\\$1'); - - ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); - return ret; - } + /** + * @ngdoc property + * @name $routeProvider#caseInsensitiveMatch + * @description + * + * A boolean property indicating if routes defined + * using this provider should be matched using a case insensitive + * algorithm. Defaults to `false`. + */ + this.caseInsensitiveMatch = false; /** * @ngdoc method @@ -216,24 +340,69 @@ function $RouteProvider(){ * Sets route definition that will be used on route change when no other route definition * is matched. * - * @param {Object} params Mapping information to be assigned to `$route.current`. + * @param {Object|string} params Mapping information to be assigned to `$route.current`. + * If called with a string, the value maps to `redirectTo`. * @returns {Object} self */ this.otherwise = function(params) { + if (typeof params === 'string') { + params = {redirectTo: params}; + } this.when(null, params); return this; }; + /** + * @ngdoc method + * @name $routeProvider#eagerInstantiationEnabled + * @kind function + * + * @description + * Call this method as a setter to enable/disable eager instantiation of the + * {@link ngRoute.$route $route} service upon application bootstrap. You can also call it as a + * getter (i.e. without any arguments) to get the current value of the + * `eagerInstantiationEnabled` flag. + * + * Instantiating `$route` early is necessary for capturing the initial + * {@link ng.$location#$locationChangeStart $locationChangeStart} event and navigating to the + * appropriate route. Usually, `$route` is instantiated in time by the + * {@link ngRoute.ngView ngView} directive. Yet, in cases where `ngView` is included in an + * asynchronously loaded template (e.g. in another directive's template), the directive factory + * might not be called soon enough for `$route` to be instantiated _before_ the initial + * `$locationChangeSuccess` event is fired. Eager instantiation ensures that `$route` is always + * instantiated in time, regardless of when `ngView` will be loaded. + * + * The default value is true. + * + * **Note**:
+ * You may want to disable the default behavior when unit-testing modules that depend on + * `ngRoute`, in order to avoid an unexpected request for the default route's template. + * + * @param {boolean=} enabled - If provided, update the internal `eagerInstantiationEnabled` flag. + * + * @returns {*} The current value of the `eagerInstantiationEnabled` flag if used as a getter or + * itself (for chaining) if used as a setter. + */ + isEagerInstantiationEnabled = true; + this.eagerInstantiationEnabled = function eagerInstantiationEnabled(enabled) { + if (isDefined(enabled)) { + isEagerInstantiationEnabled = enabled; + return this; + } + + return isEagerInstantiationEnabled; + }; + this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', - '$http', - '$templateCache', + '$templateRequest', '$sce', - function($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) { + '$browser', + function($rootScope, $location, $routeParams, $q, $injector, $templateRequest, $sce, $browser) { /** * @ngdoc service @@ -244,7 +413,7 @@ function $RouteProvider(){ * @property {Object} current Reference to the current route definition. * The route definition contains: * - * - `controller`: The controller constructor as define in route definition. + * - `controller`: The controller constructor as defined in the route definition. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for * controller instantiation. The `locals` contain * the resolved values of the `resolve` map. Additionally the `locals` also contain: @@ -252,6 +421,10 @@ function $RouteProvider(){ * - `$scope` - The current route scope. * - `$template` - The current route template HTML. * + * The `locals` will be assigned to the route scope's `$resolve` property. You can override + * the property name, using `resolveAs` in the route definition. See + * {@link ngRoute.$routeProvider $routeProvider} for more info. + * * @property {Object} routes Object with all route configuration Objects as its properties. * * @description @@ -270,9 +443,6 @@ function $RouteProvider(){ * This example shows how changing the URL hash causes the `$route` to match a route against the * URL, and the `ngView` pulls in the partial. * - * Note that this example is using {@link ng.directive:script inlined templates} - * to get it working on jsfiddle as well. - * * * @@ -317,12 +487,12 @@ function $RouteProvider(){ * }) * * .controller('BookController', function($scope, $routeParams) { - * $scope.name = "BookController"; + * $scope.name = 'BookController'; * $scope.params = $routeParams; * }) * * .controller('ChapterController', function($scope, $routeParams) { - * $scope.name = "ChapterController"; + * $scope.name = 'ChapterController'; * $scope.params = $routeParams; * }) * @@ -355,15 +525,15 @@ function $RouteProvider(){ * it('should load and compile correct template', function() { * element(by.linkText('Moby: Ch1')).click(); * var content = element(by.css('[ng-view]')).getText(); - * expect(content).toMatch(/controller\: ChapterController/); - * expect(content).toMatch(/Book Id\: Moby/); - * expect(content).toMatch(/Chapter Id\: 1/); + * expect(content).toMatch(/controller: ChapterController/); + * expect(content).toMatch(/Book Id: Moby/); + * expect(content).toMatch(/Chapter Id: 1/); * * element(by.partialLinkText('Scarlet')).click(); * * content = element(by.css('[ng-view]')).getText(); - * expect(content).toMatch(/controller\: BookController/); - * expect(content).toMatch(/Book Id\: Scarlet/); + * expect(content).toMatch(/controller: BookController/); + * expect(content).toMatch(/Book Id: Scarlet/); * }); * * @@ -380,6 +550,10 @@ function $RouteProvider(){ * defined in `resolve` route property. Once all of the dependencies are resolved * `$routeChangeSuccess` is fired. * + * The route change (and the `$location` change that triggered it) can be prevented + * by calling `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} + * for more details about event object. + * * @param {Object} angularEvent Synthetic event object. * @param {Route} next Future route information. * @param {Route} current Current route information. @@ -390,7 +564,9 @@ function $RouteProvider(){ * @name $route#$routeChangeSuccess * @eventType broadcast on root scope * @description - * Broadcasted after a route dependencies are resolved. + * Broadcasted after a route change has happened successfully. + * The `resolve` dependencies are now available in the `current.locals` property. + * * {@link ngRoute.directive:ngView ngView} listens for the directive * to instantiate the controller and render the view. * @@ -405,12 +581,14 @@ function $RouteProvider(){ * @name $route#$routeChangeError * @eventType broadcast on root scope * @description - * Broadcasted if any of the resolve promises are rejected. + * Broadcasted if a redirection function fails or any redirection or resolve promises are + * rejected. * * @param {Object} angularEvent Synthetic event object * @param {Route} current Current route information. * @param {Route} previous Previous route information. - * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. + * @param {Route} rejection The thrown error or the rejection reason of the promise. Usually + * the rejection reason is the error that caused the promise to get rejected. */ /** @@ -418,12 +596,17 @@ function $RouteProvider(){ * @name $route#$routeUpdate * @eventType broadcast on root scope * @description + * Broadcasted if the same instance of a route (including template, controller instance, + * resolved dependencies, etc.) is being reused. This can happen if either `reloadOnSearch` or + * `reloadOnUrl` has been set to `false`. * - * The `reloadOnSearch` property has been set to false, and we are reusing the same - * instance of the Controller. + * @param {Object} angularEvent Synthetic event object + * @param {Route} current Current/previous route information. */ var forceReload = false, + preparedRoute, + preparedRouteIsUpdateOnly, $route = { routes: routes, @@ -436,15 +619,52 @@ function $RouteProvider(){ * {@link ng.$location $location} hasn't changed. * * As a result of that, {@link ngRoute.directive:ngView ngView} - * creates new scope, reinstantiates the controller. + * creates new scope and reinstantiates the controller. */ reload: function() { forceReload = true; - $rootScope.$evalAsync(updateRoute); + + var fakeLocationEvent = { + defaultPrevented: false, + preventDefault: function fakePreventDefault() { + this.defaultPrevented = true; + forceReload = false; + } + }; + + $rootScope.$evalAsync(function() { + prepareRoute(fakeLocationEvent); + if (!fakeLocationEvent.defaultPrevented) commitRoute(); + }); + }, + + /** + * @ngdoc method + * @name $route#updateParams + * + * @description + * Causes `$route` service to update the current URL, replacing + * current route parameters with those specified in `newParams`. + * Provided property names that match the route's path segment + * definitions will be interpolated into the location's path, while + * remaining properties will be treated as query params. + * + * @param {!Object} newParams mapping of URL parameter names to values + */ + updateParams: function(newParams) { + if (this.current && this.current.$$route) { + newParams = angular.extend({}, this.current.params, newParams); + $location.path(interpolate(this.current.$$route.originalPath, newParams)); + // interpolate modifies newParams, only query params are left + $location.search(newParams); + } else { + throw $routeMinErr('norout', 'Tried updating route with no current route'); + } } }; - $rootScope.$on('$locationChangeSuccess', updateRoute); + $rootScope.$on('$locationChangeStart', prepareRoute); + $rootScope.$on('$locationChangeSuccess', commitRoute); return $route; @@ -473,9 +693,7 @@ function $RouteProvider(){ for (var i = 1, len = m.length; i < len; ++i) { var key = keys[i - 1]; - var val = 'string' == typeof m[i] - ? decodeURIComponent(m[i]) - : m[i]; + var val = m[i]; if (key && val) { params[key.name] = val; @@ -484,81 +702,171 @@ function $RouteProvider(){ return params; } - function updateRoute() { - var next = parseRoute(), - last = $route.current; - - if (next && last && next.$$route === last.$$route - && angular.equals(next.pathParams, last.pathParams) - && !next.reloadOnSearch && !forceReload) { - last.params = next.params; - angular.copy(last.params, $routeParams); - $rootScope.$broadcast('$routeUpdate', last); - } else if (next || last) { - forceReload = false; - $rootScope.$broadcast('$routeChangeStart', next, last); - $route.current = next; - if (next) { - if (next.redirectTo) { - if (angular.isString(next.redirectTo)) { - $location.path(interpolate(next.redirectTo, next.params)).search(next.params) - .replace(); - } else { - $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) - .replace(); - } + function prepareRoute($locationEvent) { + var lastRoute = $route.current; + + preparedRoute = parseRoute(); + preparedRouteIsUpdateOnly = isNavigationUpdateOnly(preparedRoute, lastRoute); + + if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) { + if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) { + if ($locationEvent) { + $locationEvent.preventDefault(); } } + } + } - $q.when(next). - then(function() { - if (next) { - var locals = angular.extend({}, next.resolve), - template, templateUrl; + function commitRoute() { + var lastRoute = $route.current; + var nextRoute = preparedRoute; - angular.forEach(locals, function(value, key) { - locals[key] = angular.isString(value) ? - $injector.get(value) : $injector.invoke(value); + if (preparedRouteIsUpdateOnly) { + lastRoute.params = nextRoute.params; + angular.copy(lastRoute.params, $routeParams); + $rootScope.$broadcast('$routeUpdate', lastRoute); + } else if (nextRoute || lastRoute) { + forceReload = false; + $route.current = nextRoute; + + var nextRoutePromise = $q.resolve(nextRoute); + + $browser.$$incOutstandingRequestCount('$route'); + + nextRoutePromise. + then(getRedirectionData). + then(handlePossibleRedirection). + then(function(keepProcessingRoute) { + return keepProcessingRoute && nextRoutePromise. + then(resolveLocals). + then(function(locals) { + // after route change + if (nextRoute === $route.current) { + if (nextRoute) { + nextRoute.locals = locals; + angular.copy(nextRoute.params, $routeParams); + } + $rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute); + } }); + }).catch(function(error) { + if (nextRoute === $route.current) { + $rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error); + } + }).finally(function() { + // Because `commitRoute()` is called from a `$rootScope.$evalAsync` block (see + // `$locationWatch`), this `$$completeOutstandingRequest()` call will not cause + // `outstandingRequestCount` to hit zero. This is important in case we are redirecting + // to a new route which also requires some asynchronous work. - if (angular.isDefined(template = next.template)) { - if (angular.isFunction(template)) { - template = template(next.params); - } - } else if (angular.isDefined(templateUrl = next.templateUrl)) { - if (angular.isFunction(templateUrl)) { - templateUrl = templateUrl(next.params); - } - templateUrl = $sce.getTrustedResourceUrl(templateUrl); - if (angular.isDefined(templateUrl)) { - next.loadedTemplateUrl = templateUrl; - template = $http.get(templateUrl, {cache: $templateCache}). - then(function(response) { return response.data; }); - } - } - if (angular.isDefined(template)) { - locals['$template'] = template; - } - return $q.all(locals); + $browser.$$completeOutstandingRequest(noop, '$route'); + }); + } + } + + function getRedirectionData(route) { + var data = { + route: route, + hasRedirection: false + }; + + if (route) { + if (route.redirectTo) { + if (angular.isString(route.redirectTo)) { + data.path = interpolate(route.redirectTo, route.params); + data.search = route.params; + data.hasRedirection = true; + } else { + var oldPath = $location.path(); + var oldSearch = $location.search(); + var newUrl = route.redirectTo(route.pathParams, oldPath, oldSearch); + + if (angular.isDefined(newUrl)) { + data.url = newUrl; + data.hasRedirection = true; } - }). - // after route change - then(function(locals) { - if (next == $route.current) { - if (next) { - next.locals = locals; - angular.copy(next.params, $routeParams); + } + } else if (route.resolveRedirectTo) { + return $q. + resolve($injector.invoke(route.resolveRedirectTo)). + then(function(newUrl) { + if (angular.isDefined(newUrl)) { + data.url = newUrl; + data.hasRedirection = true; } - $rootScope.$broadcast('$routeChangeSuccess', next, last); - } - }, function(error) { - if (next == $route.current) { - $rootScope.$broadcast('$routeChangeError', next, last, error); - } - }); + + return data; + }); + } } + + return data; } + function handlePossibleRedirection(data) { + var keepProcessingRoute = true; + + if (data.route !== $route.current) { + keepProcessingRoute = false; + } else if (data.hasRedirection) { + var oldUrl = $location.url(); + var newUrl = data.url; + + if (newUrl) { + $location. + url(newUrl). + replace(); + } else { + newUrl = $location. + path(data.path). + search(data.search). + replace(). + url(); + } + + if (newUrl !== oldUrl) { + // Exit out and don't process current next value, + // wait for next location change from redirect + keepProcessingRoute = false; + } + } + + return keepProcessingRoute; + } + + function resolveLocals(route) { + if (route) { + var locals = angular.extend({}, route.resolve); + angular.forEach(locals, function(value, key) { + locals[key] = angular.isString(value) ? + $injector.get(value) : + $injector.invoke(value, null, null, key); + }); + var template = getTemplateFor(route); + if (angular.isDefined(template)) { + locals['$template'] = template; + } + return $q.all(locals); + } + } + + function getTemplateFor(route) { + var template, templateUrl; + if (angular.isDefined(template = route.template)) { + if (angular.isFunction(template)) { + template = template(route.params); + } + } else if (angular.isDefined(templateUrl = route.templateUrl)) { + if (angular.isFunction(templateUrl)) { + templateUrl = templateUrl(route.params); + } + if (angular.isDefined(templateUrl)) { + route.loadedTemplateUrl = $sce.valueOf(templateUrl); + template = $templateRequest(templateUrl); + } + } + return template; + } /** * @returns {Object} the current active route, by matching it against the URL @@ -578,16 +886,39 @@ function $RouteProvider(){ return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } + /** + * @param {Object} newRoute - The new route configuration (as returned by `parseRoute()`). + * @param {Object} oldRoute - The previous route configuration (as returned by `parseRoute()`). + * @returns {boolean} Whether this is an "update-only" navigation, i.e. the URL maps to the same + * route and it can be reused (based on the config and the type of change). + */ + function isNavigationUpdateOnly(newRoute, oldRoute) { + // IF this is not a forced reload + return !forceReload + // AND both `newRoute`/`oldRoute` are defined + && newRoute && oldRoute + // AND they map to the same Route Definition Object + && (newRoute.$$route === oldRoute.$$route) + // AND `reloadOnUrl` is disabled + && (!newRoute.reloadOnUrl + // OR `reloadOnSearch` is disabled + || (!newRoute.reloadOnSearch + // AND both routes have the same path params + && angular.equals(newRoute.pathParams, oldRoute.pathParams) + ) + ); + } + /** * @returns {string} interpolation of the redirect path with the parameters */ function interpolate(string, params) { var result = []; - angular.forEach((string||'').split(':'), function(segment, i) { + angular.forEach((string || '').split(':'), function(segment, i) { if (i === 0) { result.push(segment); } else { - var segmentMatch = segment.match(/(\w+)(.*)/); + var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); @@ -599,6 +930,14 @@ function $RouteProvider(){ }]; } +instantiateRoute.$inject = ['$injector']; +function instantiateRoute($injector) { + if (isEagerInstantiationEnabled) { + // Instantiate `$route` + $injector.get('$route'); + } +} + ngRouteModule.provider('$routeParams', $RouteParamsProvider); @@ -606,6 +945,7 @@ ngRouteModule.provider('$routeParams', $RouteParamsProvider); * @ngdoc service * @name $routeParams * @requires $route + * @this * * @description * The `$routeParams` service allows you to retrieve the current set of route parameters. @@ -632,7 +972,7 @@ ngRouteModule.provider('$routeParams', $RouteParamsProvider); * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then - * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} + * $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'} * ``` */ function $RouteParamsProvider() { @@ -649,7 +989,6 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory); * @restrict ECA * * @description - * # Overview * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the @@ -658,8 +997,10 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory); * Requires the {@link ngRoute `ngRoute`} module to be installed. * * @animations - * enter - animation is used to bring new content into the browser. - * leave - animation is used to animate existing content away. + * | Animation | Occurs | + * |----------------------------------|-------------------------------------| + * | {@link ng.$animate#enter enter} | when the new element is inserted to the DOM | + * | {@link ng.$animate#leave leave} | when the old element is removed from to the DOM | * * The enter and leave animation occur concurrently. * @@ -695,7 +1036,6 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory);
$location.path() = {{main.$location.path()}}
$route.current.templateUrl = {{main.$route.current.templateUrl}}
$route.current.params = {{main.$route.current.params}}
-
$route.current.scope.name = {{main.$route.current.scope.name}}
$routeParams = {{main.$routeParams}}
@@ -719,7 +1059,6 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory); .view-animate-container { position:relative; height:100px!important; - position:relative; background:white; border:1px solid black; height:40px; @@ -731,7 +1070,6 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory); } .view-animate.ng-enter, .view-animate.ng-leave { - -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; display:block; @@ -773,21 +1111,20 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory); controllerAs: 'chapter' }); - // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }]) .controller('MainCtrl', ['$route', '$routeParams', '$location', - function($route, $routeParams, $location) { + function MainCtrl($route, $routeParams, $location) { this.$route = $route; this.$location = $location; this.$routeParams = $routeParams; }]) - .controller('BookCtrl', ['$routeParams', function($routeParams) { - this.name = "BookCtrl"; + .controller('BookCtrl', ['$routeParams', function BookCtrl($routeParams) { + this.name = 'BookCtrl'; this.params = $routeParams; }]) - .controller('ChapterCtrl', ['$routeParams', function($routeParams) { - this.name = "ChapterCtrl"; + .controller('ChapterCtrl', ['$routeParams', function ChapterCtrl($routeParams) { + this.name = 'ChapterCtrl'; this.params = $routeParams; }]); @@ -797,15 +1134,15 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory); it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('[ng-view]')).getText(); - expect(content).toMatch(/controller\: ChapterCtrl/); - expect(content).toMatch(/Book Id\: Moby/); - expect(content).toMatch(/Chapter Id\: 1/); + expect(content).toMatch(/controller: ChapterCtrl/); + expect(content).toMatch(/Book Id: Moby/); + expect(content).toMatch(/Chapter Id: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('[ng-view]')).getText(); - expect(content).toMatch(/controller\: BookCtrl/); - expect(content).toMatch(/Book Id\: Scarlet/); + expect(content).toMatch(/controller: BookCtrl/); + expect(content).toMatch(/Book Id: Scarlet/); }); @@ -820,7 +1157,7 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory); * Emitted every time the ngView content is reloaded. */ ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; -function ngViewFactory( $route, $anchorScroll, $animate) { +function ngViewFactory($route, $anchorScroll, $animate) { return { restrict: 'ECA', terminal: true, @@ -829,7 +1166,7 @@ function ngViewFactory( $route, $anchorScroll, $animate) { link: function(scope, $element, attr, ctrl, $transclude) { var currentScope, currentElement, - previousElement, + previousLeaveAnimation, autoScrollExp = attr.autoscroll, onloadExp = attr.onload || ''; @@ -837,19 +1174,20 @@ function ngViewFactory( $route, $anchorScroll, $animate) { update(); function cleanupLastView() { - if(previousElement) { - previousElement.remove(); - previousElement = null; + if (previousLeaveAnimation) { + $animate.cancel(previousLeaveAnimation); + previousLeaveAnimation = null; } - if(currentScope) { + + if (currentScope) { currentScope.$destroy(); currentScope = null; } - if(currentElement) { - $animate.leave(currentElement, function() { - previousElement = null; + if (currentElement) { + previousLeaveAnimation = $animate.leave(currentElement); + previousLeaveAnimation.done(function(response) { + if (response !== false) previousLeaveAnimation = null; }); - previousElement = currentElement; currentElement = null; } } @@ -869,8 +1207,8 @@ function ngViewFactory( $route, $anchorScroll, $animate) { // function is called before linking the content, which would apply child // directives to non existing elements. var clone = $transclude(newScope, function(clone) { - $animate.enter(clone, null, currentElement || $element, function onNgViewEnter () { - if (angular.isDefined(autoScrollExp) + $animate.enter(clone, null, currentElement || $element).done(function onNgViewEnter(response) { + if (response !== false && angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } @@ -917,6 +1255,7 @@ function ngViewFillContentFactory($compile, $controller, $route) { $element.data('$ngControllerController', controller); $element.children().data('$ngControllerController', controller); } + scope[current.resolveAs || '$resolve'] = locals; link(scope); } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-route.min.js b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-route.min.js index aef1fd601..ad7a18fb0 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-route.min.js +++ b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-route.min.js @@ -1,14 +1,17 @@ /* - AngularJS v1.2.16 - (c) 2010-2014 Google, Inc. http://angularjs.org + AngularJS v1.8.2 + (c) 2010-2020 Google LLC. http://angularjs.org License: MIT */ -(function(n,e,A){'use strict';function x(s,g,k){return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",link:function(a,c,b,f,w){function y(){p&&(p.remove(),p=null);h&&(h.$destroy(),h=null);l&&(k.leave(l,function(){p=null}),p=l,l=null)}function v(){var b=s.current&&s.current.locals;if(e.isDefined(b&&b.$template)){var b=a.$new(),d=s.current;l=w(b,function(d){k.enter(d,null,l||c,function(){!e.isDefined(t)||t&&!a.$eval(t)||g()});y()});h=d.scope=b;h.$emit("$viewContentLoaded");h.$eval(u)}else y()} -var h,l,p,t=b.autoscroll,u=b.onload||"";a.$on("$routeChangeSuccess",v);v()}}}function z(e,g,k){return{restrict:"ECA",priority:-400,link:function(a,c){var b=k.current,f=b.locals;c.html(f.$template);var w=e(c.contents());b.controller&&(f.$scope=a,f=g(b.controller,f),b.controllerAs&&(a[b.controllerAs]=f),c.data("$ngControllerController",f),c.children().data("$ngControllerController",f));w(a)}}}n=e.module("ngRoute",["ng"]).provider("$route",function(){function s(a,c){return e.extend(new (e.extend(function(){}, -{prototype:a})),c)}function g(a,e){var b=e.caseInsensitiveMatch,f={originalPath:a,regexp:a},k=f.keys=[];a=a.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)([\?\*])?/g,function(a,e,b,c){a="?"===c?c:null;c="*"===c?c:null;k.push({name:b,optional:!!a});e=e||"";return""+(a?"":e)+"(?:"+(a?e:"")+(c&&"(.+?)"||"([^/]+)")+(a||"")+")"+(a||"")}).replace(/([\/$\*])/g,"\\$1");f.regexp=RegExp("^"+a+"$",b?"i":"");return f}var k={};this.when=function(a,c){k[a]=e.extend({reloadOnSearch:!0},c,a&&g(a,c));if(a){var b= -"/"==a[a.length-1]?a.substr(0,a.length-1):a+"/";k[b]=e.extend({redirectTo:a},g(b,c))}return this};this.otherwise=function(a){this.when(null,a);return this};this.$get=["$rootScope","$location","$routeParams","$q","$injector","$http","$templateCache","$sce",function(a,c,b,f,g,n,v,h){function l(){var d=p(),m=r.current;if(d&&m&&d.$$route===m.$$route&&e.equals(d.pathParams,m.pathParams)&&!d.reloadOnSearch&&!u)m.params=d.params,e.copy(m.params,b),a.$broadcast("$routeUpdate",m);else if(d||m)u=!1,a.$broadcast("$routeChangeStart", -d,m),(r.current=d)&&d.redirectTo&&(e.isString(d.redirectTo)?c.path(t(d.redirectTo,d.params)).search(d.params).replace():c.url(d.redirectTo(d.pathParams,c.path(),c.search())).replace()),f.when(d).then(function(){if(d){var a=e.extend({},d.resolve),c,b;e.forEach(a,function(d,c){a[c]=e.isString(d)?g.get(d):g.invoke(d)});e.isDefined(c=d.template)?e.isFunction(c)&&(c=c(d.params)):e.isDefined(b=d.templateUrl)&&(e.isFunction(b)&&(b=b(d.params)),b=h.getTrustedResourceUrl(b),e.isDefined(b)&&(d.loadedTemplateUrl= -b,c=n.get(b,{cache:v}).then(function(a){return a.data})));e.isDefined(c)&&(a.$template=c);return f.all(a)}}).then(function(c){d==r.current&&(d&&(d.locals=c,e.copy(d.params,b)),a.$broadcast("$routeChangeSuccess",d,m))},function(c){d==r.current&&a.$broadcast("$routeChangeError",d,m,c)})}function p(){var a,b;e.forEach(k,function(f,k){var q;if(q=!b){var g=c.path();q=f.keys;var l={};if(f.regexp)if(g=f.regexp.exec(g)){for(var h=1,p=g.length;h/g,">")}function z(a){for(;a;){if(a.nodeType===s.Node.ELEMENT_NODE)for(var d=a.attributes,c=0,b=d.length;c"))},end:function(a){a=q(a);c||!0!==m[a]||!0===r[a]||(b(""));a==c&&(c=!1)},chars:function(a){c|| +b(K(a))}}};I=s.Node.prototype.contains||function(a){return!!(this.compareDocumentPosition(a)&16)};var Q=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,u=/([^#-~ |!])/g,r=h("area,br,col,hr,img,wbr"),x=h("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),p=h("rp,rt"),n=g({},p,x),x=g({},x,h("address,article,aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul")),p=g({},p,h("a,abbr,acronym,b,bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small,span,strike,strong,sub,sup,time,tt,u,var")), +l=h("circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,stop,svg,switch,text,title,tspan"),w=h("script,style"),m=g({},r,x,p,n),N=h("background,cite,href,longdesc,src,xlink:href,xml:base"),n=h("abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,valign,value,vspace,width"), +p=h("accent-height,accumulate,additive,alphabetic,arabic-form,ascent,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan", +!0),L=g({},N,p,n),M=function(a,d){function c(b){b=""+b;try{var c=(new a.DOMParser).parseFromString(b,"text/html").body;c.firstChild.remove();return c}catch(d){}}var b;try{b=!!c("")}catch(f){b=!1}if(b)return c;if(!d||!d.implementation)throw C("noinert");b=d.implementation.createHTMLDocument("inert");var e=(b.documentElement||b.getDocumentElement()).querySelector("body");return function(a){e.innerHTML=a;d.documentMode&&z(e);return e}}(s,s.document)}).info({angularVersion:"1.8.2"}); +e.module("ngSanitize").filter("linky",["$sanitize",function(h){var g=/((s?ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,t=/^mailto:/i,q=e.$$minErr("linky"),s=e.isDefined,z=e.isFunction,v=e.isObject,y=e.isString;return function(f,e,u){function r(e){e&&l.push(O(e))}function x(f,h){var g,a=p(f);l.push("');r(h);l.push("")}if(null== +f||""===f)return f;if(!y(f))throw q("notstring",f);for(var p=z(u)?u:v(u)?function(){return u}:function(){return{}},n=f,l=[],w,m;f=n.match(g);)w=f[0],f[2]||f[4]||(w=(f[3]?"http://":"mailto:")+w),m=f.index,r(n.substr(0,m)),x(w,f[0].replace(t,"")),n=n.substring(m+f[0].length);r(n);return h(l.join(""))}}])})(window,window.angular); +//# sourceMappingURL=angular-sanitize.min.js.map diff --git a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-sanitize.min.js.map b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-sanitize.min.js.map new file mode 100644 index 000000000..031cbd6f8 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular-sanitize.min.js.map @@ -0,0 +1,8 @@ +{ +"version":3, +"file":"angular-sanitize.min.js", +"lineCount":16, +"mappings":"A;;;;;aAKC,SAAQ,CAACA,CAAD,CAASC,CAAT,CAAkB,CAmqB3BC,QAASA,EAAY,CAACC,CAAD,CAAQ,CAC3B,IAAIC,EAAM,EACGC,EAAAC,CAAmBF,CAAnBE,CAAwBC,CAAxBD,CACbH,MAAA,CAAaA,CAAb,CACA,OAAOC,EAAAI,KAAA,CAAS,EAAT,CAJoB,CAtpB7B,IAAIC,EAAkBR,CAAAS,SAAA,CAAiB,WAAjB,CAAtB,CACIC,CADJ,CAEIC,CAFJ,CAGIC,CAHJ,CAIIC,CAJJ,CAKIC,CALJ,CAMIC,CANJ,CAOIT,CAPJ,CAQIU,CARJ,CASIC,CATJ,CAUIb,CAqpBJJ,EAAAkB,OAAA,CAAe,YAAf,CAA6B,EAA7B,CAAAC,SAAA,CACY,WADZ,CA1hBAC,QAA0B,EAAG,CAkQ3BC,QAASA,EAAW,CAACC,CAAD,CAAMC,CAAN,CAAqB,CACvC,MAAOC,EAAA,CAAWF,CAAAG,MAAA,CAAU,GAAV,CAAX,CAA2BF,CAA3B,CADgC,CAIzCC,QAASA,EAAU,CAACE,CAAD,CAAQH,CAAR,CAAuB,CAAA,IACpCI,EAAM,EAD8B,CAC1BC,CACd,KAAKA,CAAL,CAAS,CAAT,CAAYA,CAAZ,CAAgBF,CAAAG,OAAhB,CAA8BD,CAAA,EAA9B,CACED,CAAA,CAAIJ,CAAA,CAAgBR,CAAA,CAAUW,CAAA,CAAME,CAAN,CAAV,CAAhB,CAAsCF,CAAA,CAAME,CAAN,CAA1C,CAAA,CAAsD,CAAA,CAExD,OAAOD,EALiC,CAQ1CG,QAASA,EAAa,CAACC,CAAD,CAAcC,CAAd,CAA2B,CAC3CA,CAAJ,EAAmBA,CAAAH,OAAnB,EACElB,CAAA,CAAOoB,CAAP,CAAoBP,CAAA,CAAWQ,CAAX,CAApB,CAF6C,CAgIjDC,QAASA,EAAS,CAACC,CAAD,CAAQ,CAExB,IADA,IAAIC,EAAM,EAAV,CACSP,EAAI,CADb,CACgBQ,EAAKF,CAAAL,OAArB,CAAmCD,CAAnC,CAAuCQ,CAAvC,CAA2CR,CAAA,EAA3C,CAAgD,CAC9C,IAAIS,EAAOH,CAAA,CAAMN,CAAN,CACXO,EAAA,CAAIE,CAAAC,KAAJ,CAAA,CAAiBD,CAAAE,MAF6B,CAIhD,MAAOJ,EANiB,CAiB1BK,QAASA,EAAc,CAACD,CAAD,CAAQ,CAC7B,MAAOA,EAAAE,QAAA,CACG,IADH,CACS,OADT,CAAAA,QAAA,CAEGC,CAFH,CAE0B,QAAQ,CAACH,CAAD,CAAQ,CAC7C,IAAII;AAAKJ,CAAAK,WAAA,CAAiB,CAAjB,CACLC,EAAAA,CAAMN,CAAAK,WAAA,CAAiB,CAAjB,CACV,OAAO,IAAP,EAAgC,IAAhC,EAAiBD,CAAjB,CAAsB,KAAtB,GAA0CE,CAA1C,CAAgD,KAAhD,EAA0D,KAA1D,EAAqE,GAHxB,CAF1C,CAAAJ,QAAA,CAOGK,CAPH,CAO4B,QAAQ,CAACP,CAAD,CAAQ,CAC/C,MAAO,IAAP,CAAcA,CAAAK,WAAA,CAAiB,CAAjB,CAAd,CAAoC,GADW,CAP5C,CAAAH,QAAA,CAUG,IAVH,CAUS,MAVT,CAAAA,QAAA,CAWG,IAXH,CAWS,MAXT,CADsB,CAgF/BM,QAASA,EAAkB,CAACC,CAAD,CAAO,CAChC,IAAA,CAAOA,CAAP,CAAA,CAAa,CACX,GAAIA,CAAAC,SAAJ,GAAsBlD,CAAAmD,KAAAC,aAAtB,CAEE,IADA,IAAIjB,EAAQc,CAAAI,WAAZ,CACSxB,EAAI,CADb,CACgByB,EAAInB,CAAAL,OAApB,CAAkCD,CAAlC,CAAsCyB,CAAtC,CAAyCzB,CAAA,EAAzC,CAA8C,CAC5C,IAAI0B,EAAWpB,CAAA,CAAMN,CAAN,CAAf,CACI2B,EAAWD,CAAAhB,KAAAkB,YAAA,EACf,IAAiB,WAAjB,GAAID,CAAJ,EAAoE,CAApE,GAAgCA,CAAAE,YAAA,CAAqB,MAArB,CAA6B,CAA7B,CAAhC,CACET,CAAAU,oBAAA,CAAyBJ,CAAzB,CAEA,CADA1B,CAAA,EACA,CAAAyB,CAAA,EAN0C,CAYhD,CADIM,CACJ,CADeX,CAAAY,WACf,GACEb,CAAA,CAAmBY,CAAnB,CAGFX,EAAA,CAAOa,CAAA,CAAiB,aAAjB,CAAgCb,CAAhC,CAnBI,CADmB,CAwBlCa,QAASA,EAAgB,CAACC,CAAD,CAAWd,CAAX,CAAiB,CAExC,IAAIW,EAAWX,CAAA,CAAKc,CAAL,CACf,IAAIH,CAAJ,EAAgB3C,CAAA+C,KAAA,CAAkBf,CAAlB,CAAwBW,CAAxB,CAAhB,CACE,KAAMnD,EAAA,CAAgB,QAAhB;AAA2FwC,CAAAgB,UAA3F,EAA6GhB,CAAAiB,UAA7G,CAAN,CAEF,MAAON,EANiC,CAtgB1C,IAAIO,EAAsB,CAAA,CAA1B,CACIC,EAAa,CAAA,CAEjB,KAAAC,KAAA,CAAY,CAAC,eAAD,CAAkB,QAAQ,CAACC,CAAD,CAAgB,CACpDH,CAAA,CAAsB,CAAA,CAClBC,EAAJ,EACExD,CAAA,CAAO2D,CAAP,CAAsBC,CAAtB,CAEF,OAAO,SAAQ,CAACC,CAAD,CAAO,CACpB,IAAIrE,EAAM,EACVc,EAAA,CAAWuD,CAAX,CAAiBpE,CAAA,CAAmBD,CAAnB,CAAwB,QAAQ,CAACsE,CAAD,CAAMC,CAAN,CAAe,CAC9D,MAAO,CAAC,UAAAC,KAAA,CAAgBN,CAAA,CAAcI,CAAd,CAAmBC,CAAnB,CAAhB,CADsD,CAA/C,CAAjB,CAGA,OAAOvE,EAAAI,KAAA,CAAS,EAAT,CALa,CAL8B,CAA1C,CA6CZ,KAAAqE,UAAA,CAAiBC,QAAQ,CAACD,CAAD,CAAY,CACnC,MAAI9D,EAAA,CAAU8D,CAAV,CAAJ,EACET,CACO,CADMS,CACN,CAAA,IAFT,EAIST,CAL0B,CAwDrC,KAAAW,iBAAA,CAAwBC,QAAQ,CAACC,CAAD,CAAW,CACpCd,CAAL,GACMrD,CAAA,CAAQmE,CAAR,CAOJ,GANEA,CAMF,CANa,CAACC,aAAcD,CAAf,CAMb,EAHAlD,CAAA,CAAcyC,CAAd,CAA2BS,CAAAT,YAA3B,CAGA,CAFAzC,CAAA,CAAcoD,CAAd,CAA4BF,CAAAG,iBAA5B,CAEA,CADArD,CAAA,CAAcwC,CAAd,CAA6BU,CAAAG,iBAA7B,CACA,CAAArD,CAAA,CAAcwC,CAAd,CAA6BU,CAAAC,aAA7B,CARF,CAWA,OAAO,KAZkC,CA6C3C,KAAAG,cAAA,CAAqBC,QAAQ,CAACnD,CAAD,CAAQ,CAC9BgC,CAAL,EACEvD,CAAA,CAAO2E,CAAP,CAAmB9D,CAAA,CAAWU,CAAX,CAAkB,CAAA,CAAlB,CAAnB,CAEF,OAAO,KAJ4B,CAWrCxB,EAAA,CAAOV,CAAAU,KACPC,EAAA,CAASX,CAAAW,OACTC;CAAA,CAAUZ,CAAAY,QACVC,EAAA,CAAUb,CAAAa,QACVC,EAAA,CAAYd,CAAAc,UACZC,EAAA,CAAYf,CAAAuF,YACZjF,EAAA,CAAON,CAAAM,KAEPW,EAAA,CA0KAuE,QAAuB,CAAChB,CAAD,CAAOiB,CAAP,CAAgB,CACxB,IAAb,GAAIjB,CAAJ,EAA8BkB,IAAAA,EAA9B,GAAqBlB,CAArB,CACEA,CADF,CACS,EADT,CAE2B,QAF3B,GAEW,MAAOA,EAFlB,GAGEA,CAHF,CAGS,EAHT,CAGcA,CAHd,CAMA,KAAImB,EAAmBC,CAAA,CAAoBpB,CAApB,CACvB,IAAKmB,CAAAA,CAAL,CAAuB,MAAO,EAG9B,KAAIE,EAAe,CACnB,GAAG,CACD,GAAqB,CAArB,GAAIA,CAAJ,CACE,KAAMrF,EAAA,CAAgB,QAAhB,CAAN,CAEFqF,CAAA,EAGArB,EAAA,CAAOmB,CAAAG,UACPH,EAAA,CAAmBC,CAAA,CAAoBpB,CAApB,CARlB,CAAH,MASSA,CATT,GASkBmB,CAAAG,UATlB,CAYA,KADI9C,CACJ,CADW2C,CAAA/B,WACX,CAAOZ,CAAP,CAAA,CAAa,CACX,OAAQA,CAAAC,SAAR,EACE,KAAK,CAAL,CACEwC,CAAAM,MAAA,CAAc/C,CAAAgD,SAAAxC,YAAA,EAAd,CAA2CvB,CAAA,CAAUe,CAAAI,WAAV,CAA3C,CACA,MACF,MAAK,CAAL,CACEqC,CAAAvF,MAAA,CAAc8C,CAAAiD,YAAd,CALJ,CASA,IAAItC,CACJ,IAAM,EAAAA,CAAA,CAAWX,CAAAY,WAAX,CAAN,GACwB,CAIjBD,GAJDX,CAAAC,SAICU,EAHH8B,CAAAS,IAAA,CAAYlD,CAAAgD,SAAAxC,YAAA,EAAZ,CAGGG,CADLA,CACKA,CADME,CAAA,CAAiB,aAAjB,CAAgCb,CAAhC,CACNW,CAAAA,CAAAA,CALP,EAMI,IAAA,CAAmB,IAAnB,EAAOA,CAAP,CAAA,CAAyB,CACvBX,CAAA;AAAOa,CAAA,CAAiB,YAAjB,CAA+Bb,CAA/B,CACP,IAAIA,CAAJ,GAAa2C,CAAb,CAA+B,KAC/BhC,EAAA,CAAWE,CAAA,CAAiB,aAAjB,CAAgCb,CAAhC,CACW,EAAtB,GAAIA,CAAAC,SAAJ,EACEwC,CAAAS,IAAA,CAAYlD,CAAAgD,SAAAxC,YAAA,EAAZ,CALqB,CAU7BR,CAAA,CAAOW,CA3BI,CA8Bb,IAAA,CAAQX,CAAR,CAAe2C,CAAA/B,WAAf,CAAA,CACE+B,CAAAQ,YAAA,CAA6BnD,CAA7B,CAvDmC,CAzKvC5C,EAAA,CA8QAgG,QAA+B,CAACjG,CAAD,CAAMkG,CAAN,CAAoB,CACjD,IAAIC,EAAuB,CAAA,CAA3B,CACIC,EAAM7F,CAAA,CAAKP,CAAL,CAAUA,CAAAqG,KAAV,CACV,OAAO,CACLT,MAAOA,QAAQ,CAACU,CAAD,CAAMvE,CAAN,CAAa,CAC1BuE,CAAA,CAAM1F,CAAA,CAAU0F,CAAV,CACDH,EAAAA,CAAL,EAA6BI,CAAA,CAAgBD,CAAhB,CAA7B,GACEH,CADF,CACyBG,CADzB,CAGKH,EAAL,EAAoD,CAAA,CAApD,GAA6BhC,CAAA,CAAcmC,CAAd,CAA7B,GACEF,CAAA,CAAI,GAAJ,CAcA,CAbAA,CAAA,CAAIE,CAAJ,CAaA,CAZA7F,CAAA,CAAQsB,CAAR,CAAe,QAAQ,CAACK,CAAD,CAAQoE,CAAR,CAAa,CAClC,IAAIC,EAAO7F,CAAA,CAAU4F,CAAV,CAAX,CACIjC,EAAmB,KAAnBA,GAAW+B,CAAX/B,EAAqC,KAArCA,GAA4BkC,CAA5BlC,EAAyD,YAAzDA,GAAgDkC,CAC3B,EAAA,CAAzB,GAAItB,CAAA,CAAWsB,CAAX,CAAJ,EACsB,CAAA,CADtB,GACGC,CAAA,CAASD,CAAT,CADH,EAC8B,CAAAP,CAAA,CAAa9D,CAAb,CAAoBmC,CAApB,CAD9B,GAEE6B,CAAA,CAAI,GAAJ,CAIA,CAHAA,CAAA,CAAII,CAAJ,CAGA,CAFAJ,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAI/D,CAAA,CAAeD,CAAf,CAAJ,CACA,CAAAgE,CAAA,CAAI,GAAJ,CANF,CAHkC,CAApC,CAYA,CAAAA,CAAA,CAAI,GAAJ,CAfF,CAL0B,CADvB,CAwBLL,IAAKA,QAAQ,CAACO,CAAD,CAAM,CACjBA,CAAA,CAAM1F,CAAA,CAAU0F,CAAV,CACDH,EAAL,EAAoD,CAAA,CAApD,GAA6BhC,CAAA,CAAcmC,CAAd,CAA7B,EAAkF,CAAA,CAAlF,GAA4DvB,CAAA,CAAauB,CAAb,CAA5D,GACEF,CAAA,CAAI,IAAJ,CAEA,CADAA,CAAA,CAAIE,CAAJ,CACA,CAAAF,CAAA,CAAI,GAAJ,CAHF,CAMIE,EAAJ,EAAWH,CAAX,GACEA,CADF,CACyB,CAAA,CADzB,CARiB,CAxBd,CAoCLpG,MAAOA,QAAQ,CAACA,CAAD,CAAQ,CAChBoG,CAAL;AACEC,CAAA,CAAI/D,CAAA,CAAetC,CAAf,CAAJ,CAFmB,CApClB,CAH0C,CA5QnDc,EAAA,CAAejB,CAAAmD,KAAA4D,UAAAC,SAAf,EAA8D,QAAQ,CAACC,CAAD,CAAM,CAE1E,MAAO,CAAG,EAAA,IAAAC,wBAAA,CAA6BD,CAA7B,CAAA,CAAoC,EAApC,CAFgE,CA5KjD,KAkLvBtE,EAAwB,iCAlLD,CAoLzBI,EAA0B,cApLD,CA6LvBoC,EAAe7D,CAAA,CAAY,wBAAZ,CA7LQ,CAiMvB6F,EAA8B7F,CAAA,CAAY,gDAAZ,CAjMP,CAkMvB8F,EAA+B9F,CAAA,CAAY,OAAZ,CAlMR,CAmMvB+F,EAAyBzG,CAAA,CAAO,EAAP,CACewG,CADf,CAEeD,CAFf,CAnMF,CAwMvBG,EAAgB1G,CAAA,CAAO,EAAP,CAAWuG,CAAX,CAAwC7F,CAAA,CAAY,qKAAZ,CAAxC,CAxMO,CA6MvBiG,EAAiB3G,CAAA,CAAO,EAAP,CAAWwG,CAAX,CAAyC9F,CAAA,CAAY,2JAAZ,CAAzC,CA7MM;AAqNvBkD,EAAclD,CAAA,CAAY,wNAAZ,CArNS,CA0NvBqF,EAAkBrF,CAAA,CAAY,cAAZ,CA1NK,CA4NvBiD,EAAgB3D,CAAA,CAAO,EAAP,CACeuE,CADf,CAEemC,CAFf,CAGeC,CAHf,CAIeF,CAJf,CA5NO,CAmOvBP,EAAWxF,CAAA,CAAY,uDAAZ,CAnOY,CAqOvBkG,EAAYlG,CAAA,CAAY,kTAAZ,CArOW;AA6OvBmG,EAAWnG,CAAA,CAAY,guCAAZ;AAcoE,CAAA,CAdpE,CA7OY,CA6PvBiE,EAAa3E,CAAA,CAAO,EAAP,CACekG,CADf,CAEeW,CAFf,CAGeD,CAHf,CA7PU,CAyRvB3B,EAAqE,QAAQ,CAAC7F,CAAD,CAAS0H,CAAT,CAAmB,CAoBlGC,QAASA,EAA6B,CAAClD,CAAD,CAAO,CAG3CA,CAAA,CAAO,mBAAP,CAA6BA,CAC7B,IAAI,CACF,IAAImD,EAAOC,CAAA,IAAI7H,CAAA8H,UAAJD,iBAAA,CAAuCpD,CAAvC,CAA6C,WAA7C,CAAAmD,KACXA,EAAA/D,WAAAkE,OAAA,EACA,OAAOH,EAHL,CAIF,MAAOI,CAAP,CAAU,EAR+B,CAnBzC,IAAA,CAYF,IAAI,CACF,CAAA,CAAO,CAAE,CAAAL,CAAA,CAA8B,EAA9B,CADP,CAEF,MAAOK,CAAP,CAAU,CACV,CAAA,CAAO,CAAA,CADG,CAdd,GAAI,CAAJ,CACE,MAAOL,EAGT,IAAKD,CAAAA,CAAL,EAAkBO,CAAAP,CAAAO,eAAlB,CACE,KAAMxH,EAAA,CAAgB,SAAhB,CAAN,CAEEyH,CAAAA,CAAgBR,CAAAO,eAAAE,mBAAA,CAA2C,OAA3C,CACpB,KAAIvC,EAAmBwC,CAACF,CAAAG,gBAADD,EAAkCF,CAAAI,mBAAA,EAAlCF,eAAA,CAAoF,MAApF,CACvB,OAuBAG,SAA0C,CAAC9D,CAAD,CAAO,CAC/CmB,CAAAG,UAAA,CAA6BtB,CAIzBiD,EAAAc,aAAJ,EACExF,CAAA,CAAmB4C,CAAnB,CAGF,OAAOA,EATwC,CAjCiD,CAA5B,CA4CrE5F,CA5CqE,CA4C7DA,CAAA0H,SA5C6D,CAzR7C,CA0hB7B,CAAAe,KAAA,CAEQ,CAAEC,eAAgB,OAAlB,CAFR,CAmIAzI;CAAAkB,OAAA,CAAe,YAAf,CAAAwH,OAAA,CAAoC,OAApC,CAA6C,CAAC,WAAD,CAAc,QAAQ,CAACC,CAAD,CAAY,CAAA,IACzEC,EACE,2FAFuE,CAGzEC,EAAgB,WAHyD,CAKzEC,EAAc9I,CAAAS,SAAA,CAAiB,OAAjB,CAL2D,CAMzEK,EAAYd,CAAAc,UAN6D,CAOzEiI,EAAa/I,CAAA+I,WAP4D,CAQzEC,EAAWhJ,CAAAgJ,SAR8D,CASzEC,EAAWjJ,CAAAiJ,SAEf,OAAO,SAAQ,CAACC,CAAD,CAAOC,CAAP,CAAe/F,CAAf,CAA2B,CA6BxCgG,QAASA,EAAO,CAACF,CAAD,CAAO,CAChBA,CAAL,EAGA1E,CAAAgC,KAAA,CAAUvG,CAAA,CAAaiJ,CAAb,CAAV,CAJqB,CAOvBG,QAASA,EAAO,CAACC,CAAD,CAAMJ,CAAN,CAAY,CAAA,IACtBvC,CADsB,CACjB4C,EAAiBC,CAAA,CAAaF,CAAb,CAC1B9E,EAAAgC,KAAA,CAAU,KAAV,CAEA,KAAKG,CAAL,GAAY4C,EAAZ,CACE/E,CAAAgC,KAAA,CAAUG,CAAV,CAAgB,IAAhB,CAAuB4C,CAAA,CAAe5C,CAAf,CAAvB,CAA6C,IAA7C,CAGE,EAAA7F,CAAA,CAAUqI,CAAV,CAAJ,EAA2B,QAA3B,EAAuCI,EAAvC,EACE/E,CAAAgC,KAAA,CAAU,UAAV,CACU2C,CADV,CAEU,IAFV,CAIF3E,EAAAgC,KAAA,CAAU,QAAV,CACU8C,CAAA7G,QAAA,CAAY,IAAZ,CAAkB,QAAlB,CADV,CAEU,IAFV,CAGA2G,EAAA,CAAQF,CAAR,CACA1E,EAAAgC,KAAA,CAAU,MAAV,CAjB0B,CAnC5B,GAAY,IAAZ;AAAI0C,CAAJ,EAA6B,EAA7B,GAAoBA,CAApB,CAAiC,MAAOA,EACxC,IAAK,CAAAD,CAAA,CAASC,CAAT,CAAL,CAAqB,KAAMJ,EAAA,CAAY,WAAZ,CAA8DI,CAA9D,CAAN,CAYrB,IAVA,IAAIM,EACFT,CAAA,CAAW3F,CAAX,CAAA,CAAyBA,CAAzB,CACA4F,CAAA,CAAS5F,CAAT,CAAA,CAAuBqG,QAA4B,EAAG,CAAC,MAAOrG,EAAR,CAAtD,CACAsG,QAAiC,EAAG,CAAC,MAAO,EAAR,CAHtC,CAMIC,EAAMT,CANV,CAOI1E,EAAO,EAPX,CAQI8E,CARJ,CASI1H,CACJ,CAAQgI,CAAR,CAAgBD,CAAAC,MAAA,CAAUhB,CAAV,CAAhB,CAAA,CAEEU,CAQA,CARMM,CAAA,CAAM,CAAN,CAQN,CANKA,CAAA,CAAM,CAAN,CAML,EANkBA,CAAA,CAAM,CAAN,CAMlB,GALEN,CAKF,EALSM,CAAA,CAAM,CAAN,CAAA,CAAW,SAAX,CAAuB,SAKhC,EAL6CN,CAK7C,EAHA1H,CAGA,CAHIgI,CAAAC,MAGJ,CAFAT,CAAA,CAAQO,CAAAG,OAAA,CAAW,CAAX,CAAclI,CAAd,CAAR,CAEA,CADAyH,CAAA,CAAQC,CAAR,CAAaM,CAAA,CAAM,CAAN,CAAAnH,QAAA,CAAiBoG,CAAjB,CAAgC,EAAhC,CAAb,CACA,CAAAc,CAAA,CAAMA,CAAAI,UAAA,CAAcnI,CAAd,CAAkBgI,CAAA,CAAM,CAAN,CAAA/H,OAAlB,CAERuH,EAAA,CAAQO,CAAR,CACA,OAAOhB,EAAA,CAAUnE,CAAAjE,KAAA,CAAU,EAAV,CAAV,CA3BiC,CAXmC,CAAlC,CAA7C,CA/yB2B,CAA1B,CAAD,CAq3BGR,MAr3BH,CAq3BWA,MAAAC,QAr3BX;", +"sources":["angular-sanitize.js"], +"names":["window","angular","sanitizeText","chars","buf","htmlSanitizeWriter","writer","noop","join","$sanitizeMinErr","$$minErr","bind","extend","forEach","isArray","isDefined","lowercase","nodeContains","htmlParser","module","provider","$SanitizeProvider","stringToMap","str","lowercaseKeys","arrayToMap","split","items","obj","i","length","addElementsTo","elementsMap","newElements","attrToMap","attrs","map","ii","attr","name","value","encodeEntities","replace","SURROGATE_PAIR_REGEXP","hi","charCodeAt","low","NON_ALPHANUMERIC_REGEXP","stripCustomNsAttrs","node","nodeType","Node","ELEMENT_NODE","attributes","l","attrNode","attrName","toLowerCase","lastIndexOf","removeAttributeNode","nextNode","firstChild","getNonDescendant","propName","call","outerHTML","outerText","hasBeenInstantiated","svgEnabled","$get","$$sanitizeUri","validElements","svgElements","html","uri","isImage","test","enableSvg","this.enableSvg","addValidElements","this.addValidElements","elements","htmlElements","voidElements","htmlVoidElements","addValidAttrs","this.addValidAttrs","validAttrs","$$lowercase","htmlParserImpl","handler","undefined","inertBodyElement","getInertBodyElement","mXSSAttempts","innerHTML","start","nodeName","textContent","end","removeChild","htmlSanitizeWriterImpl","uriValidator","ignoreCurrentElement","out","push","tag","blockedElements","key","lkey","uriAttrs","prototype","contains","arg","compareDocumentPosition","optionalEndTagBlockElements","optionalEndTagInlineElements","optionalEndTagElements","blockElements","inlineElements","htmlAttrs","svgAttrs","document","getInertBodyElement_DOMParser","body","parseFromString","DOMParser","remove","e","implementation","inertDocument","createHTMLDocument","querySelector","documentElement","getDocumentElement","getInertBodyElement_InertDocument","documentMode","info","angularVersion","filter","$sanitize","LINKY_URL_REGEXP","MAILTO_REGEXP","linkyMinErr","isFunction","isObject","isString","text","target","addText","addLink","url","linkAttributes","attributesFn","getAttributesObject","getEmptyAttributesObject","raw","match","index","substr","substring"] +} diff --git a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular.js b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular.js index 2f26beed6..e67a6906e 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular.js +++ b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/angular.js @@ -1,15 +1,76 @@ /** - * @license AngularJS v1.2.16 - * (c) 2010-2014 Google, Inc. http://angularjs.org + * @license AngularJS v1.8.2 + * (c) 2010-2020 Google LLC. http://angularjs.org * License: MIT */ -(function(window, document, undefined) {'use strict'; +(function(window) {'use strict'; + +/* exported + minErrConfig, + errorHandlingConfig, + isValidObjectMaxDepth +*/ + +var minErrConfig = { + objectMaxDepth: 5, + urlErrorParamsEnabled: true +}; + +/** + * @ngdoc function + * @name angular.errorHandlingConfig + * @module ng + * @kind function + * + * @description + * Configure several aspects of error handling in AngularJS if used as a setter or return the + * current configuration if used as a getter. The following options are supported: + * + * - **objectMaxDepth**: The maximum depth to which objects are traversed when stringified for error messages. + * + * Omitted or undefined options will leave the corresponding configuration values unchanged. + * + * @param {Object=} config - The configuration object. May only contain the options that need to be + * updated. Supported keys: + * + * * `objectMaxDepth` **{Number}** - The max depth for stringifying objects. Setting to a + * non-positive or non-numeric value, removes the max depth limit. + * Default: 5 + * + * * `urlErrorParamsEnabled` **{Boolean}** - Specifies whether the generated error url will + * contain the parameters of the thrown error. Disabling the parameters can be useful if the + * generated error url is very long. + * + * Default: true. When used without argument, it returns the current value. + */ +function errorHandlingConfig(config) { + if (isObject(config)) { + if (isDefined(config.objectMaxDepth)) { + minErrConfig.objectMaxDepth = isValidObjectMaxDepth(config.objectMaxDepth) ? config.objectMaxDepth : NaN; + } + if (isDefined(config.urlErrorParamsEnabled) && isBoolean(config.urlErrorParamsEnabled)) { + minErrConfig.urlErrorParamsEnabled = config.urlErrorParamsEnabled; + } + } else { + return minErrConfig; + } +} + +/** + * @private + * @param {Number} maxDepth + * @return {boolean} + */ +function isValidObjectMaxDepth(maxDepth) { + return isNumber(maxDepth) && maxDepth > 0; +} + /** * @description * * This object provides a utility for producing rich Error messages within - * Angular. It can be called as follows: + * AngularJS. It can be called as follows: * * var exampleMinErr = minErr('example'); * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); @@ -26,143 +87,159 @@ * Since data will be parsed statically during a build step, some restrictions * are applied with respect to how minErr instances are created and called. * Instances should have names of the form namespaceMinErr for a minErr created - * using minErr('namespace') . Error codes, namespaces and template strings + * using minErr('namespace'). Error codes, namespaces and template strings * should all be static strings, not variables or general expressions. * * @param {string} module The namespace to use for the new minErr instance. + * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning + * error from returned function, for cases when a particular type of error is useful. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance */ -function minErr(module) { - return function () { - var code = arguments[0], - prefix = '[' + (module ? module + ':' : '') + code + '] ', - template = arguments[1], - templateArgs = arguments, - stringify = function (obj) { - if (typeof obj === 'function') { - return obj.toString().replace(/ \{[\s\S]*$/, ''); - } else if (typeof obj === 'undefined') { - return 'undefined'; - } else if (typeof obj !== 'string') { - return JSON.stringify(obj); - } - return obj; - }, - message, i; +function minErr(module, ErrorConstructor) { + ErrorConstructor = ErrorConstructor || Error; - message = prefix + template.replace(/\{\d+\}/g, function (match) { - var index = +match.slice(1, -1), arg; + var url = 'https://errors.angularjs.org/1.8.2/'; + var regex = url.replace('.', '\\.') + '[\\s\\S]*'; + var errRegExp = new RegExp(regex, 'g'); - if (index + 2 < templateArgs.length) { - arg = templateArgs[index + 2]; - if (typeof arg === 'function') { - return arg.toString().replace(/ ?\{[\s\S]*$/, ''); - } else if (typeof arg === 'undefined') { - return 'undefined'; - } else if (typeof arg !== 'string') { - return toJson(arg); - } - return arg; + return function() { + var code = arguments[0], + template = arguments[1], + message = '[' + (module ? module + ':' : '') + code + '] ', + templateArgs = sliceArgs(arguments, 2).map(function(arg) { + return toDebugString(arg, minErrConfig.objectMaxDepth); + }), + paramPrefix, i; + + // A minErr message has two parts: the message itself and the url that contains the + // encoded message. + // The message's parameters can contain other error messages which also include error urls. + // To prevent the messages from getting too long, we strip the error urls from the parameters. + + message += template.replace(/\{\d+\}/g, function(match) { + var index = +match.slice(1, -1); + + if (index < templateArgs.length) { + return templateArgs[index].replace(errRegExp, ''); } + return match; }); - message = message + '\nhttp://errors.angularjs.org/1.2.16/' + - (module ? module + '/' : '') + code; - for (i = 2; i < arguments.length; i++) { - message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' + - encodeURIComponent(stringify(arguments[i])); + message += '\n' + url + (module ? module + '/' : '') + code; + + if (minErrConfig.urlErrorParamsEnabled) { + for (i = 0, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') { + message += paramPrefix + 'p' + i + '=' + encodeURIComponent(templateArgs[i]); + } } - return new Error(message); + return new ErrorConstructor(message); }; } -/* We need to tell jshint what variables are being exported */ -/* global - -angular, - -msie, - -jqLite, - -jQuery, - -slice, - -push, - -toString, - -ngMinErr, - -_angular, - -angularModule, - -nodeName_, - -uid, - - -lowercase, - -uppercase, - -manualLowercase, - -manualUppercase, - -nodeName_, - -isArrayLike, - -forEach, - -sortedKeys, - -forEachSorted, - -reverseParams, - -nextUid, - -setHashKey, - -extend, - -int, - -inherit, - -noop, - -identity, - -valueFn, - -isUndefined, - -isDefined, - -isObject, - -isString, - -isNumber, - -isDate, - -isArray, - -isFunction, - -isRegExp, - -isWindow, - -isScope, - -isFile, - -isBlob, - -isBoolean, - -trim, - -isElement, - -makeMap, - -map, - -size, - -includes, - -indexOf, - -arrayRemove, - -isLeafNode, - -copy, - -shallowCopy, - -equals, - -csp, - -concat, - -sliceArgs, - -bind, - -toJsonReplacer, - -toJson, - -fromJson, - -toBoolean, - -startingTag, - -tryDecodeURIComponent, - -parseKeyValue, - -toKeyValue, - -encodeUriSegment, - -encodeUriQuery, - -angularInit, - -bootstrap, - -snake_case, - -bindJQuery, - -assertArg, - -assertArgFn, - -assertNotHasOwnProperty, - -getter, - -getBlockElements, - -hasOwnProperty, - +/* We need to tell ESLint what variables are being exported */ +/* exported + angular, + msie, + jqLite, + jQuery, + slice, + splice, + push, + toString, + minErrConfig, + errorHandlingConfig, + isValidObjectMaxDepth, + ngMinErr, + angularModule, + uid, + REGEX_STRING_REGEXP, + VALIDITY_STATE_PROPERTY, + + lowercase, + uppercase, + nodeName_, + isArrayLike, + forEach, + forEachSorted, + reverseParams, + nextUid, + setHashKey, + extend, + toInt, + inherit, + merge, + noop, + identity, + valueFn, + isUndefined, + isDefined, + isObject, + isBlankObject, + isString, + isNumber, + isNumberNaN, + isDate, + isError, + isArray, + isFunction, + isRegExp, + isWindow, + isScope, + isFile, + isFormData, + isBlob, + isBoolean, + isPromiseLike, + trim, + escapeForRegexp, + isElement, + makeMap, + includes, + arrayRemove, + copy, + simpleCompare, + equals, + csp, + jq, + concat, + sliceArgs, + bind, + toJsonReplacer, + toJson, + fromJson, + convertTimezoneToLocal, + timezoneToOffset, + addDateMinutes, + startingTag, + tryDecodeURIComponent, + parseKeyValue, + toKeyValue, + encodeUriSegment, + encodeUriQuery, + angularInit, + bootstrap, + getTestability, + snake_case, + bindJQuery, + assertArg, + assertArgFn, + assertNotHasOwnProperty, + getter, + getBlockNodes, + hasOwnProperty, + createMap, + stringify, + UNSAFE_restoreLegacyJqLiteXHTMLReplacement, + + NODE_TYPE_ELEMENT, + NODE_TYPE_ATTRIBUTE, + NODE_TYPE_TEXT, + NODE_TYPE_COMMENT, + NODE_TYPE_DOCUMENT, + NODE_TYPE_DOCUMENT_FRAGMENT */ //////////////////////////////////// @@ -171,91 +248,66 @@ function minErr(module) { * @ngdoc module * @name ng * @module ng + * @installation * @description * - * # ng (core module) * The ng module is loaded by default when an AngularJS application is started. The module itself * contains the essential components for an AngularJS application to function. The table below * lists a high level breakdown of each of the services/factories, filters, directives and testing * components available within this core module. * - *
*/ +var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/; + +// The name of a form control's ValidityState property. +// This is used so that it's possible for internal tests to create mock ValidityStates. +var VALIDITY_STATE_PROPERTY = 'validity'; + + +var hasOwnProperty = Object.prototype.hasOwnProperty; + /** - * @ngdoc function - * @name angular.lowercase - * @module ng - * @function + * @private * * @description Converts the specified string to lowercase. * @param {string} string String to be converted to lowercase. * @returns {string} Lowercased string. */ -var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;}; -var hasOwnProperty = Object.prototype.hasOwnProperty; +var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;}; /** - * @ngdoc function - * @name angular.uppercase - * @module ng - * @function + * @private * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. * @returns {string} Uppercased string. */ -var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;}; - - -var manualLowercase = function(s) { - /* jshint bitwise: false */ - return isString(s) - ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);}) - : s; -}; -var manualUppercase = function(s) { - /* jshint bitwise: false */ - return isString(s) - ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);}) - : s; -}; - - -// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish -// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods -// with correct but slower alternatives. -if ('i' !== 'I'.toLowerCase()) { - lowercase = manualLowercase; - uppercase = manualUppercase; -} +var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;}; -var /** holds major version number for IE or NaN for real browsers */ - msie, +var + msie, // holds major version number for IE, or NaN if UA is not IE. jqLite, // delay binding since jQuery could be loaded after us. jQuery, // delay binding slice = [].slice, + splice = [].splice, push = [].push, toString = Object.prototype.toString, + getPrototypeOf = Object.getPrototypeOf, ngMinErr = minErr('ng'), - - _angular = window.angular, /** @name angular */ angular = window.angular || (window.angular = {}), angularModule, - nodeName_, - uid = ['0', '0', '0']; + uid = 0; +// Support: IE 9-11 only /** - * IE 11 changed the format of the UserAgent string. - * See http://msdn.microsoft.com/en-us/library/ms537503.aspx + * documentMode is an IE-only property + * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx */ -msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]); -if (isNaN(msie)) { - msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]); -} +msie = window.document.documentMode; /** @@ -265,39 +317,50 @@ if (isNaN(msie)) { * String ...) */ function isArrayLike(obj) { - if (obj == null || isWindow(obj)) { - return false; - } - var length = obj.length; + // `null`, `undefined` and `window` are not array-like + if (obj == null || isWindow(obj)) return false; - if (obj.nodeType === 1 && length) { - return true; - } + // arrays, strings and jQuery/jqLite objects are array like + // * jqLite is either the jQuery or jqLite constructor function + // * we have to check the existence of jqLite first as this method is called + // via the forEach method when constructing the jqLite object in the first place + if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true; + + // Support: iOS 8.2 (not reproducible in simulator) + // "length" in obj used to prevent JIT error (gh-11508) + var length = 'length' in Object(obj) && obj.length; + + // NodeList objects (with `item` method) and + // other objects with suitable length characteristics are array-like + return isNumber(length) && (length >= 0 && (length - 1) in obj || typeof obj.item === 'function'); - return isString(obj) || isArray(obj) || length === 0 || - typeof length === 'number' && length > 0 && (length - 1) in obj; } /** * @ngdoc function * @name angular.forEach * @module ng - * @function + * @kind function * * @description * Invokes the `iterator` function once for each item in `obj` collection, which can be either an - * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value` - * is the value of an object property or an array element and `key` is the object property key or - * array element index. Specifying a `context` for the function is optional. + * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value` + * is the value of an object property or an array element, `key` is the object property key or + * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional. * * It is worth noting that `.forEach` does not iterate over inherited properties because it filters * using the `hasOwnProperty` method. + * + * Unlike ES262's + * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18), + * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just + * return the value provided. * ```js var values = {name: 'misko', gender: 'male'}; var log = []; - angular.forEach(values, function(value, key){ + angular.forEach(values, function(value, key) { this.push(key + ': ' + value); }, log); expect(log).toEqual(['name: misko', 'gender: male']); @@ -308,26 +371,42 @@ function isArrayLike(obj) { * @param {Object=} context Object to become context (`this`) for the iterator function. * @returns {Object|Array} Reference to `obj`. */ + function forEach(obj, iterator, context) { - var key; + var key, length; if (obj) { - if (isFunction(obj)){ + if (isFunction(obj)) { for (key in obj) { - // Need to check if hasOwnProperty exists, - // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function - if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) { - iterator.call(context, obj[key], key); + if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) { + iterator.call(context, obj[key], key, obj); + } + } + } else if (isArray(obj) || isArrayLike(obj)) { + var isPrimitive = typeof obj !== 'object'; + for (key = 0, length = obj.length; key < length; key++) { + if (isPrimitive || key in obj) { + iterator.call(context, obj[key], key, obj); } } } else if (obj.forEach && obj.forEach !== forEach) { - obj.forEach(iterator, context); - } else if (isArrayLike(obj)) { - for (key = 0; key < obj.length; key++) - iterator.call(context, obj[key], key); - } else { + obj.forEach(iterator, context, obj); + } else if (isBlankObject(obj)) { + // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty + for (key in obj) { + iterator.call(context, obj[key], key, obj); + } + } else if (typeof obj.hasOwnProperty === 'function') { + // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed for (key in obj) { if (obj.hasOwnProperty(key)) { - iterator.call(context, obj[key], key); + iterator.call(context, obj[key], key, obj); + } + } + } else { + // Slow path for objects which do not have a method `hasOwnProperty` + for (key in obj) { + if (hasOwnProperty.call(obj, key)) { + iterator.call(context, obj[key], key, obj); } } } @@ -335,19 +414,9 @@ function forEach(obj, iterator, context) { return obj; } -function sortedKeys(obj) { - var keys = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - keys.push(key); - } - } - return keys.sort(); -} - function forEachSorted(obj, iterator, context) { - var keys = sortedKeys(obj); - for ( var i = 0; i < keys.length; i++) { + var keys = Object.keys(obj).sort(); + for (var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } return keys; @@ -360,37 +429,21 @@ function forEachSorted(obj, iterator, context) { * @returns {function(*, string)} */ function reverseParams(iteratorFn) { - return function(value, key) { iteratorFn(key, value); }; + return function(value, key) {iteratorFn(key, value);}; } /** - * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric - * characters such as '012ABC'. The reason why we are not using simply a number counter is that - * the number string gets longer over time, and it can also overflow, where as the nextId - * will grow much slower, it is a string, and it will never overflow. + * A consistent way of creating unique IDs in angular. + * + * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before + * we hit number precision issues in JavaScript. * - * @returns {string} an unique alpha-numeric string + * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M + * + * @returns {number} an unique alpha-numeric string */ function nextUid() { - var index = uid.length; - var digit; - - while(index) { - index--; - digit = uid[index].charCodeAt(0); - if (digit == 57 /*'9'*/) { - uid[index] = 'A'; - return uid.join(''); - } - if (digit == 90 /*'Z'*/) { - uid[index] = '0'; - } else { - uid[index] = String.fromCharCode(digit + 1); - return uid.join(''); - } - } - uid.unshift('0'); - return uid.join(''); + return ++uid; } @@ -402,54 +455,130 @@ function nextUid() { function setHashKey(obj, h) { if (h) { obj.$$hashKey = h; - } - else { + } else { delete obj.$$hashKey; } } + +function baseExtend(dst, objs, deep) { + var h = dst.$$hashKey; + + for (var i = 0, ii = objs.length; i < ii; ++i) { + var obj = objs[i]; + if (!isObject(obj) && !isFunction(obj)) continue; + var keys = Object.keys(obj); + for (var j = 0, jj = keys.length; j < jj; j++) { + var key = keys[j]; + var src = obj[key]; + + if (deep && isObject(src)) { + if (isDate(src)) { + dst[key] = new Date(src.valueOf()); + } else if (isRegExp(src)) { + dst[key] = new RegExp(src); + } else if (src.nodeName) { + dst[key] = src.cloneNode(true); + } else if (isElement(src)) { + dst[key] = src.clone(); + } else { + if (key !== '__proto__') { + if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {}; + baseExtend(dst[key], [src], true); + } + } + } else { + dst[key] = src; + } + } + } + + setHashKey(dst, h); + return dst; +} + /** * @ngdoc function * @name angular.extend * @module ng - * @function + * @kind function * * @description - * Extends the destination object `dst` by copying all of the properties from the `src` object(s) - * to `dst`. You can specify multiple `src` objects. + * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s) + * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so + * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`. + * + * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use + * {@link angular.merge} for this. * * @param {Object} dst Destination object. * @param {...Object} src Source object(s). * @returns {Object} Reference to `dst`. */ function extend(dst) { - var h = dst.$$hashKey; - forEach(arguments, function(obj){ - if (obj !== dst) { - forEach(obj, function(value, key){ - dst[key] = value; - }); - } - }); + return baseExtend(dst, slice.call(arguments, 1), false); +} - setHashKey(dst,h); - return dst; + +/** +* @ngdoc function +* @name angular.merge +* @module ng +* @kind function +* +* @description +* Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s) +* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so +* by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`. +* +* Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source +* objects, performing a deep copy. +* +* @deprecated +* sinceVersion="1.6.5" +* This function is deprecated, but will not be removed in the 1.x lifecycle. +* There are edge cases (see {@link angular.merge#known-issues known issues}) that are not +* supported by this function. We suggest using another, similar library for all-purpose merging, +* such as [lodash's merge()](https://lodash.com/docs/4.17.4#merge). +* +* @knownIssue +* This is a list of (known) object types that are not handled correctly by this function: +* - [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob) +* - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream) +* - [`CanvasGradient`](https://developer.mozilla.org/docs/Web/API/CanvasGradient) +* - AngularJS {@link $rootScope.Scope scopes}; +* +* `angular.merge` also does not support merging objects with circular references. +* +* @param {Object} dst Destination object. +* @param {...Object} src Source object(s). +* @returns {Object} Reference to `dst`. +*/ +function merge(dst) { + return baseExtend(dst, slice.call(arguments, 1), true); } -function int(str) { + + +function toInt(str) { return parseInt(str, 10); } +var isNumberNaN = Number.isNaN || function isNumberNaN(num) { + // eslint-disable-next-line no-self-compare + return num !== num; +}; + function inherit(parent, extra) { - return extend(new (extend(function() {}, {prototype:parent}))(), extra); + return extend(Object.create(parent), extra); } /** * @ngdoc function * @name angular.noop * @module ng - * @function + * @kind function * * @description * A function that performs no operations. This function can be useful when writing code in the @@ -469,29 +598,46 @@ noop.$inject = []; * @ngdoc function * @name angular.identity * @module ng - * @function + * @kind function * * @description * A function that returns its first argument. This function is useful when writing code in the * functional style. * ```js - function transformer(transformationFn, value) { - return (transformationFn || angular.identity)(value); - }; + function transformer(transformationFn, value) { + return (transformationFn || angular.identity)(value); + }; + + // E.g. + function getResult(fn, input) { + return (fn || angular.identity)(input); + }; + + getResult(function(n) { return n * 2; }, 21); // returns 42 + getResult(null, 21); // returns 21 + getResult(undefined, 21); // returns 21 ``` + * + * @param {*} value to be returned. + * @returns {*} the value passed in. */ function identity($) {return $;} identity.$inject = []; -function valueFn(value) {return function() {return value;};} +function valueFn(value) {return function valueRef() {return value;};} + +function hasCustomToString(obj) { + return isFunction(obj.toString) && obj.toString !== toString; +} + /** * @ngdoc function * @name angular.isUndefined * @module ng - * @function + * @kind function * * @description * Determines if a reference is undefined. @@ -499,14 +645,14 @@ function valueFn(value) {return function() {return value;};} * @param {*} value Reference to check. * @returns {boolean} True if `value` is undefined. */ -function isUndefined(value){return typeof value === 'undefined';} +function isUndefined(value) {return typeof value === 'undefined';} /** * @ngdoc function * @name angular.isDefined * @module ng - * @function + * @kind function * * @description * Determines if a reference is defined. @@ -514,14 +660,14 @@ function isUndefined(value){return typeof value === 'undefined';} * @param {*} value Reference to check. * @returns {boolean} True if `value` is defined. */ -function isDefined(value){return typeof value !== 'undefined';} +function isDefined(value) {return typeof value !== 'undefined';} /** * @ngdoc function * @name angular.isObject * @module ng - * @function + * @kind function * * @description * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not @@ -530,14 +676,27 @@ function isDefined(value){return typeof value !== 'undefined';} * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Object` but not `null`. */ -function isObject(value){return value != null && typeof value === 'object';} +function isObject(value) { + // http://jsperf.com/isobject4 + return value !== null && typeof value === 'object'; +} + + +/** + * Determine if a value is an object with a null prototype + * + * @returns {boolean} True if `value` is an `Object` with a null prototype + */ +function isBlankObject(value) { + return value !== null && typeof value === 'object' && !getPrototypeOf(value); +} /** * @ngdoc function * @name angular.isString * @module ng - * @function + * @kind function * * @description * Determines if a reference is a `String`. @@ -545,29 +704,35 @@ function isObject(value){return value != null && typeof value === 'object';} * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `String`. */ -function isString(value){return typeof value === 'string';} +function isString(value) {return typeof value === 'string';} /** * @ngdoc function * @name angular.isNumber * @module ng - * @function + * @kind function * * @description * Determines if a reference is a `Number`. * + * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`. + * + * If you wish to exclude these then you can use the native + * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite) + * method. + * * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Number`. */ -function isNumber(value){return typeof value === 'number';} +function isNumber(value) {return typeof value === 'number';} /** * @ngdoc function * @name angular.isDate * @module ng - * @function + * @kind function * * @description * Determines if a value is a date. @@ -575,7 +740,7 @@ function isNumber(value){return typeof value === 'number';} * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Date`. */ -function isDate(value){ +function isDate(value) { return toString.call(value) === '[object Date]'; } @@ -584,7 +749,7 @@ function isDate(value){ * @ngdoc function * @name angular.isArray * @module ng - * @function + * @kind function * * @description * Determines if a reference is an `Array`. @@ -592,16 +757,33 @@ function isDate(value){ * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ -function isArray(value) { - return toString.call(value) === '[object Array]'; +function isArray(arr) { + return Array.isArray(arr) || arr instanceof Array; } +/** + * @description + * Determines if a reference is an `Error`. + * Loosely based on https://www.npmjs.com/package/iserror + * + * @param {*} value Reference to check. + * @returns {boolean} True if `value` is an `Error`. + */ +function isError(value) { + var tag = toString.call(value); + switch (tag) { + case '[object Error]': return true; + case '[object Exception]': return true; + case '[object DOMException]': return true; + default: return value instanceof Error; + } +} /** * @ngdoc function * @name angular.isFunction * @module ng - * @function + * @kind function * * @description * Determines if a reference is a `Function`. @@ -609,7 +791,7 @@ function isArray(value) { * @param {*} value Reference to check. * @returns {boolean} True if `value` is a `Function`. */ -function isFunction(value){return typeof value === 'function';} +function isFunction(value) {return typeof value === 'function';} /** @@ -632,7 +814,7 @@ function isRegExp(value) { * @returns {boolean} True if `obj` is a window obj. */ function isWindow(obj) { - return obj && obj.document && obj.location && obj.alert && obj.setInterval; + return obj && obj.window === obj; } @@ -646,6 +828,11 @@ function isFile(obj) { } +function isFormData(obj) { + return toString.call(obj) === '[object FormData]'; +} + + function isBlob(obj) { return toString.call(obj) === '[object Blob]'; } @@ -656,26 +843,41 @@ function isBoolean(value) { } -var trim = (function() { - // native trim is way faster: http://jsperf.com/angular-trim-test - // but IE doesn't have it... :-( - // TODO: we should move this into IE/ES5 polyfill - if (!String.prototype.trim) { - return function(value) { - return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value; - }; - } - return function(value) { - return isString(value) ? value.trim() : value; - }; -})(); +function isPromiseLike(obj) { + return obj && isFunction(obj.then); +} + + +var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array]$/; +function isTypedArray(value) { + return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value)); +} + +function isArrayBuffer(obj) { + return toString.call(obj) === '[object ArrayBuffer]'; +} + + +var trim = function(value) { + return isString(value) ? value.trim() : value; +}; + +// Copied from: +// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021 +// Prereq: s is a string. +var escapeForRegexp = function(s) { + return s + .replace(/([-()[\]{}+?*.$^|,:#=0) + var index = array.indexOf(value); + if (index >= 0) { array.splice(index, 1); - return value; -} - -function isLeafNode (node) { - if (node) { - switch (node.nodeName) { - case "OPTION": - case "PRE": - case "TITLE": - return true; - } } - return false; + return index; } /** * @ngdoc function * @name angular.copy * @module ng - * @function + * @kind function * * @description - * Creates a deep copy of `source`, which should be an object or an array. + * Creates a deep copy of `source`, which should be an object or an array. This functions is used + * internally, mostly in the change-detection code. It is not intended as an all-purpose copy + * function, and has several limitations (see below). * * * If no destination is supplied, a copy of the object or array is created. - * * If a destination is provided, all of its elements (for array) or properties (for objects) + * * If a destination is provided, all of its elements (for arrays) or properties (for objects) * are deleted and then all elements/properties from the source are copied to it. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned. - * * If `source` is identical to 'destination' an exception will be thrown. + * * If `source` is identical to `destination` an exception will be thrown. * - * @param {*} source The source that will be used to make a copy. - * Can be any type, including primitives, `null`, and `undefined`. - * @param {(Object|Array)=} destination Destination into which the source is copied. If - * provided, must be of the same type as `source`. + *
+ * + *
+ * Only enumerable properties are taken into account. Non-enumerable properties (both on `source` + * and on `destination`) will be ignored. + *
+ * + *
+ * `angular.copy` does not check if destination and source are of the same type. It's the + * developer's responsibility to make sure they are compatible. + *
+ * + * @knownIssue + * This is a non-exhaustive list of object types / features that are not handled correctly by + * `angular.copy`. Note that since this functions is used by the change detection code, this + * means binding or watching objects of these types (or that include these types) might not work + * correctly. + * - [`File`](https://developer.mozilla.org/docs/Web/API/File) + * - [`Map`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Map) + * - [`ImageData`](https://developer.mozilla.org/docs/Web/API/ImageData) + * - [`MediaStream`](https://developer.mozilla.org/docs/Web/API/MediaStream) + * - [`Set`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Set) + * - [`WeakMap`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) + * - [`getter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)/ + * [`setter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + * + * @param {*} source The source that will be used to make a copy. Can be any type, including + * primitives, `null`, and `undefined`. + * @param {(Object|Array)=} destination Destination into which the source is copied. If provided, + * must be of the same type as `source`. * @returns {*} The copy or updated `destination`, if `destination` was specified. * * @example - - -
-
- Name:
- E-mail:
- Gender: male - female
- - -
-
form = {{user | json}}
-
master = {{master | json}}
-
- - -
-
+ $scope.reset(); + }]); + + */ -function copy(source, destination){ - if (isWindow(source) || isScope(source)) { - throw ngMinErr('cpws', - "Can't copy! Making copies of Window or Scope instances is not supported."); +function copy(source, destination, maxDepth) { + var stackSource = []; + var stackDest = []; + maxDepth = isValidObjectMaxDepth(maxDepth) ? maxDepth : NaN; + + if (destination) { + if (isTypedArray(destination) || isArrayBuffer(destination)) { + throw ngMinErr('cpta', 'Can\'t copy! TypedArray destination cannot be mutated.'); + } + if (source === destination) { + throw ngMinErr('cpi', 'Can\'t copy! Source and destination are identical.'); + } + + // Empty the destination object + if (isArray(destination)) { + destination.length = 0; + } else { + forEach(destination, function(value, key) { + if (key !== '$$hashKey') { + delete destination[key]; + } + }); + } + + stackSource.push(source); + stackDest.push(destination); + return copyRecurse(source, destination, maxDepth); } - if (!destination) { - destination = source; - if (source) { - if (isArray(source)) { - destination = copy(source, []); - } else if (isDate(source)) { - destination = new Date(source.getTime()); - } else if (isRegExp(source)) { - destination = new RegExp(source.source); - } else if (isObject(source)) { - destination = copy(source, {}); - } + return copyElement(source, maxDepth); + + function copyRecurse(source, destination, maxDepth) { + maxDepth--; + if (maxDepth < 0) { + return '...'; } - } else { - if (source === destination) throw ngMinErr('cpi', - "Can't copy! Source and destination are identical."); + var h = destination.$$hashKey; + var key; if (isArray(source)) { - destination.length = 0; - for ( var i = 0; i < source.length; i++) { - destination.push(copy(source[i])); + for (var i = 0, ii = source.length; i < ii; i++) { + destination.push(copyElement(source[i], maxDepth)); + } + } else if (isBlankObject(source)) { + // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty + for (key in source) { + destination[key] = copyElement(source[key], maxDepth); + } + } else if (source && typeof source.hasOwnProperty === 'function') { + // Slow path, which must rely on hasOwnProperty + for (key in source) { + if (source.hasOwnProperty(key)) { + destination[key] = copyElement(source[key], maxDepth); + } } } else { - var h = destination.$$hashKey; - forEach(destination, function(value, key){ - delete destination[key]; - }); - for ( var key in source) { - destination[key] = copy(source[key]); + // Slowest path --- hasOwnProperty can't be called as a method + for (key in source) { + if (hasOwnProperty.call(source, key)) { + destination[key] = copyElement(source[key], maxDepth); + } } - setHashKey(destination,h); } + setHashKey(destination, h); + return destination; } - return destination; -} -/** - * Create a shallow copy of an object - */ -function shallowCopy(src, dst) { - dst = dst || {}; + function copyElement(source, maxDepth) { + // Simple values + if (!isObject(source)) { + return source; + } + + // Already copied values + var index = stackSource.indexOf(source); + if (index !== -1) { + return stackDest[index]; + } + + if (isWindow(source) || isScope(source)) { + throw ngMinErr('cpws', + 'Can\'t copy! Making copies of Window or Scope instances is not supported.'); + } + + var needsRecurse = false; + var destination = copyType(source); - for(var key in src) { - // shallowCopy is only ever called by $compile nodeLinkFn, which has control over src - // so we don't need to worry about using our custom hasOwnProperty here - if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) { - dst[key] = src[key]; + if (destination === undefined) { + destination = isArray(source) ? [] : Object.create(getPrototypeOf(source)); + needsRecurse = true; } + + stackSource.push(source); + stackDest.push(destination); + + return needsRecurse + ? copyRecurse(source, destination, maxDepth) + : destination; } - return dst; -} + function copyType(source) { + switch (toString.call(source)) { + case '[object Int8Array]': + case '[object Int16Array]': + case '[object Int32Array]': + case '[object Float32Array]': + case '[object Float64Array]': + case '[object Uint8Array]': + case '[object Uint8ClampedArray]': + case '[object Uint16Array]': + case '[object Uint32Array]': + return new source.constructor(copyElement(source.buffer), source.byteOffset, source.length); + + case '[object ArrayBuffer]': + // Support: IE10 + if (!source.slice) { + // If we're in this case we know the environment supports ArrayBuffer + /* eslint-disable no-undef */ + var copied = new ArrayBuffer(source.byteLength); + new Uint8Array(copied).set(new Uint8Array(source)); + /* eslint-enable */ + return copied; + } + return source.slice(0); + case '[object Boolean]': + case '[object Number]': + case '[object String]': + case '[object Date]': + return new source.constructor(source.valueOf()); -/** - * @ngdoc function - * @name angular.equals + case '[object RegExp]': + var re = new RegExp(source.source, source.toString().match(/[^/]*$/)[0]); + re.lastIndex = source.lastIndex; + return re; + + case '[object Blob]': + return new source.constructor([source], {type: source.type}); + } + + if (isFunction(source.cloneNode)) { + return source.cloneNode(true); + } + } +} + + +// eslint-disable-next-line no-self-compare +function simpleCompare(a, b) { return a === b || (a !== a && b !== b); } + + +/** + * @ngdoc function + * @name angular.equals * @module ng - * @function + * @kind function * * @description * Determines if two objects or two values are equivalent. Supports value types, regular @@ -914,7 +1173,7 @@ function shallowCopy(src, dst) { * * Both objects or values are of the same type and all of their properties are equal by * comparing them with `angular.equals`. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal) - * * Both values represent the same regular expression (In JavasScript, + * * Both values represent the same regular expression (In JavaScript, * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual * representation matches). * @@ -926,54 +1185,171 @@ function shallowCopy(src, dst) { * @param {*} o1 Object or value to compare. * @param {*} o2 Object or value to compare. * @returns {boolean} True if arguments are equal. + * + * @example + + +
+
+

User 1

+ Name: + Age: + +

User 2

+ Name: + Age: + +
+
+ +
+ User 1:
{{user1 | json}}
+ User 2:
{{user2 | json}}
+ Equal:
{{result}}
+
+
+
+ + angular.module('equalsExample', []).controller('ExampleController', ['$scope', function($scope) { + $scope.user1 = {}; + $scope.user2 = {}; + $scope.compare = function() { + $scope.result = angular.equals($scope.user1, $scope.user2); + }; + }]); + +
*/ function equals(o1, o2) { if (o1 === o2) return true; if (o1 === null || o2 === null) return false; + // eslint-disable-next-line no-self-compare if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN var t1 = typeof o1, t2 = typeof o2, length, key, keySet; - if (t1 == t2) { - if (t1 == 'object') { - if (isArray(o1)) { - if (!isArray(o2)) return false; - if ((length = o1.length) == o2.length) { - for(key=0; key + + ... + ... + + ``` + * @example + * This example shows how to use a jQuery based library of a different name. + * The library name must be available at the top most 'window'. + ```html + + + ... + ... + + ``` + */ +var jq = function() { + if (isDefined(jq.name_)) return jq.name_; + var el; + var i, ii = ngAttrPrefixes.length, prefix, name; + for (i = 0; i < ii; ++i) { + prefix = ngAttrPrefixes[i]; + el = window.document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]'); + if (el) { + name = el.getAttribute(prefix + 'jq'); + break; + } + } + + return (jq.name_ = name); +}; function concat(array1, array2, index) { return array1.concat(slice.call(array2, index)); @@ -984,12 +1360,11 @@ function sliceArgs(args, startIndex) { } -/* jshint -W101 */ /** * @ngdoc function * @name angular.bind * @module ng - * @function + * @kind function * * @description * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for @@ -1002,14 +1377,13 @@ function sliceArgs(args, startIndex) { * @param {...*} args Optional arguments to be prebound to the `fn` function call. * @returns {function()} Function that wraps the `fn` with all the specified bindings. */ -/* jshint +W101 */ function bind(self, fn) { var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : []; if (isFunction(fn) && !(fn instanceof RegExp)) { return curryArgs.length ? function() { return arguments.length - ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0))) + ? fn.apply(self, concat(curryArgs, arguments, 0)) : fn.apply(self, curryArgs); } : function() { @@ -1018,7 +1392,7 @@ function bind(self, fn) { : fn.call(self); }; } else { - // in IE, native methods are not functions so they cannot be bound (note: they don't need to be) + // In IE, native methods are not functions so they cannot be bound (note: they don't need to be). return fn; } } @@ -1027,11 +1401,11 @@ function bind(self, fn) { function toJsonReplacer(key, value) { var val = value; - if (typeof key === 'string' && key.charAt(0) === '$') { + if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') { val = undefined; } else if (isWindow(value)) { val = '$WINDOW'; - } else if (value && document === value) { + } else if (value && window.document === value) { val = '$DOCUMENT'; } else if (isScope(value)) { val = '$SCOPE'; @@ -1045,19 +1419,44 @@ function toJsonReplacer(key, value) { * @ngdoc function * @name angular.toJson * @module ng - * @function + * @kind function * * @description - * Serializes input into a JSON-formatted string. Properties with leading $ characters will be - * stripped since angular uses this notation internally. + * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be + * stripped since AngularJS uses this notation internally. * - * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. - * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace. + * @param {Object|Array|Date|string|number|boolean} obj Input to be serialized into JSON. + * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace. + * If set to an integer, the JSON output will contain that many spaces per indentation. * @returns {string|undefined} JSON-ified string representing `obj`. + * @knownIssue + * + * The Safari browser throws a `RangeError` instead of returning `null` when it tries to stringify a `Date` + * object with an invalid date value. The only reliable way to prevent this is to monkeypatch the + * `Date.prototype.toJSON` method as follows: + * + * ``` + * var _DatetoJSON = Date.prototype.toJSON; + * Date.prototype.toJSON = function() { + * try { + * return _DatetoJSON.call(this); + * } catch(e) { + * if (e instanceof RangeError) { + * return null; + * } + * throw e; + * } + * }; + * ``` + * + * See https://github.com/angular/angular.js/pull/14221 for more information. */ function toJson(obj, pretty) { - if (typeof obj === 'undefined') return undefined; - return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null); + if (isUndefined(obj)) return undefined; + if (!isNumber(pretty)) { + pretty = pretty ? 2 : null; + } + return JSON.stringify(obj, toJsonReplacer, pretty); } @@ -1065,13 +1464,13 @@ function toJson(obj, pretty) { * @ngdoc function * @name angular.fromJson * @module ng - * @function + * @kind function * * @description * Deserializes a JSON string. * * @param {string} json JSON string to deserialize. - * @returns {Object|Array|string|number} Deserialized thingy. + * @returns {Object|Array|string|number} Deserialized JSON string. */ function fromJson(json) { return isString(json) @@ -1080,37 +1479,43 @@ function fromJson(json) { } -function toBoolean(value) { - if (typeof value === 'function') { - value = true; - } else if (value && value.length !== 0) { - var v = lowercase("" + value); - value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]'); - } else { - value = false; - } - return value; +var ALL_COLONS = /:/g; +function timezoneToOffset(timezone, fallback) { + // Support: IE 9-11 only, Edge 13-15+ + // IE/Edge do not "understand" colon (`:`) in timezone + timezone = timezone.replace(ALL_COLONS, ''); + var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000; + return isNumberNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset; +} + + +function addDateMinutes(date, minutes) { + date = new Date(date.getTime()); + date.setMinutes(date.getMinutes() + minutes); + return date; +} + + +function convertTimezoneToLocal(date, timezone, reverse) { + reverse = reverse ? -1 : 1; + var dateTimezoneOffset = date.getTimezoneOffset(); + var timezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); + return addDateMinutes(date, reverse * (timezoneOffset - dateTimezoneOffset)); } + /** * @returns {string} Returns the string representation of the element. */ function startingTag(element) { - element = jqLite(element).clone(); - try { - // turns out IE does not let you set .html() on elements which - // are not allowed to have children. So we just ignore it. - element.empty(); - } catch(e) {} - // As Per DOM Standards - var TEXT_NODE = 3; - var elemHtml = jqLite('
').append(element).html(); + element = jqLite(element).clone().empty(); + var elemHtml = jqLite('
').append(element).html(); try { - return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) : + return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) : elemHtml. match(/^(<[^>]+>)/)[1]. - replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); - } catch(e) { + replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);}); + } catch (e) { return lowercase(elemHtml); } @@ -1130,8 +1535,8 @@ function startingTag(element) { function tryDecodeURIComponent(value) { try { return decodeURIComponent(value); - } catch(e) { - // Ignore any invalid uri component + } catch (e) { + // Ignore any invalid uri component. } } @@ -1141,16 +1546,22 @@ function tryDecodeURIComponent(value) { * @returns {Object.} */ function parseKeyValue(/**string*/keyValue) { - var obj = {}, key_value, key; - forEach((keyValue || "").split('&'), function(keyValue){ - if ( keyValue ) { - key_value = keyValue.split('='); - key = tryDecodeURIComponent(key_value[0]); - if ( isDefined(key) ) { - var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; - if (!obj[key]) { + var obj = {}; + forEach((keyValue || '').split('&'), function(keyValue) { + var splitPoint, key, val; + if (keyValue) { + key = keyValue = keyValue.replace(/\+/g,'%20'); + splitPoint = keyValue.indexOf('='); + if (splitPoint !== -1) { + key = keyValue.substring(0, splitPoint); + val = keyValue.substring(splitPoint + 1); + } + key = tryDecodeURIComponent(key); + if (isDefined(key)) { + val = isDefined(val) ? tryDecodeURIComponent(val) : true; + if (!hasOwnProperty.call(obj, key)) { obj[key] = val; - } else if(isArray(obj[key])) { + } else if (isArray(obj[key])) { obj[key].push(val); } else { obj[key] = [obj[key],val]; @@ -1201,7 +1612,7 @@ function encodeUriSegment(val) { * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: - * query = *( pchar / "/" / "?" ) + * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG @@ -1214,9 +1625,74 @@ function encodeUriQuery(val, pctEncodeSpaces) { replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). + replace(/%3B/gi, ';'). replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); } +var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-']; + +function getNgAttribute(element, ngAttr) { + var attr, i, ii = ngAttrPrefixes.length; + for (i = 0; i < ii; ++i) { + attr = ngAttrPrefixes[i] + ngAttr; + if (isString(attr = element.getAttribute(attr))) { + return attr; + } + } + return null; +} + +function allowAutoBootstrap(document) { + var script = document.currentScript; + + if (!script) { + // Support: IE 9-11 only + // IE does not have `document.currentScript` + return true; + } + + // If the `currentScript` property has been clobbered just return false, since this indicates a probable attack + if (!(script instanceof window.HTMLScriptElement || script instanceof window.SVGScriptElement)) { + return false; + } + + var attributes = script.attributes; + var srcs = [attributes.getNamedItem('src'), attributes.getNamedItem('href'), attributes.getNamedItem('xlink:href')]; + + return srcs.every(function(src) { + if (!src) { + return true; + } + if (!src.value) { + return false; + } + + var link = document.createElement('a'); + link.href = src.value; + + if (document.location.origin === link.origin) { + // Same-origin resources are always allowed, even for banned URL schemes. + return true; + } + // Disabled bootstrapping unless angular.js was loaded from a known scheme used on the web. + // This is to prevent angular.js bundled with browser extensions from being used to bypass the + // content security policy in web pages and other browser extensions. + switch (link.protocol) { + case 'http:': + case 'https:': + case 'ftp:': + case 'blob:': + case 'file:': + case 'data:': + return true; + default: + return false; + } + }); +} + +// Cached as it has to run during loading so that document.currentScript is available. +var isAutoBootstrapAllowed = allowAutoBootstrap(window.document); /** * @ngdoc directive @@ -1226,6 +1702,11 @@ function encodeUriQuery(val, pctEncodeSpaces) { * @element ANY * @param {angular.Module} ngApp an optional application * {@link angular.module module} name to load. + * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be + * created in "strict-di" mode. This means that the application will fail to invoke functions which + * do not use explicit function annotation (and are thus unsuitable for minification), as described + * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in + * tracking down the root of these bugs. * * @description * @@ -1233,13 +1714,20 @@ function encodeUriQuery(val, pctEncodeSpaces) { * designates the **root element** of the application and is typically placed near the root element * of the page - e.g. on the `` or `` tags. * - * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` - * found in the document will be used to define the root element to auto-bootstrap as an - * application. To run multiple applications in an HTML document you must manually bootstrap them using - * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other. + * There are a few things to keep in mind when using `ngApp`: + * - only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` + * found in the document will be used to define the root element to auto-bootstrap as an + * application. To run multiple applications in an HTML document you must manually bootstrap them using + * {@link angular.bootstrap} instead. + * - AngularJS applications cannot be nested within each other. + * - Do not use a directive that uses {@link ng.$compile#transclusion transclusion} on the same element as `ngApp`. + * This includes directives such as {@link ng.ngIf `ngIf`}, {@link ng.ngInclude `ngInclude`} and + * {@link ngRoute.ngView `ngView`}. + * Doing this misplaces the app {@link ng.$rootElement `$rootElement`} and the app's {@link auto.$injector injector}, + * causing animations to stop working and making the injector inaccessible from outside the app. * * You can specify an **AngularJS module** to be used as the root module for the application. This - * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and + * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It * should contain the application code needed or have dependencies on other modules that will * contain the code. See {@link angular.module} for more information. * @@ -1247,9 +1735,13 @@ function encodeUriQuery(val, pctEncodeSpaces) { * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` * would not be resolved to `3`. * - * `ngApp` is the easiest, and most common, way to bootstrap an application. + * @example + * + * ### Simple Usage * - + * `ngApp` is the easiest, and most common way to bootstrap an application. + * +
I can add: {{a}} + {{b}} = {{ a+b }} @@ -1263,48 +1755,118 @@ function encodeUriQuery(val, pctEncodeSpaces) { * + * @example + * + * ### With `ngStrictDi` + * + * Using `ngStrictDi`, you would see something like this: + * + + +
+
+ I can add: {{a}} + {{b}} = {{ a+b }} + +

This renders because the controller does not fail to + instantiate, by using explicit annotation style (see + script.js for details) +

+
+ +
+ Name:
+ Hello, {{name}}! + +

This renders because the controller does not fail to + instantiate, by using explicit annotation style + (see script.js for details) +

+
+ +
+ I can add: {{a}} + {{b}} = {{ a+b }} + +

The controller could not be instantiated, due to relying + on automatic function annotations (which are disabled in + strict mode). As such, the content of this section is not + interpolated, and there should be an error in your web console. +

+
+
+
+ + angular.module('ngAppStrictDemo', []) + // BadController will fail to instantiate, due to relying on automatic function annotation, + // rather than an explicit annotation + .controller('BadController', function($scope) { + $scope.a = 1; + $scope.b = 2; + }) + // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated, + // due to using explicit annotations using the array style and $inject property, respectively. + .controller('GoodController1', ['$scope', function($scope) { + $scope.a = 1; + $scope.b = 2; + }]) + .controller('GoodController2', GoodController2); + function GoodController2($scope) { + $scope.name = 'World'; + } + GoodController2.$inject = ['$scope']; + + + div[ng-controller] { + margin-bottom: 1em; + -webkit-border-radius: 4px; + border-radius: 4px; + border: 1px solid; + padding: .5em; + } + div[ng-controller^=Good] { + border-color: #d6e9c6; + background-color: #dff0d8; + color: #3c763d; + } + div[ng-controller^=Bad] { + border-color: #ebccd1; + background-color: #f2dede; + color: #a94442; + margin-bottom: 0; + } + +
*/ function angularInit(element, bootstrap) { - var elements = [element], - appElement, + var appElement, module, - names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'], - NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/; + config = {}; - function append(element) { - element && elements.push(element); - } + // The element `element` has priority over any other element. + forEach(ngAttrPrefixes, function(prefix) { + var name = prefix + 'app'; - forEach(names, function(name) { - names[name] = true; - append(document.getElementById(name)); - name = name.replace(':', '\\:'); - if (element.querySelectorAll) { - forEach(element.querySelectorAll('.' + name), append); - forEach(element.querySelectorAll('.' + name + '\\:'), append); - forEach(element.querySelectorAll('[' + name + ']'), append); + if (!appElement && element.hasAttribute && element.hasAttribute(name)) { + appElement = element; + module = element.getAttribute(name); } }); + forEach(ngAttrPrefixes, function(prefix) { + var name = prefix + 'app'; + var candidate; - forEach(elements, function(element) { - if (!appElement) { - var className = ' ' + element.className + ' '; - var match = NG_APP_CLASS_REGEXP.exec(className); - if (match) { - appElement = element; - module = (match[2] || '').replace(/\s+/g, ','); - } else { - forEach(element.attributes, function(attr) { - if (!appElement && names[attr.name]) { - appElement = element; - module = attr.value; - } - }); - } + if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) { + appElement = candidate; + module = candidate.getAttribute(name); } }); if (appElement) { - bootstrap(appElement, module ? [module] : []); + if (!isAutoBootstrapAllowed) { + window.console.error('AngularJS: disabling automatic bootstrap. - *
- * - * - * - * - * - * - * - *
{{heading}}
{{fill}}
+ * ```html + * + * + * + *
+ * {{greeting}} *
- * - * - * var app = angular.module('multi-bootstrap', []) * - * .controller('BrokenTable', function($scope) { - * $scope.headings = ['One', 'Two', 'Three']; - * $scope.fillings = [[1, 2, 3], ['A', 'B', 'C'], [7, 8, 9]]; - * }); - * - * - * it('should only insert one table cell for each item in $scope.fillings', function() { - * expect(element.all(by.css('td')).count()) - * .toBe(9); - * }); - * - * + * + * + * + * + * ``` * - * @param {DOMElement} element DOM element which is the root of angular application. + * @param {DOMElement} element DOM element which is the root of AngularJS application. * @param {Array=} modules an array of modules to load into the application. * Each item in the array should be the name of a predefined module or a (DI annotated) - * function that will be invoked by the injector as a run block. + * function that will be invoked by the injector as a `config` block. * See: {@link angular.module modules} + * @param {Object=} config an object for defining configuration options for the application. The + * following keys are supported: + * + * * `strictDi` - disable automatic function annotation for the application. This is meant to + * assist in finding bugs which break minified code. Defaults to `false`. + * * @returns {auto.$injector} Returns the newly created injector for this app. */ -function bootstrap(element, modules) { +function bootstrap(element, modules, config) { + if (!isObject(config)) config = {}; + var defaultConfig = { + strictDi: false + }; + config = extend(defaultConfig, config); var doBootstrap = function() { element = jqLite(element); if (element.injector()) { - var tag = (element[0] === document) ? 'document' : startingTag(element); - throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag); + var tag = (element[0] === window.document) ? 'document' : startingTag(element); + // Encode angle brackets to prevent input from being sanitized to empty string #8683. + throw ngMinErr( + 'btstrpd', + 'App already bootstrapped with this element \'{0}\'', + tag.replace(//,'>')); } modules = modules || []; modules.unshift(['$provide', function($provide) { $provide.value('$rootElement', element); }]); + + if (config.debugInfoEnabled) { + // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`. + modules.push(['$compileProvider', function($compileProvider) { + $compileProvider.debugInfoEnabled(true); + }]); + } + modules.unshift('ng'); - var injector = createInjector(modules); - injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate', - function(scope, element, compile, injector, animate) { + var injector = createInjector(modules, config.strictDi); + injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', + function bootstrapApply(scope, element, compile, injector) { scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); @@ -1388,8 +1972,14 @@ function bootstrap(element, modules) { return injector; }; + var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/; var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/; + if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) { + config.debugInfoEnabled = true; + window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, ''); + } + if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) { return doBootstrap(); } @@ -1399,40 +1989,124 @@ function bootstrap(element, modules) { forEach(extraModules, function(module) { modules.push(module); }); - doBootstrap(); + return doBootstrap(); }; + + if (isFunction(angular.resumeDeferredBootstrap)) { + angular.resumeDeferredBootstrap(); + } +} + +/** + * @ngdoc function + * @name angular.reloadWithDebugInfo + * @module ng + * @description + * Use this function to reload the current application with debug information turned on. + * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`. + * + * See {@link ng.$compileProvider#debugInfoEnabled} for more. + */ +function reloadWithDebugInfo() { + window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name; + window.location.reload(); +} + +/** + * @name angular.getTestability + * @module ng + * @description + * Get the testability service for the instance of AngularJS on the given + * element. + * @param {DOMElement} element DOM element which is the root of AngularJS application. + */ +function getTestability(rootElement) { + var injector = angular.element(rootElement).injector(); + if (!injector) { + throw ngMinErr('test', + 'no injector found for element argument to getTestability'); + } + return injector.get('$$testability'); } var SNAKE_CASE_REGEXP = /[A-Z]/g; -function snake_case(name, separator){ +function snake_case(name, separator) { separator = separator || '_'; return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } +var bindJQueryFired = false; function bindJQuery() { + var originalCleanData; + + if (bindJQueryFired) { + return; + } + // bind to jQuery if present; - jQuery = window.jQuery; - // reset to jQuery or default to us. - if (jQuery) { + var jqName = jq(); + jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present) + !jqName ? undefined : // use jqLite + window[jqName]; // use jQuery specified by `ngJq` + + // Use jQuery if it exists with proper functionality, otherwise default to us. + // AngularJS 1.2+ requires jQuery 1.7+ for on()/off() support. + // AngularJS 1.3+ technically requires at least jQuery 2.1+ but it may work with older + // versions. It will not work for sure with jQuery <1.7, though. + if (jQuery && jQuery.fn.on) { jqLite = jQuery; extend(jQuery.fn, { scope: JQLitePrototype.scope, isolateScope: JQLitePrototype.isolateScope, - controller: JQLitePrototype.controller, + controller: /** @type {?} */ (JQLitePrototype).controller, injector: JQLitePrototype.injector, inheritedData: JQLitePrototype.inheritedData }); - // Method signature: - // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) - jqLitePatchJQueryRemove('remove', true, true, false); - jqLitePatchJQueryRemove('empty', false, false, false); - jqLitePatchJQueryRemove('html', false, false, true); } else { jqLite = JQLite; } + + // All nodes removed from the DOM via various jqLite/jQuery APIs like .remove() + // are passed through jqLite/jQuery.cleanData. Monkey-patch this method to fire + // the $destroy event on all removed nodes. + originalCleanData = jqLite.cleanData; + jqLite.cleanData = function(elems) { + var events; + for (var i = 0, elem; (elem = elems[i]) != null; i++) { + events = (jqLite._data(elem) || {}).events; + if (events && events.$destroy) { + jqLite(elem).triggerHandler('$destroy'); + } + } + originalCleanData(elems); + }; + angular.element = jqLite; + + // Prevent double-proxying. + bindJQueryFired = true; +} + +/** + * @ngdoc function + * @name angular.UNSAFE_restoreLegacyJqLiteXHTMLReplacement + * @module ng + * @kind function + * + * @description + * Restores the pre-1.8 behavior of jqLite that turns XHTML-like strings like + * `
` to `
` instead of `
`. + * The new behavior is a security fix. Thus, if you need to call this function, please try to adjust + * your code for this change and remove your use of this function as soon as possible. + + * Note that this only patches jqLite. If you use jQuery 3.5.0 or newer, please read the + * [jQuery 3.5 upgrade guide](https://jquery.com/upgrade-guide/3.5/) for more details + * about the workarounds. + */ +function UNSAFE_restoreLegacyJqLiteXHTMLReplacement() { + JQLite.legacyXHTMLReplacement = true; } /** @@ -1440,7 +2114,7 @@ function bindJQuery() { */ function assertArg(arg, name, reason) { if (!arg) { - throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required")); + throw ngMinErr('areq', 'Argument \'{0}\' is {1}', (name || '?'), (reason || 'required')); } return arg; } @@ -1451,7 +2125,7 @@ function assertArgFn(arg, name, acceptArrayAnnotation) { } assertArg(isFunction(arg), name, 'not a function, got ' + - (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg)); + (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg)); return arg; } @@ -1462,7 +2136,7 @@ function assertArgFn(arg, name, acceptArrayAnnotation) { */ function assertNotHasOwnProperty(name, context) { if (name === 'hasOwnProperty') { - throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context); + throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); } } @@ -1496,34 +2170,77 @@ function getter(obj, path, bindFnToScope) { /** * Return the DOM siblings between the first and last node in the given array. * @param {Array} array like object - * @returns {DOMElement} object containing the elements + * @returns {Array} the inputted object or a jqLite collection containing the nodes */ -function getBlockElements(nodes) { - var startNode = nodes[0], - endNode = nodes[nodes.length - 1]; - if (startNode === endNode) { - return jqLite(startNode); +function getBlockNodes(nodes) { + // TODO(perf): update `nodes` instead of creating a new object? + var node = nodes[0]; + var endNode = nodes[nodes.length - 1]; + var blockNodes; + + for (var i = 1; node !== endNode && (node = node.nextSibling); i++) { + if (blockNodes || nodes[i] !== node) { + if (!blockNodes) { + blockNodes = jqLite(slice.call(nodes, 0, i)); + } + blockNodes.push(node); + } } - var element = startNode; - var elements = [element]; + return blockNodes || nodes; +} + - do { - element = element.nextSibling; - if (!element) break; - elements.push(element); - } while (element !== endNode); +/** + * Creates a new object without a prototype. This object is useful for lookup without having to + * guard against prototypically inherited properties via hasOwnProperty. + * + * Related micro-benchmarks: + * - http://jsperf.com/object-create2 + * - http://jsperf.com/proto-map-lookup/2 + * - http://jsperf.com/for-in-vs-object-keys2 + * + * @returns {Object} + */ +function createMap() { + return Object.create(null); +} + +function stringify(value) { + if (value == null) { // null || undefined + return ''; + } + switch (typeof value) { + case 'string': + break; + case 'number': + value = '' + value; + break; + default: + if (hasCustomToString(value) && !isArray(value) && !isDate(value)) { + value = value.toString(); + } else { + value = toJson(value); + } + } - return jqLite(elements); + return value; } +var NODE_TYPE_ELEMENT = 1; +var NODE_TYPE_ATTRIBUTE = 2; +var NODE_TYPE_TEXT = 3; +var NODE_TYPE_COMMENT = 8; +var NODE_TYPE_DOCUMENT = 9; +var NODE_TYPE_DOCUMENT_FRAGMENT = 11; + /** * @ngdoc type * @name angular.Module * @module ng * @description * - * Interface for configuring angular {@link angular.module modules}. + * Interface for configuring AngularJS {@link angular.module modules}. */ function setupModuleLoader(window) { @@ -1550,18 +2267,18 @@ function setupModuleLoader(window) { * @module ng * @description * - * The `angular.module` is a global place for creating, registering and retrieving Angular + * The `angular.module` is a global place for creating, registering and retrieving AngularJS * modules. - * All modules (angular core or 3rd party) that should be available to an application must be + * All modules (AngularJS core or 3rd party) that should be available to an application must be * registered using this mechanism. * - * When passed two or more arguments, a new module is created. If passed only one argument, an - * existing module (the name passed as the first argument to `module`) is retrieved. + * Passing one argument retrieves an existing {@link angular.Module}, + * whereas passing more than one argument creates a new {@link angular.Module} * * * # Module * - * A module is a collection of services, directives, filters, and configuration information. + * A module is a collection of services, directives, controllers, filters, and configuration information. * `angular.module` is used to configure the {@link auto.$injector $injector}. * * ```js @@ -1589,13 +2306,16 @@ function setupModuleLoader(window) { * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. -<<<<<* @param {!Array.=} requires If specified then new module is being created. If ->>>>>* unspecified then the module is being retrieved for further configuration. - * @param {Function} configFn Optional configuration function for the module. Same as + * @param {!Array.=} requires If specified then new module is being created. If + * unspecified then the module is being retrieved for further configuration. + * @param {Function=} configFn Optional configuration function for the module. Same as * {@link angular.Module#config Module#config()}. - * @returns {module} new module with the {@link angular.Module} api. + * @returns {angular.Module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { + + var info = {}; + var assertNotHasOwnProperty = function(name, context) { if (name === 'hasOwnProperty') { throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); @@ -1608,30 +2328,73 @@ function setupModuleLoader(window) { } return ensure(modules, name, function() { if (!requires) { - throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + - "the module name or forgot to load it. If registering a module ensure that you " + - "specify the dependencies as the second argument.", name); + throw $injectorMinErr('nomod', 'Module \'{0}\' is not available! You either misspelled ' + + 'the module name or forgot to load it. If registering a module ensure that you ' + + 'specify the dependencies as the second argument.', name); } /** @type {!Array.>} */ var invokeQueue = []; + /** @type {!Array.} */ + var configBlocks = []; + /** @type {!Array.} */ var runBlocks = []; - var config = invokeLater('$injector', 'invoke'); + var config = invokeLater('$injector', 'invoke', 'push', configBlocks); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, + _configBlocks: configBlocks, _runBlocks: runBlocks, + /** + * @ngdoc method + * @name angular.Module#info + * @module ng + * + * @param {Object=} info Information about the module + * @returns {Object|Module} The current info object for this module if called as a getter, + * or `this` if called as a setter. + * + * @description + * Read and write custom information about this module. + * For example you could put the version of the module in here. + * + * ```js + * angular.module('myModule', []).info({ version: '1.0.0' }); + * ``` + * + * The version could then be read back out by accessing the module elsewhere: + * + * ``` + * var version = angular.module('myModule').info().version; + * ``` + * + * You can also retrieve this information during runtime via the + * {@link $injector#modules `$injector.modules`} property: + * + * ```js + * var version = $injector.modules['myModule'].info().version; + * ``` + */ + info: function(value) { + if (isDefined(value)) { + if (!isObject(value)) throw ngMinErr('aobj', 'Argument \'{0}\' must be an object', 'value'); + info = value; + return this; + } + return info; + }, + /** * @ngdoc property * @name angular.Module#requires * @module ng - * @returns {Array.} List of module names which must be loaded before this module. + * * @description * Holds the list of modules which the injector will load before the current module is * loaded. @@ -1642,8 +2405,9 @@ function setupModuleLoader(window) { * @ngdoc property * @name angular.Module#name * @module ng - * @returns {string} Name of the module. + * * @description + * Name of the module. */ name: name, @@ -1658,7 +2422,7 @@ function setupModuleLoader(window) { * @description * See {@link auto.$provide#provider $provide.provider()}. */ - provider: invokeLater('$provide', 'provider'), + provider: invokeLaterAndSetModuleName('$provide', 'provider'), /** * @ngdoc method @@ -1669,7 +2433,7 @@ function setupModuleLoader(window) { * @description * See {@link auto.$provide#factory $provide.factory()}. */ - factory: invokeLater('$provide', 'factory'), + factory: invokeLaterAndSetModuleName('$provide', 'factory'), /** * @ngdoc method @@ -1680,7 +2444,7 @@ function setupModuleLoader(window) { * @description * See {@link auto.$provide#service $provide.service()}. */ - service: invokeLater('$provide', 'service'), + service: invokeLaterAndSetModuleName('$provide', 'service'), /** * @ngdoc method @@ -1700,12 +2464,24 @@ function setupModuleLoader(window) { * @param {string} name constant name * @param {*} object Constant value. * @description - * Because the constant are fixed, they get applied before other provide methods. + * Because the constants are fixed, they get applied before other provide methods. * See {@link auto.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), - /** + /** + * @ngdoc method + * @name angular.Module#decorator + * @module ng + * @param {string} name The name of the service to decorate. + * @param {Function} decorFn This function will be invoked when the service needs to be + * instantiated and should return the decorated service instance. + * @description + * See {@link auto.$provide#decorator $provide.decorator()}. + */ + decorator: invokeLaterAndSetModuleName('$provide', 'decorator', configBlocks), + + /** * @ngdoc method * @name angular.Module#animation * @module ng @@ -1718,7 +2494,7 @@ function setupModuleLoader(window) { * * * Defines an animation hook that can be later used with - * {@link ngAnimate.$animate $animate} service and directives that use this service. + * {@link $animate $animate} service and directives that use this service. * * ```js * module.animation('.animation-name', function($inject1, $inject2) { @@ -1734,21 +2510,28 @@ function setupModuleLoader(window) { * }) * ``` * - * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and + * See {@link ng.$animateProvider#register $animateProvider.register()} and * {@link ngAnimate ngAnimate module} for more information. */ - animation: invokeLater('$animateProvider', 'register'), + animation: invokeLaterAndSetModuleName('$animateProvider', 'register'), /** * @ngdoc method * @name angular.Module#filter * @module ng - * @param {string} name Filter name. + * @param {string} name Filter name - this must be a valid AngularJS expression identifier * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. + * + *
+ * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`. + * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace + * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores + * (`myapp_subsection_filterx`). + *
*/ - filter: invokeLater('$filterProvider', 'register'), + filter: invokeLaterAndSetModuleName('$filterProvider', 'register'), /** * @ngdoc method @@ -1760,7 +2543,7 @@ function setupModuleLoader(window) { * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ - controller: invokeLater('$controllerProvider', 'register'), + controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'), /** * @ngdoc method @@ -1773,7 +2556,21 @@ function setupModuleLoader(window) { * @description * See {@link ng.$compileProvider#directive $compileProvider.directive()}. */ - directive: invokeLater('$compileProvider', 'directive'), + directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'), + + /** + * @ngdoc method + * @name angular.Module#component + * @module ng + * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match ``), + * or an object map of components where the keys are the names and the values are the component definition objects. + * @param {Object} options Component definition object (a simplified + * {@link ng.$compile#directive-definition-object directive definition object}) + * + * @description + * See {@link ng.$compileProvider#component $compileProvider.component()}. + */ + component: invokeLaterAndSetModuleName('$compileProvider', 'component'), /** * @ngdoc method @@ -1782,7 +2579,15 @@ function setupModuleLoader(window) { * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description - * Use this method to register work which needs to be performed on module loading. + * Use this method to configure services by injecting their + * {@link angular.Module#provider `providers`}, e.g. for adding routes to the + * {@link ngRoute.$routeProvider $routeProvider}. + * + * Note that you can only inject {@link angular.Module#provider `providers`} and + * {@link angular.Module#constant `constants`} into this function. + * + * For more about how to configure services, see + * {@link providers#provider-recipe Provider Recipe}. */ config: config, @@ -1806,7 +2611,7 @@ function setupModuleLoader(window) { config(configFn); } - return moduleInstance; + return moduleInstance; /** * @param {string} provider @@ -1814,9 +2619,24 @@ function setupModuleLoader(window) { * @param {String=} insertMethod * @returns {angular.Module} */ - function invokeLater(provider, method, insertMethod) { + function invokeLater(provider, method, insertMethod, queue) { + if (!queue) queue = invokeQueue; return function() { - invokeQueue[insertMethod || 'push']([provider, method, arguments]); + queue[insertMethod || 'push']([provider, method, arguments]); + return moduleInstance; + }; + } + + /** + * @param {string} provider + * @param {string} method + * @returns {angular.Module} + */ + function invokeLaterAndSetModuleName(provider, method, queue) { + if (!queue) queue = invokeQueue; + return function(recipeName, factoryFunction) { + if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name; + queue.push([provider, method, arguments]); return moduleInstance; }; } @@ -1826,81 +2646,167 @@ function setupModuleLoader(window) { } -/* global - angularModule: true, - version: true, - - $LocaleProvider, - $CompileProvider, - - htmlAnchorDirective, - inputDirective, - inputDirective, - formDirective, - scriptDirective, - selectDirective, - styleDirective, - optionDirective, - ngBindDirective, - ngBindHtmlDirective, - ngBindTemplateDirective, - ngClassDirective, - ngClassEvenDirective, - ngClassOddDirective, - ngCspDirective, - ngCloakDirective, - ngControllerDirective, - ngFormDirective, - ngHideDirective, - ngIfDirective, - ngIncludeDirective, - ngIncludeFillContentDirective, - ngInitDirective, - ngNonBindableDirective, - ngPluralizeDirective, - ngRepeatDirective, - ngShowDirective, - ngStyleDirective, - ngSwitchDirective, - ngSwitchWhenDirective, - ngSwitchDefaultDirective, - ngOptionsDirective, - ngTranscludeDirective, - ngModelDirective, - ngListDirective, - ngChangeDirective, - requiredDirective, - requiredDirective, - ngValueDirective, - ngAttributeAliasDirectives, - ngEventDirectives, - - $AnchorScrollProvider, - $AnimateProvider, - $BrowserProvider, - $CacheFactoryProvider, - $ControllerProvider, - $DocumentProvider, - $ExceptionHandlerProvider, - $FilterProvider, - $InterpolateProvider, - $IntervalProvider, - $HttpProvider, - $HttpBackendProvider, - $LocationProvider, - $LogProvider, - $ParseProvider, - $RootScopeProvider, - $QProvider, - $$SanitizeUriProvider, - $SceProvider, - $SceDelegateProvider, - $SnifferProvider, - $TemplateCacheProvider, - $TimeoutProvider, - $$RAFProvider, - $$AsyncCallbackProvider, - $WindowProvider +/* global shallowCopy: true */ + +/** + * Creates a shallow copy of an object, an array or a primitive. + * + * Assumes that there are no proto properties for objects. + */ +function shallowCopy(src, dst) { + if (isArray(src)) { + dst = dst || []; + + for (var i = 0, ii = src.length; i < ii; i++) { + dst[i] = src[i]; + } + } else if (isObject(src)) { + dst = dst || {}; + + for (var key in src) { + if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { + dst[key] = src[key]; + } + } + } + + return dst || src; +} + +/* exported toDebugString */ + +function serializeObject(obj, maxDepth) { + var seen = []; + + // There is no direct way to stringify object until reaching a specific depth + // and a very deep object can cause a performance issue, so we copy the object + // based on this specific depth and then stringify it. + if (isValidObjectMaxDepth(maxDepth)) { + // This file is also included in `angular-loader`, so `copy()` might not always be available in + // the closure. Therefore, it is lazily retrieved as `angular.copy()` when needed. + obj = angular.copy(obj, null, maxDepth); + } + return JSON.stringify(obj, function(key, val) { + val = toJsonReplacer(key, val); + if (isObject(val)) { + + if (seen.indexOf(val) >= 0) return '...'; + + seen.push(val); + } + return val; + }); +} + +function toDebugString(obj, maxDepth) { + if (typeof obj === 'function') { + return obj.toString().replace(/ \{[\s\S]*$/, ''); + } else if (isUndefined(obj)) { + return 'undefined'; + } else if (typeof obj !== 'string') { + return serializeObject(obj, maxDepth); + } + return obj; +} + +/* global angularModule: true, + version: true, + + $CompileProvider, + + htmlAnchorDirective, + inputDirective, + hiddenInputBrowserCacheDirective, + formDirective, + scriptDirective, + selectDirective, + optionDirective, + ngBindDirective, + ngBindHtmlDirective, + ngBindTemplateDirective, + ngClassDirective, + ngClassEvenDirective, + ngClassOddDirective, + ngCloakDirective, + ngControllerDirective, + ngFormDirective, + ngHideDirective, + ngIfDirective, + ngIncludeDirective, + ngIncludeFillContentDirective, + ngInitDirective, + ngNonBindableDirective, + ngPluralizeDirective, + ngRefDirective, + ngRepeatDirective, + ngShowDirective, + ngStyleDirective, + ngSwitchDirective, + ngSwitchWhenDirective, + ngSwitchDefaultDirective, + ngOptionsDirective, + ngTranscludeDirective, + ngModelDirective, + ngListDirective, + ngChangeDirective, + patternDirective, + patternDirective, + requiredDirective, + requiredDirective, + minlengthDirective, + minlengthDirective, + maxlengthDirective, + maxlengthDirective, + ngValueDirective, + ngModelOptionsDirective, + ngAttributeAliasDirectives, + ngEventDirectives, + + $AnchorScrollProvider, + $AnimateProvider, + $CoreAnimateCssProvider, + $$CoreAnimateJsProvider, + $$CoreAnimateQueueProvider, + $$AnimateRunnerFactoryProvider, + $$AnimateAsyncRunFactoryProvider, + $BrowserProvider, + $CacheFactoryProvider, + $ControllerProvider, + $DateProvider, + $DocumentProvider, + $$IsDocumentHiddenProvider, + $ExceptionHandlerProvider, + $FilterProvider, + $$ForceReflowProvider, + $InterpolateProvider, + $$IntervalFactoryProvider, + $IntervalProvider, + $HttpProvider, + $HttpParamSerializerProvider, + $HttpParamSerializerJQLikeProvider, + $HttpBackendProvider, + $xhrFactoryProvider, + $jsonpCallbacksProvider, + $LocationProvider, + $LogProvider, + $$MapProvider, + $ParseProvider, + $RootScopeProvider, + $QProvider, + $$QProvider, + $$SanitizeUriProvider, + $SceProvider, + $SceDelegateProvider, + $SnifferProvider, + $$TaskTrackerFactoryProvider, + $TemplateCacheProvider, + $TemplateRequestProvider, + $$TestabilityProvider, + $TimeoutProvider, + $$RAFProvider, + $WindowProvider, + $$jqLiteProvider, + $$CookieReaderProvider */ @@ -1909,8 +2815,9 @@ function setupModuleLoader(window) { * @name angular.version * @module ng * @description - * An object that contains information about the current AngularJS version. This object has the - * following properties: + * An object that contains information about the current AngularJS version. + * + * This object has the following properties: * * - `full` – `{string}` – Full version string, such as "0.9.18". * - `major` – `{number}` – Major version number, such as "0". @@ -1919,28 +2826,32 @@ function setupModuleLoader(window) { * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat". */ var version = { - full: '1.2.16', // all of these placeholder strings will be replaced by grunt's - major: 1, // package task - minor: 2, - dot: 16, - codeName: 'badger-enumeration' + // These placeholder strings will be replaced by grunt's `build` task. + // They need to be double- or single-quoted. + full: '1.8.2', + major: 1, + minor: 8, + dot: 2, + codeName: 'meteoric-mining' }; -function publishExternalAPI(angular){ +function publishExternalAPI(angular) { extend(angular, { + 'errorHandlingConfig': errorHandlingConfig, 'bootstrap': bootstrap, 'copy': copy, 'extend': extend, + 'merge': merge, 'equals': equals, 'element': jqLite, 'forEach': forEach, 'injector': createInjector, - 'noop':noop, - 'bind':bind, + 'noop': noop, + 'bind': bind, 'toJson': toJson, 'fromJson': fromJson, - 'identity':identity, + 'identity': identity, 'isUndefined': isUndefined, 'isDefined': isDefined, 'isString': isString, @@ -1951,19 +2862,20 @@ function publishExternalAPI(angular){ 'isArray': isArray, 'version': version, 'isDate': isDate, - 'lowercase': lowercase, - 'uppercase': uppercase, - 'callbacks': {counter: 0}, + 'callbacks': {$$counter: 0}, + 'getTestability': getTestability, + 'reloadWithDebugInfo': reloadWithDebugInfo, + 'UNSAFE_restoreLegacyJqLiteXHTMLReplacement': UNSAFE_restoreLegacyJqLiteXHTMLReplacement, '$$minErr': minErr, - '$$csp': csp + '$$csp': csp, + '$$encodeUriSegment': encodeUriSegment, + '$$encodeUriQuery': encodeUriQuery, + '$$lowercase': lowercase, + '$$stringify': stringify, + '$$uppercase': uppercase }); angularModule = setupModuleLoader(window); - try { - angularModule('ngLocale'); - } catch (e) { - angularModule('ngLocale', []).provider('$locale', $LocaleProvider); - } angularModule('ng', ['ngLocale'], ['$provide', function ngModule($provide) { @@ -1979,7 +2891,6 @@ function publishExternalAPI(angular){ form: formDirective, script: scriptDirective, select: selectDirective, - style: styleDirective, option: optionDirective, ngBind: ngBindDirective, ngBindHtml: ngBindHtmlDirective, @@ -1996,6 +2907,7 @@ function publishExternalAPI(angular){ ngInit: ngInitDirective, ngNonBindable: ngNonBindableDirective, ngPluralize: ngPluralizeDirective, + ngRef: ngRefDirective, ngRepeat: ngRepeatDirective, ngShow: ngShowDirective, ngStyle: ngStyleDirective, @@ -2007,52 +2919,88 @@ function publishExternalAPI(angular){ ngModel: ngModelDirective, ngList: ngListDirective, ngChange: ngChangeDirective, + pattern: patternDirective, + ngPattern: patternDirective, required: requiredDirective, ngRequired: requiredDirective, - ngValue: ngValueDirective + minlength: minlengthDirective, + ngMinlength: minlengthDirective, + maxlength: maxlengthDirective, + ngMaxlength: maxlengthDirective, + ngValue: ngValueDirective, + ngModelOptions: ngModelOptionsDirective }). directive({ - ngInclude: ngIncludeFillContentDirective + ngInclude: ngIncludeFillContentDirective, + input: hiddenInputBrowserCacheDirective }). directive(ngAttributeAliasDirectives). directive(ngEventDirectives); $provide.provider({ $anchorScroll: $AnchorScrollProvider, $animate: $AnimateProvider, + $animateCss: $CoreAnimateCssProvider, + $$animateJs: $$CoreAnimateJsProvider, + $$animateQueue: $$CoreAnimateQueueProvider, + $$AnimateRunner: $$AnimateRunnerFactoryProvider, + $$animateAsyncRun: $$AnimateAsyncRunFactoryProvider, $browser: $BrowserProvider, $cacheFactory: $CacheFactoryProvider, $controller: $ControllerProvider, $document: $DocumentProvider, + $$isDocumentHidden: $$IsDocumentHiddenProvider, $exceptionHandler: $ExceptionHandlerProvider, $filter: $FilterProvider, + $$forceReflow: $$ForceReflowProvider, $interpolate: $InterpolateProvider, $interval: $IntervalProvider, + $$intervalFactory: $$IntervalFactoryProvider, $http: $HttpProvider, + $httpParamSerializer: $HttpParamSerializerProvider, + $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider, $httpBackend: $HttpBackendProvider, + $xhrFactory: $xhrFactoryProvider, + $jsonpCallbacks: $jsonpCallbacksProvider, $location: $LocationProvider, $log: $LogProvider, $parse: $ParseProvider, $rootScope: $RootScopeProvider, $q: $QProvider, + $$q: $$QProvider, $sce: $SceProvider, $sceDelegate: $SceDelegateProvider, $sniffer: $SnifferProvider, + $$taskTrackerFactory: $$TaskTrackerFactoryProvider, $templateCache: $TemplateCacheProvider, + $templateRequest: $TemplateRequestProvider, + $$testability: $$TestabilityProvider, $timeout: $TimeoutProvider, $window: $WindowProvider, $$rAF: $$RAFProvider, - $$asyncCallback : $$AsyncCallbackProvider + $$jqLite: $$jqLiteProvider, + $$Map: $$MapProvider, + $$cookieReader: $$CookieReaderProvider }); } - ]); + ]) + .info({ angularVersion: '1.8.2' }); } -/* global +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Any commits to this file should be reviewed with security in mind. * + * Changes to this file can potentially create security vulnerabilities. * + * An approval from 2 Core members with history of modifying * + * this file is required. * + * * + * Does the change somehow allow for arbitrary javascript to be executed? * + * Or allows for someone to change the prototype of built-in objects? * + * Or gives undesired access to variables likes document or window? * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ - -JQLitePrototype, - -addEventListenerFn, - -removeEventListenerFn, - -BOOLEAN_ATTR +/* global + JQLitePrototype: true, + BOOLEAN_ATTR: true, + ALIASED_ATTR: true */ ////////////////////////////////// @@ -2063,37 +3011,46 @@ function publishExternalAPI(angular){ * @ngdoc function * @name angular.element * @module ng - * @function + * @kind function * * @description * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element. * * If jQuery is available, `angular.element` is an alias for the * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element` - * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite." + * delegates to AngularJS's built-in subset of jQuery, called "jQuery lite" or **jqLite**. * - *
jqLite is a tiny, API-compatible subset of jQuery that allows - * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most - * commonly needed functionality with the goal of having a very small footprint.
+ * jqLite is a tiny, API-compatible subset of jQuery that allows + * AngularJS to manipulate the DOM in a cross-browser compatible way. jqLite implements only the most + * commonly needed functionality with the goal of having a very small footprint. * - * To use jQuery, simply load it before `DOMContentLoaded` event fired. + * To use `jQuery`, simply ensure it is loaded before the `angular.js` file. You can also use the + * {@link ngJq `ngJq`} directive to specify that jqlite should be used over jQuery, or to use a + * specific version of jQuery if multiple versions exist on the page. * - *
**Note:** all element references in Angular are always wrapped with jQuery or - * jqLite; they are never raw DOM references.
+ *
**Note:** All element references in AngularJS are always wrapped with jQuery or + * jqLite (such as the element argument in a directive's compile / link function). They are never raw DOM references.
* - * ## Angular's jqLite + *
**Note:** Keep in mind that this function will not find elements + * by tag name / CSS selector. For lookups by tag name, try instead `angular.element(document).find(...)` + * or `$document.find()`, or use the standard DOM APIs, e.g. `document.querySelectorAll()`.
+ * + * ## AngularJS's jqLite * jqLite provides only the following jQuery methods: * - * - [`addClass()`](http://api.jquery.com/addClass/) + * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument * - [`after()`](http://api.jquery.com/after/) - * - [`append()`](http://api.jquery.com/append/) - * - [`attr()`](http://api.jquery.com/attr/) - * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData + * - [`append()`](http://api.jquery.com/append/) - Contrary to jQuery, this doesn't clone elements + * so will not work correctly when invoked on a jqLite object containing more than one DOM node + * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters + * - [`bind()`](http://api.jquery.com/bind/) (_deprecated_, use [`on()`](http://api.jquery.com/on/)) - Does not support namespaces, selectors or eventData * - [`children()`](http://api.jquery.com/children/) - Does not support selectors * - [`clone()`](http://api.jquery.com/clone/) * - [`contents()`](http://api.jquery.com/contents/) - * - [`css()`](http://api.jquery.com/css/) + * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. + * As a setter, does not convert numbers to strings or append 'px', and also does not have automatic property prefixing. * - [`data()`](http://api.jquery.com/data/) + * - [`detach()`](http://api.jquery.com/detach/) * - [`empty()`](http://api.jquery.com/empty/) * - [`eq()`](http://api.jquery.com/eq/) * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name @@ -2101,26 +3058,36 @@ function publishExternalAPI(angular){ * - [`html()`](http://api.jquery.com/html/) * - [`next()`](http://api.jquery.com/next/) - Does not support selectors * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData - * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors + * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors * - [`prepend()`](http://api.jquery.com/prepend/) * - [`prop()`](http://api.jquery.com/prop/) - * - [`ready()`](http://api.jquery.com/ready/) + * - [`ready()`](http://api.jquery.com/ready/) (_deprecated_, use `angular.element(callback)` instead of `angular.element(document).ready(callback)`) * - [`remove()`](http://api.jquery.com/remove/) - * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - * - [`removeClass()`](http://api.jquery.com/removeClass/) + * - [`removeAttr()`](http://api.jquery.com/removeAttr/) - Does not support multiple attributes + * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument * - [`removeData()`](http://api.jquery.com/removeData/) * - [`replaceWith()`](http://api.jquery.com/replaceWith/) * - [`text()`](http://api.jquery.com/text/) - * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. - * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces + * - [`toggleClass()`](http://api.jquery.com/toggleClass/) - Does not support a function as first argument + * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers + * - [`unbind()`](http://api.jquery.com/unbind/) (_deprecated_, use [`off()`](http://api.jquery.com/off/)) - Does not support namespaces or event object as parameter * - [`val()`](http://api.jquery.com/val/) * - [`wrap()`](http://api.jquery.com/wrap/) * + * jqLite also provides a method restoring pre-1.8 insecure treatment of XHTML-like tags. + * This legacy behavior turns input like `
` to `
` + * instead of `
` like version 1.8 & newer do. To restore it, invoke: + * ```js + * angular.UNSAFE_restoreLegacyJqLiteXHTMLReplacement(); + * ``` + * Note that this only patches jqLite. If you use jQuery 3.5.0 or newer, please read the + * [jQuery 3.5 upgrade guide](https://jquery.com/upgrade-guide/3.5/) for more details + * about the workarounds. + * * ## jQuery/jqLite Extras - * Angular also provides the following additional methods and events to both jQuery and jqLite: + * AngularJS also provides the following additional methods and events to both jQuery and jqLite: * * ### Events * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event @@ -2134,31 +3101,31 @@ function publishExternalAPI(angular){ * `'ngModel'`). * - `injector()` - retrieves the injector of the current element or its parent. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current - * element or its parent. + * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to + * be enabled. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the * current element. This getter should be used only on elements that contain a directive which starts a new isolate * scope. Calling `scope()` on this element always returns the original non-isolate scope. + * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top * parent element is reached. * + * @knownIssue You cannot spy on `angular.element` if you are using Jasmine version 1.x. See + * https://github.com/angular/angular.js/issues/14251 for more information. + * * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery. * @returns {Object} jQuery object. */ +JQLite.expando = 'ng339'; + var jqCache = JQLite.cache = {}, - jqName = JQLite.expando = 'ng-' + new Date().getTime(), - jqId = 1, - addEventListenerFn = (window.document.addEventListener - ? function(element, type, fn) {element.addEventListener(type, fn, false);} - : function(element, type, fn) {element.attachEvent('on' + type, fn);}), - removeEventListenerFn = (window.document.removeEventListener - ? function(element, type, fn) {element.removeEventListener(type, fn, false); } - : function(element, type, fn) {element.detachEvent('on' + type, fn); }); + jqId = 1; /* * !!! This is an undocumented "private" function !!! */ -var jqData = JQLite._data = function(node) { +JQLite._data = function(node) { //jQuery always returns an object on cache miss return this.cache[node[this.expando]] || {}; }; @@ -2166,154 +3133,196 @@ var jqData = JQLite._data = function(node) { function jqNextId() { return ++jqId; } -var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g; -var MOZ_HACK_REGEXP = /^moz([A-Z])/; +var DASH_LOWERCASE_REGEXP = /-([a-z])/g; +var MS_HACK_REGEXP = /^-ms-/; +var MOUSE_EVENT_MAP = { mouseleave: 'mouseout', mouseenter: 'mouseover' }; var jqLiteMinErr = minErr('jqLite'); /** - * Converts snake_case to camelCase. - * Also there is special case for Moz prefix starting with upper case letter. + * Converts kebab-case to camelCase. + * There is also a special case for the ms prefix starting with a lowercase letter. * @param name Name to normalize */ -function camelCase(name) { - return name. - replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) { - return offset ? letter.toUpperCase() : letter; - }). - replace(MOZ_HACK_REGEXP, 'Moz$1'); +function cssKebabToCamel(name) { + return kebabToCamel(name.replace(MS_HACK_REGEXP, 'ms-')); } -///////////////////////////////////////////// -// jQuery mutation patch -// -// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a -// $destroy event on all DOM nodes being removed. -// -///////////////////////////////////////////// +function fnCamelCaseReplace(all, letter) { + return letter.toUpperCase(); +} -function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) { - var originalJqFn = jQuery.fn[name]; - originalJqFn = originalJqFn.$original || originalJqFn; - removePatch.$original = originalJqFn; - jQuery.fn[name] = removePatch; - - function removePatch(param) { - // jshint -W040 - var list = filterElems && param ? [this.filter(param)] : [this], - fireEvent = dispatchThis, - set, setIndex, setLength, - element, childIndex, childLength, children; - - if (!getterIfNoArguments || param != null) { - while(list.length) { - set = list.shift(); - for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) { - element = jqLite(set[setIndex]); - if (fireEvent) { - element.triggerHandler('$destroy'); - } else { - fireEvent = !fireEvent; - } - for(childIndex = 0, childLength = (children = element.children()).length; - childIndex < childLength; - childIndex++) { - list.push(jQuery(children[childIndex])); - } - } - } - } - return originalJqFn.apply(this, arguments); - } +/** + * Converts kebab-case to camelCase. + * @param name Name to normalize + */ +function kebabToCamel(name) { + return name + .replace(DASH_LOWERCASE_REGEXP, fnCamelCaseReplace); } -var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/; +var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/; var HTML_REGEXP = /<|&#?\w+;/; -var TAG_NAME_REGEXP = /<([\w:]+)/; -var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi; - +var TAG_NAME_REGEXP = /<([\w:-]+)/; +var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi; + +// Table parts need to be wrapped with `` or they're +// stripped to their contents when put in a div. +// XHTML parsers do not magically insert elements in the +// same way that tag soup parsers do, so we cannot shorten +// this by omitting or other required elements. var wrapMap = { - 'option': [1, ''], - - 'thead': [1, '
', '
'], - 'col': [2, '', '
'], - 'tr': [2, '', '
'], - 'td': [3, '', '
'], - '_default': [0, "", ""] + thead: ['table'], + col: ['colgroup', 'table'], + tr: ['tbody', 'table'], + td: ['tr', 'tbody', 'table'] }; -wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; +// Support: IE <10 only +// IE 9 requires an option wrapper & it needs to have the whole table structure +// set up in advance; assigning `""` to `tr.innerHTML` doesn't work, etc. +var wrapMapIE9 = { + option: [1, ''], + _default: [0, '', ''] +}; + +for (var key in wrapMap) { + var wrapMapValueClosing = wrapMap[key]; + var wrapMapValue = wrapMapValueClosing.slice().reverse(); + wrapMapIE9[key] = [wrapMapValue.length, '<' + wrapMapValue.join('><') + '>', '']; +} + +wrapMapIE9.optgroup = wrapMapIE9.option; + function jqLiteIsTextNode(html) { return !HTML_REGEXP.test(html); } +function jqLiteAcceptsData(node) { + // The window object can accept data but has no nodeType + // Otherwise we are only interested in elements (1) and documents (9) + var nodeType = node.nodeType; + return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT; +} + +function jqLiteHasData(node) { + for (var key in jqCache[node.ng339]) { + return true; + } + return false; +} + function jqLiteBuildFragment(html, context) { - var elem, tmp, tag, wrap, + var tmp, tag, wrap, finalHtml, fragment = context.createDocumentFragment(), - nodes = [], i, j, jj; + nodes = [], i; if (jqLiteIsTextNode(html)) { // Convert non-html into a text node nodes.push(context.createTextNode(html)); } else { - tmp = fragment.appendChild(context.createElement('div')); // Convert html into DOM nodes - tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase(); - wrap = wrapMap[tag] || wrapMap._default; - tmp.innerHTML = '
 
' + - wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1>") + wrap[2]; - tmp.removeChild(tmp.firstChild); - - // Descend through wrappers to the right content - i = wrap[0]; - while (i--) { - tmp = tmp.lastChild; + tmp = fragment.appendChild(context.createElement('div')); + tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase(); + finalHtml = JQLite.legacyXHTMLReplacement ? + html.replace(XHTML_TAG_REGEXP, '<$1>') : + html; + + if (msie < 10) { + wrap = wrapMapIE9[tag] || wrapMapIE9._default; + tmp.innerHTML = wrap[1] + finalHtml + wrap[2]; + + // Descend through wrappers to the right content + i = wrap[0]; + while (i--) { + tmp = tmp.firstChild; + } + } else { + wrap = wrapMap[tag] || []; + + // Create wrappers & descend into them + i = wrap.length; + while (--i > -1) { + tmp.appendChild(window.document.createElement(wrap[i])); + tmp = tmp.firstChild; + } + + tmp.innerHTML = finalHtml; } - for (j=0, jj=tmp.childNodes.length; j 0)) { + element.removeEventListener(type, handle); delete events[type]; - } else { - arrayRemove(events[type] || [], fn); + } + }; + + forEach(type.split(' '), function(type) { + removeHandler(type); + if (MOUSE_EVENT_MAP[type]) { + removeHandler(MOUSE_EVENT_MAP[type]); } }); } + + removeIfEmptyData(element); } function jqLiteRemoveData(element, name) { - var expandoId = element[jqName], - expandoStore = jqCache[expandoId]; + var expandoId = element.ng339; + var expandoStore = expandoId && jqCache[expandoId]; if (expandoStore) { if (name) { - delete jqCache[expandoId].data[name]; - return; + delete expandoStore.data[name]; + } else { + expandoStore.data = {}; } - if (expandoStore.handle) { - expandoStore.events.$destroy && expandoStore.handle({}, '$destroy'); - jqLiteOff(element); - } - delete jqCache[expandoId]; - element[jqName] = undefined; // ie does not allow deletion of attributes on elements. + removeIfEmptyData(element); } } -function jqLiteExpandoStore(element, key, value) { - var expandoId = element[jqName], - expandoStore = jqCache[expandoId || -1]; - if (isDefined(value)) { - if (!expandoStore) { - element[jqName] = expandoId = jqNextId(); - expandoStore = jqCache[expandoId] = {}; - } - expandoStore[key] = value; - } else { - return expandoStore && expandoStore[key]; +function jqLiteExpandoStore(element, createIfNecessary) { + var expandoId = element.ng339, + expandoStore = expandoId && jqCache[expandoId]; + + if (createIfNecessary && !expandoStore) { + element.ng339 = expandoId = jqNextId(); + expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined}; } + + return expandoStore; } + function jqLiteData(element, key, value) { - var data = jqLiteExpandoStore(element, 'data'), - isSetter = isDefined(value), - keyDefined = !isSetter && isDefined(key), - isSimpleGetter = keyDefined && !isObject(key); + if (jqLiteAcceptsData(element)) { + var prop; - if (!data && !isSimpleGetter) { - jqLiteExpandoStore(element, 'data', data = {}); - } + var isSimpleSetter = isDefined(value); + var isSimpleGetter = !isSimpleSetter && key && !isObject(key); + var massGetter = !key; + var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter); + var data = expandoStore && expandoStore.data; - if (isSetter) { - data[key] = value; - } else { - if (keyDefined) { - if (isSimpleGetter) { - // don't create data in this case. - return data && data[key]; + if (isSimpleSetter) { // data('key', value) + data[kebabToCamel(key)] = value; + } else { + if (massGetter) { // data() + return data; } else { - extend(data, key); + if (isSimpleGetter) { // data('key') + // don't force creation of expandoStore if it doesn't exist yet + return data && data[kebabToCamel(key)]; + } else { // mass-setter: data({key1: val1, key2: val2}) + for (prop in key) { + data[kebabToCamel(prop)] = key[prop]; + } + } } - } else { - return data; } } } function jqLiteHasClass(element, selector) { if (!element.getAttribute) return false; - return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " "). - indexOf( " " + selector + " " ) > -1); + return ((' ' + (element.getAttribute('class') || '') + ' ').replace(/[\n\t]/g, ' '). + indexOf(' ' + selector + ' ') > -1); } function jqLiteRemoveClass(element, cssClasses) { if (cssClasses && element.setAttribute) { + var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') + .replace(/[\n\t]/g, ' '); + var newClasses = existingClasses; + forEach(cssClasses.split(' '), function(cssClass) { - element.setAttribute('class', trim( - (" " + (element.getAttribute('class') || '') + " ") - .replace(/[\n\t]/g, " ") - .replace(" " + trim(cssClass) + " ", " ")) - ); + cssClass = trim(cssClass); + newClasses = newClasses.replace(' ' + cssClass + ' ', ' '); }); + + if (newClasses !== existingClasses) { + element.setAttribute('class', trim(newClasses)); + } } } function jqLiteAddClass(element, cssClasses) { if (cssClasses && element.setAttribute) { var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ') - .replace(/[\n\t]/g, " "); + .replace(/[\n\t]/g, ' '); + var newClasses = existingClasses; forEach(cssClasses.split(' '), function(cssClass) { cssClass = trim(cssClass); - if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) { - existingClasses += cssClass + ' '; + if (newClasses.indexOf(' ' + cssClass + ' ') === -1) { + newClasses += cssClass + ' '; } }); - element.setAttribute('class', trim(existingClasses)); + if (newClasses !== existingClasses) { + element.setAttribute('class', trim(newClasses)); + } } } + function jqLiteAddNodes(root, elements) { + // THIS CODE IS VERY HOT. Don't make changes without benchmarking. + if (elements) { - elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements)) - ? elements - : [ elements ]; - for(var i=0; i < elements.length; i++) { - root.push(elements[i]); + + // if a Node (the most common case) + if (elements.nodeType) { + root[root.length++] = elements; + } else { + var length = elements.length; + + // if an Array or NodeList and not a Window + if (typeof length === 'number' && elements.window !== elements) { + if (length) { + for (var i = 0; i < length; i++) { + root[root.length++] = elements[i]; + } + } + } else { + root[root.length++] = elements; + } } } } + function jqLiteController(element, name) { - return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller'); + return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller'); } function jqLiteInheritedData(element, name, value) { - element = jqLite(element); - // if element is the document object work with the html element instead // this makes $(document).scope() possible - if(element[0].nodeType == 9) { - element = element.find('html'); + if (element.nodeType === NODE_TYPE_DOCUMENT) { + element = element.documentElement; } var names = isArray(name) ? name : [name]; - while (element.length) { - var node = element[0]; + while (element) { for (var i = 0, ii = names.length; i < ii; i++) { - if ((value = element.data(names[i])) !== undefined) return value; + if (isDefined(value = jqLite.data(element, names[i]))) return value; } // If dealing with a document fragment node with a host element, and no parent, use the host // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM // to lookup parent controllers. - element = jqLite(node.parentNode || (node.nodeType === 11 && node.host)); + element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host); } } function jqLiteEmpty(element) { - for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { - jqLiteDealoc(childNodes[i]); - } + jqLiteDealoc(element, true); while (element.firstChild) { element.removeChild(element.firstChild); } } +function jqLiteRemove(element, keepData) { + if (!keepData) jqLiteDealoc(element); + var parent = element.parentNode; + if (parent) parent.removeChild(element); +} + + +function jqLiteDocumentLoaded(action, win) { + win = win || window; + if (win.document.readyState === 'complete') { + // Force the action to be run async for consistent behavior + // from the action's point of view + // i.e. it will definitely not be in a $apply + win.setTimeout(action); + } else { + // No need to unbind this handler as load is only ever called once + jqLite(win).on('load', action); + } +} + +function jqLiteReady(fn) { + function trigger() { + window.document.removeEventListener('DOMContentLoaded', trigger); + window.removeEventListener('load', trigger); + fn(); + } + + // check if document is already loaded + if (window.document.readyState === 'complete') { + window.setTimeout(fn); + } else { + // We can not use jqLite since we are not done loading and jQuery could be loaded later. + + // Works for modern browsers and IE9 + window.document.addEventListener('DOMContentLoaded', trigger); + + // Fallback to window.onload for others + window.addEventListener('load', trigger); + } +} + ////////////////////////////////////////// // Functions which are declared directly. ////////////////////////////////////////// var JQLitePrototype = JQLite.prototype = { - ready: function(fn) { - var fired = false; - - function trigger() { - if (fired) return; - fired = true; - fn(); - } - - // check if document already is loaded - if (document.readyState === 'complete'){ - setTimeout(trigger); - } else { - this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9 - // we can not use jqLite since we are not done loading and jQuery could be loaded later. - // jshint -W064 - JQLite(window).on('load', trigger); // fallback to window.onload for others - // jshint +W064 - } - }, + ready: jqLiteReady, toString: function() { var value = []; - forEach(this, function(e){ value.push('' + e);}); + forEach(this, function(e) { value.push('' + e);}); return '[' + value.join(', ') + ']'; }, @@ -2547,29 +3633,55 @@ forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), }); var BOOLEAN_ELEMENTS = {}; forEach('input,select,option,textarea,button,form,details'.split(','), function(value) { - BOOLEAN_ELEMENTS[uppercase(value)] = true; + BOOLEAN_ELEMENTS[value] = true; }); +var ALIASED_ATTR = { + 'ngMinlength': 'minlength', + 'ngMaxlength': 'maxlength', + 'ngMin': 'min', + 'ngMax': 'max', + 'ngPattern': 'pattern', + 'ngStep': 'step' +}; function getBooleanAttrName(element, name) { // check dom last since we will most likely fail on name var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()]; // booleanAttr is here twice to minimize DOM access - return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr; + return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr; } +function getAliasedAttrName(name) { + return ALIASED_ATTR[name]; +} + +forEach({ + data: jqLiteData, + removeData: jqLiteRemoveData, + hasData: jqLiteHasData, + cleanData: function jqLiteCleanData(nodes) { + for (var i = 0, ii = nodes.length; i < ii; i++) { + jqLiteRemoveData(nodes[i]); + jqLiteOff(nodes[i]); + } + } +}, function(fn, name) { + JQLite[name] = fn; +}); + forEach({ data: jqLiteData, inheritedData: jqLiteInheritedData, scope: function(element) { // Can't use jqLiteData here directly so we stay compatible with jQuery! - return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); + return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']); }, isolateScope: function(element) { // Can't use jqLiteData here directly so we stay compatible with jQuery! - return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate'); + return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate'); }, controller: jqLiteController, @@ -2578,61 +3690,50 @@ forEach({ return jqLiteInheritedData(element, '$injector'); }, - removeAttr: function(element,name) { + removeAttr: function(element, name) { element.removeAttribute(name); }, hasClass: jqLiteHasClass, css: function(element, name, value) { - name = camelCase(name); + name = cssKebabToCamel(name); if (isDefined(value)) { element.style[name] = value; } else { - var val; + return element.style[name]; + } + }, - if (msie <= 8) { - // this is some IE specific weirdness that jQuery 1.6.4 does not sure why - val = element.currentStyle && element.currentStyle[name]; - if (val === '') val = 'auto'; - } + attr: function(element, name, value) { + var ret; + var nodeType = element.nodeType; + if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT || + !element.getAttribute) { + return; + } + + var lowercasedName = lowercase(name); + var isBooleanAttr = BOOLEAN_ATTR[lowercasedName]; - val = val || element.style[name]; + if (isDefined(value)) { + // setter - if (msie <= 8) { - // jquery weirdness :-/ - val = (val === '') ? undefined : val; + if (value === null || (value === false && isBooleanAttr)) { + element.removeAttribute(name); + } else { + element.setAttribute(name, isBooleanAttr ? lowercasedName : value); } + } else { + // getter - return val; - } - }, + ret = element.getAttribute(name); - attr: function(element, name, value){ - var lowercasedName = lowercase(name); - if (BOOLEAN_ATTR[lowercasedName]) { - if (isDefined(value)) { - if (!!value) { - element[name] = true; - element.setAttribute(name, lowercasedName); - } else { - element[name] = false; - element.removeAttribute(lowercasedName); - } - } else { - return (element[name] || - (element.attributes.getNamedItem(name)|| noop).specified) - ? lowercasedName - : undefined; - } - } else if (isDefined(value)) { - element.setAttribute(name, value); - } else if (element.getAttribute) { - // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code - // some elements (e.g. Document) don't have get attribute, so return undefined - var ret = element.getAttribute(name, 2); - // normalize non-existing attributes to undefined (as jQuery) + if (isBooleanAttr && ret !== null) { + ret = lowercasedName; + } + // Normalize non-existing attributes to undefined (as jQuery). return ret === null ? undefined : ret; } }, @@ -2646,36 +3747,28 @@ forEach({ }, text: (function() { - var NODE_TYPE_TEXT_PROPERTY = []; - if (msie < 9) { - NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/ - NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/ - } else { - NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/ - NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/ - } getText.$dv = ''; return getText; function getText(element, value) { - var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType]; if (isUndefined(value)) { - return textProp ? element[textProp] : ''; + var nodeType = element.nodeType; + return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : ''; } - element[textProp] = value; + element.textContent = value; } })(), val: function(element, value) { if (isUndefined(value)) { - if (nodeName_(element) === 'SELECT' && element.multiple) { + if (element.multiple && nodeName_(element) === 'select') { var result = []; - forEach(element.options, function (option) { + forEach(element.options, function(option) { if (option.selected) { result.push(option.value || option.text); } }); - return result.length === 0 ? null : result; + return result; } return element.value; } @@ -2686,29 +3779,28 @@ forEach({ if (isUndefined(value)) { return element.innerHTML; } - for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) { - jqLiteDealoc(childNodes[i]); - } + jqLiteDealoc(element, true); element.innerHTML = value; }, empty: jqLiteEmpty -}, function(fn, name){ +}, function(fn, name) { /** * Properties: writes return selection, reads return first value */ JQLite.prototype[name] = function(arg1, arg2) { var i, key; + var nodeCount = this.length; // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it // in a way that survives minification. // jqLiteEmpty takes no arguments but is a setter. if (fn !== jqLiteEmpty && - (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) { + (isUndefined((fn.length === 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) { if (isObject(arg1)) { // we are a write, but the object properties are the key/values - for (i = 0; i < this.length; i++) { + for (i = 0; i < nodeCount; i++) { if (fn === jqLiteData) { // data() takes the whole object in jQuery fn(this[i], arg1); @@ -2722,9 +3814,10 @@ forEach({ return this; } else { // we are a read, so read the first child. + // TODO: do we still need this? var value = fn.$dv; // Only if we have $dv do we iterate over all, otherwise it is just the first element. - var jj = (value === undefined) ? Math.min(this.length, 1) : this.length; + var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount; for (var j = 0; j < jj; j++) { var nodeValue = fn(this[j], arg1, arg2); value = value ? value + nodeValue : nodeValue; @@ -2733,7 +3826,7 @@ forEach({ } } else { // we are a write, so apply to all children - for (i = 0; i < this.length; i++) { + for (i = 0; i < nodeCount; i++) { fn(this[i], arg1, arg2); } // return self for chaining @@ -2743,61 +3836,73 @@ forEach({ }); function createEventHandler(element, events) { - var eventHandler = function (event, type) { - if (!event.preventDefault) { - event.preventDefault = function() { - event.returnValue = false; //ie - }; - } + var eventHandler = function(event, type) { + // jQuery specific api + event.isDefaultPrevented = function() { + return event.defaultPrevented; + }; - if (!event.stopPropagation) { - event.stopPropagation = function() { - event.cancelBubble = true; //ie - }; - } + var eventFns = events[type || event.type]; + var eventFnsLength = eventFns ? eventFns.length : 0; - if (!event.target) { - event.target = event.srcElement || document; - } + if (!eventFnsLength) return; - if (isUndefined(event.defaultPrevented)) { - var prevent = event.preventDefault; - event.preventDefault = function() { - event.defaultPrevented = true; - prevent.call(event); + if (isUndefined(event.immediatePropagationStopped)) { + var originalStopImmediatePropagation = event.stopImmediatePropagation; + event.stopImmediatePropagation = function() { + event.immediatePropagationStopped = true; + + if (event.stopPropagation) { + event.stopPropagation(); + } + + if (originalStopImmediatePropagation) { + originalStopImmediatePropagation.call(event); + } }; - event.defaultPrevented = false; } - event.isDefaultPrevented = function() { - return event.defaultPrevented || event.returnValue === false; + event.isImmediatePropagationStopped = function() { + return event.immediatePropagationStopped === true; }; - // Copy event handlers in case event handlers array is modified during execution. - var eventHandlersCopy = shallowCopy(events[type || event.type] || []); + // Some events have special handlers that wrap the real handler + var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper; - forEach(eventHandlersCopy, function(fn) { - fn.call(element, event); - }); + // Copy event handlers in case event handlers array is modified during execution. + if ((eventFnsLength > 1)) { + eventFns = shallowCopy(eventFns); + } - // Remove monkey-patched methods (IE), - // as they would cause memory leaks in IE8. - if (msie <= 8) { - // IE7/8 does not allow to delete property on native object - event.preventDefault = null; - event.stopPropagation = null; - event.isDefaultPrevented = null; - } else { - // It shouldn't affect normal browsers (native methods are defined on prototype). - delete event.preventDefault; - delete event.stopPropagation; - delete event.isDefaultPrevented; + for (var i = 0; i < eventFnsLength; i++) { + if (!event.isImmediatePropagationStopped()) { + handlerWrapper(element, event, eventFns[i]); + } } }; + + // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all + // events on `element` eventHandler.elem = element; return eventHandler; } +function defaultHandlerWrapper(element, event, handler) { + handler.call(element, event); +} + +function specialMouseHandlerWrapper(target, event, handler) { + // Refer to jQuery's implementation of mouseenter & mouseleave + // Read about mouseenter and mouseleave: + // http://www.quirksmode.org/js/events_mouse.html#link8 + var related = event.relatedTarget; + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if (!related || (related !== target && !jqLiteContains.call(target, related))) { + handler.call(target, event); + } +} + ////////////////////////////////////////// // Functions iterating traversal. // These functions chain results into a single @@ -2806,68 +3911,49 @@ function createEventHandler(element, events) { forEach({ removeData: jqLiteRemoveData, - dealoc: jqLiteDealoc, - - on: function onFn(element, type, fn, unsupported){ + on: function jqLiteOn(element, type, fn, unsupported) { if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters'); - var events = jqLiteExpandoStore(element, 'events'), - handle = jqLiteExpandoStore(element, 'handle'); + // Do not add event handlers to non-elements because they will not be cleaned up. + if (!jqLiteAcceptsData(element)) { + return; + } - if (!events) jqLiteExpandoStore(element, 'events', events = {}); - if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events)); + var expandoStore = jqLiteExpandoStore(element, true); + var events = expandoStore.events; + var handle = expandoStore.handle; - forEach(type.split(' '), function(type){ - var eventFns = events[type]; - - if (!eventFns) { - if (type == 'mouseenter' || type == 'mouseleave') { - var contains = document.body.contains || document.body.compareDocumentPosition ? - function( a, b ) { - // jshint bitwise: false - var adown = a.nodeType === 9 ? a.documentElement : a, - bup = b && b.parentNode; - return a === bup || !!( bup && bup.nodeType === 1 && ( - adown.contains ? - adown.contains( bup ) : - a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 - )); - } : - function( a, b ) { - if ( b ) { - while ( (b = b.parentNode) ) { - if ( b === a ) { - return true; - } - } - } - return false; - }; - - events[type] = []; + if (!handle) { + handle = expandoStore.handle = createEventHandler(element, events); + } - // Refer to jQuery's implementation of mouseenter & mouseleave - // Read about mouseenter and mouseleave: - // http://www.quirksmode.org/js/events_mouse.html#link8 - var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"}; + // http://jsperf.com/string-indexof-vs-split + var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type]; + var i = types.length; - onFn(element, eventmap[type], function(event) { - var target = this, related = event.relatedTarget; - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !contains(target, related)) ){ - handle(event, type); - } - }); + var addHandler = function(type, specialHandlerWrapper, noEventListener) { + var eventFns = events[type]; - } else { - addEventListenerFn(element, type, handle); - events[type] = []; + if (!eventFns) { + eventFns = events[type] = []; + eventFns.specialHandlerWrapper = specialHandlerWrapper; + if (type !== '$destroy' && !noEventListener) { + element.addEventListener(type, handle); } - eventFns = events[type]; } + eventFns.push(fn); - }); + }; + + while (i--) { + type = types[i]; + if (MOUSE_EVENT_MAP[type]) { + addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper); + addHandler(type, undefined, true); + } else { + addHandler(type); + } + } }, off: jqLiteOff, @@ -2888,7 +3974,7 @@ forEach({ replaceWith: function(element, replaceNode) { var index, parent = element.parentNode; jqLiteDealoc(element); - forEach(new JQLite(replaceNode), function(node){ + forEach(new JQLite(replaceNode), function(node) { if (index) { parent.insertBefore(node, index.nextSibling); } else { @@ -2900,9 +3986,10 @@ forEach({ children: function(element) { var children = []; - forEach(element.childNodes, function(element){ - if (element.nodeType === 1) + forEach(element.childNodes, function(element) { + if (element.nodeType === NODE_TYPE_ELEMENT) { children.push(element); + } }); return children; }, @@ -2912,43 +3999,48 @@ forEach({ }, append: function(element, node) { - forEach(new JQLite(node), function(child){ - if (element.nodeType === 1 || element.nodeType === 11) { - element.appendChild(child); - } - }); + var nodeType = element.nodeType; + if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return; + + node = new JQLite(node); + + for (var i = 0, ii = node.length; i < ii; i++) { + var child = node[i]; + element.appendChild(child); + } }, prepend: function(element, node) { - if (element.nodeType === 1) { + if (element.nodeType === NODE_TYPE_ELEMENT) { var index = element.firstChild; - forEach(new JQLite(node), function(child){ + forEach(new JQLite(node), function(child) { element.insertBefore(child, index); }); } }, wrap: function(element, wrapNode) { - wrapNode = jqLite(wrapNode)[0]; - var parent = element.parentNode; - if (parent) { - parent.replaceChild(wrapNode, element); - } - wrapNode.appendChild(element); + jqLiteWrapNode(element, jqLite(wrapNode).eq(0).clone()[0]); }, - remove: function(element) { - jqLiteDealoc(element); - var parent = element.parentNode; - if (parent) parent.removeChild(element); + remove: jqLiteRemove, + + detach: function(element) { + jqLiteRemove(element, true); }, after: function(element, newElement) { var index = element, parent = element.parentNode; - forEach(new JQLite(newElement), function(node){ - parent.insertBefore(node, index.nextSibling); - index = node; - }); + + if (parent) { + newElement = new JQLite(newElement); + + for (var i = 0, ii = newElement.length; i < ii; i++) { + var node = newElement[i]; + parent.insertBefore(node, index.nextSibling); + index = node; + } + } }, addClass: jqLiteAddClass, @@ -2956,7 +4048,7 @@ forEach({ toggleClass: function(element, selector, condition) { if (selector) { - forEach(selector.split(' '), function(className){ + forEach(selector.split(' '), function(className) { var classCondition = condition; if (isUndefined(classCondition)) { classCondition = !jqLiteHasClass(element, className); @@ -2968,20 +4060,11 @@ forEach({ parent: function(element) { var parent = element.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; + return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null; }, next: function(element) { - if (element.nextElementSibling) { - return element.nextElementSibling; - } - - // IE8 doesn't have nextElementSibling - var elm = element.nextSibling; - while (elm != null && elm.nodeType !== 1) { - elm = elm.nextSibling; - } - return elm; + return element.nextElementSibling; }, find: function(element, selector) { @@ -2994,27 +4077,50 @@ forEach({ clone: jqLiteClone, - triggerHandler: function(element, eventName, eventData) { - var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName]; + triggerHandler: function(element, event, extraParameters) { + + var dummyEvent, eventFnsCopy, handlerArgs; + var eventName = event.type || event; + var expandoStore = jqLiteExpandoStore(element); + var events = expandoStore && expandoStore.events; + var eventFns = events && events[eventName]; + + if (eventFns) { + // Create a dummy event to pass to the handlers + dummyEvent = { + preventDefault: function() { this.defaultPrevented = true; }, + isDefaultPrevented: function() { return this.defaultPrevented === true; }, + stopImmediatePropagation: function() { this.immediatePropagationStopped = true; }, + isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; }, + stopPropagation: noop, + type: eventName, + target: element + }; - eventData = eventData || []; + // If a custom event was provided then extend our dummy event with it + if (event.type) { + dummyEvent = extend(dummyEvent, event); + } - var event = [{ - preventDefault: noop, - stopPropagation: noop - }]; + // Copy event handlers in case event handlers array is modified during execution. + eventFnsCopy = shallowCopy(eventFns); + handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent]; - forEach(eventFns, function(fn) { - fn.apply(element, event.concat(eventData)); - }); + forEach(eventFnsCopy, function(fn) { + if (!dummyEvent.isImmediatePropagationStopped()) { + fn.apply(element, handlerArgs); + } + }); + } } -}, function(fn, name){ +}, function(fn, name) { /** * chaining functions */ JQLite.prototype[name] = function(arg1, arg2, arg3) { var value; - for(var i=0; i < this.length; i++) { + + for (var i = 0, ii = this.length; i < ii; i++) { if (isUndefined(value)) { value = fn(this[i], arg1, arg2, arg3); if (isDefined(value)) { @@ -3027,12 +4133,34 @@ forEach({ } return isDefined(value) ? value : this; }; - - // bind legacy bind/unbind to on/off - JQLite.prototype.bind = JQLite.prototype.on; - JQLite.prototype.unbind = JQLite.prototype.off; }); +// bind legacy bind/unbind to on/off +JQLite.prototype.bind = JQLite.prototype.on; +JQLite.prototype.unbind = JQLite.prototype.off; + + +// Provider for private $$jqLite service +/** @this */ +function $$jqLiteProvider() { + this.$get = function $$jqLite() { + return extend(JQLite, { + hasClass: function(node, classes) { + if (node.attr) node = node[0]; + return jqLiteHasClass(node, classes); + }, + addClass: function(node, classes) { + if (node.attr) node = node[0]; + return jqLiteAddClass(node, classes); + }, + removeClass: function(node, classes) { + if (node.attr) node = node[0]; + return jqLiteRemoveClass(node, classes); + } + }); + }; +} + /** * Computes a hash of an 'obj'. * Hash of a: @@ -3045,73 +4173,112 @@ forEach({ * @returns {string} hash string such that the same input will have the same hash string. * The resulting string key is in 'type:hashKey' format. */ -function hashKey(obj) { - var objType = typeof obj, - key; +function hashKey(obj, nextUidFn) { + var key = obj && obj.$$hashKey; - if (objType == 'object' && obj !== null) { - if (typeof (key = obj.$$hashKey) == 'function') { - // must invoke on object to keep the right this + if (key) { + if (typeof key === 'function') { key = obj.$$hashKey(); - } else if (key === undefined) { - key = obj.$$hashKey = nextUid(); } + return key; + } + + var objType = typeof obj; + if (objType === 'function' || (objType === 'object' && obj !== null)) { + key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)(); } else { - key = obj; + key = objType + ':' + obj; } - return objType + ':' + key; + return key; } -/** - * HashMap which can use objects as keys - */ -function HashMap(array){ - forEach(array, this.put, this); +// A minimal ES2015 Map implementation. +// Should be bug/feature equivalent to the native implementations of supported browsers +// (for the features required in Angular). +// See https://kangax.github.io/compat-table/es6/#test-Map +var nanKey = Object.create(null); +function NgMapShim() { + this._keys = []; + this._values = []; + this._lastKey = NaN; + this._lastIndex = -1; } -HashMap.prototype = { - /** - * Store key value pair - * @param key key to store can be any type - * @param value value to store can be any type - */ - put: function(key, value) { - this[hashKey(key)] = value; +NgMapShim.prototype = { + _idx: function(key) { + if (key !== this._lastKey) { + this._lastKey = key; + this._lastIndex = this._keys.indexOf(key); + } + return this._lastIndex; + }, + _transformKey: function(key) { + return isNumberNaN(key) ? nanKey : key; }, - - /** - * @param key - * @returns {Object} the value for the key - */ get: function(key) { - return this[hashKey(key)]; + key = this._transformKey(key); + var idx = this._idx(key); + if (idx !== -1) { + return this._values[idx]; + } + }, + has: function(key) { + key = this._transformKey(key); + var idx = this._idx(key); + return idx !== -1; }, + set: function(key, value) { + key = this._transformKey(key); + var idx = this._idx(key); + if (idx === -1) { + idx = this._lastIndex = this._keys.length; + } + this._keys[idx] = key; + this._values[idx] = value; - /** - * Remove the key/value pair - * @param key - */ - remove: function(key) { - var value = this[key = hashKey(key)]; - delete this[key]; - return value; + // Support: IE11 + // Do not `return this` to simulate the partial IE11 implementation + }, + delete: function(key) { + key = this._transformKey(key); + var idx = this._idx(key); + if (idx === -1) { + return false; + } + this._keys.splice(idx, 1); + this._values.splice(idx, 1); + this._lastKey = NaN; + this._lastIndex = -1; + return true; } }; +// For now, always use `NgMapShim`, even if `window.Map` is available. Some native implementations +// are still buggy (often in subtle ways) and can cause hard-to-debug failures. When native `Map` +// implementations get more stable, we can reconsider switching to `window.Map` (when available). +var NgMap = NgMapShim; + +var $$MapProvider = [/** @this */function() { + this.$get = [function() { + return NgMap; + }]; +}]; + /** * @ngdoc function * @module ng * @name angular.injector - * @function + * @kind function * * @description - * Creates an injector function that can be used for retrieving services as well as for + * Creates an injector object that can be used for retrieving services as well as for * dependency injection (see {@link guide/di dependency injection}). * - * @param {Array.} modules A list of module functions or their aliases. See - * {@link angular.module}. The `ng` module must be explicitly added. - * @returns {function()} Injector function. See {@link auto.$injector $injector}. + * {@link angular.module}. The `ng` module must be explicitly added. + * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which + * disallows argument name annotation inference. + * @returns {injector} Injector object. See {@link auto.$injector $injector}. * * @example * Typical usage @@ -3121,15 +4288,15 @@ HashMap.prototype = { * * // use the injector to kick off your application * // use the type inference to auto inject arguments, or use implicit injection - * $injector.invoke(function($rootScope, $compile, $document){ + * $injector.invoke(function($rootScope, $compile, $document) { * $compile($document)($rootScope); * $rootScope.$digest(); * }); * ``` * - * Sometimes you want to get access to the injector of a currently running Angular app - * from outside Angular. Perhaps, you want to inject and compile some markup after the - * application has been bootstrapped. You can do this using extra `injector()` added + * Sometimes you want to get access to the injector of a currently running AngularJS app + * from outside AngularJS. Perhaps, you want to inject and compile some markup after the + * application has been bootstrapped. You can do this using the extra `injector()` added * to JQuery/jqLite elements. See {@link angular.element}. * * *This is fairly rare but could be the case if a third party library is injecting the @@ -3154,30 +4321,58 @@ HashMap.prototype = { /** * @ngdoc module * @name auto + * @installation * @description * * Implicit module which gets automatically added to each {@link auto.$injector $injector}. */ -var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; +var ARROW_ARG = /^([^(]+?)=>/; +var FN_ARGS = /^[^(]*\(\s*([^)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; var $injectorMinErr = minErr('$injector'); -function annotate(fn) { + +function stringifyFn(fn) { + return Function.prototype.toString.call(fn); +} + +function extractArgs(fn) { + var fnText = stringifyFn(fn).replace(STRIP_COMMENTS, ''), + args = fnText.match(ARROW_ARG) || fnText.match(FN_ARGS); + return args; +} + +function anonFn(fn) { + // For anonymous functions, showing at the very least the function signature can help in + // debugging. + var args = extractArgs(fn); + if (args) { + return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')'; + } + return 'fn'; +} + +function annotate(fn, strictDi, name) { var $inject, - fnText, argDecl, last; - if (typeof fn == 'function') { + if (typeof fn === 'function') { if (!($inject = fn.$inject)) { $inject = []; if (fn.length) { - fnText = fn.toString().replace(STRIP_COMMENTS, ''); - argDecl = fnText.match(FN_ARGS); - forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){ - arg.replace(FN_ARG, function(all, underscore, name){ + if (strictDi) { + if (!isString(name) || !name) { + name = fn.name || anonFn(fn); + } + throw $injectorMinErr('strictdi', + '{0} is not using explicit annotation and cannot be invoked in strict mode', name); + } + argDecl = extractArgs(fn); + forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) { + arg.replace(FN_ARG, function(all, underscore, name) { $inject.push(name); }); }); @@ -3199,7 +4394,6 @@ function annotate(fn) { /** * @ngdoc service * @name $injector - * @function * * @description * @@ -3212,12 +4406,12 @@ function annotate(fn) { * ```js * var $injector = angular.injector(); * expect($injector.get('$injector')).toBe($injector); - * expect($injector.invoke(function($injector){ + * expect($injector.invoke(function($injector) { * return $injector; - * }).toBe($injector); + * })).toBe($injector); * ``` * - * # Injection Function Annotation + * ## Injection Function Annotation * * JavaScript does not have annotations, and annotations are needed for dependency injection. The * following are all valid ways of annotating function with injection arguments and are equivalent. @@ -3235,19 +4429,43 @@ function annotate(fn) { * $injector.invoke(['serviceA', function(serviceA){}]); * ``` * - * ## Inference + * ### Inference * * In JavaScript calling `toString()` on a function returns the function definition. The definition - * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with - * minification, and obfuscation tools since these tools change the argument names. + * can then be parsed and the function arguments can be extracted. This method of discovering + * annotations is disallowed when the injector is in strict mode. + * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the + * argument names. * - * ## `$inject` Annotation - * By adding a `$inject` property onto a function the injection parameters can be specified. + * ### `$inject` Annotation + * By adding an `$inject` property onto a function the injection parameters can be specified. * - * ## Inline + * ### Inline * As an array of injection names, where the last item in the array is the function to call. */ +/** + * @ngdoc property + * @name $injector#modules + * @type {Object} + * @description + * A hash containing all the modules that have been loaded into the + * $injector. + * + * You can use this property to find out information about a module via the + * {@link angular.Module#info `myModule.info(...)`} method. + * + * For example: + * + * ``` + * var info = $injector.modules['ngAnimate'].info(); + * ``` + * + * **Do not use this property to attempt to modify the modules after the application + * has been bootstrapped.** + */ + + /** * @ngdoc method * @name $injector#get @@ -3256,6 +4474,7 @@ function annotate(fn) { * Return an instance of the service. * * @param {string} name The name of the instance to retrieve. + * @param {string=} caller An optional string to provide the origin of the function call for error messages. * @return {*} The instance. */ @@ -3266,8 +4485,8 @@ function annotate(fn) { * @description * Invoke the method and supply the method arguments from the `$injector`. * - * @param {!Function} fn The function to invoke. Function parameters are injected according to the - * {@link guide/di $inject Annotation} rules. + * @param {Function|Array.} fn The injectable function to invoke. Function parameters are + * injected according to the {@link guide/di $inject Annotation} rules. * @param {Object=} self The `this` for the invoked method. * @param {Object=} locals Optional object. If preset then any argument names are read from this * object first, before the `$injector` is consulted. @@ -3279,18 +4498,18 @@ function annotate(fn) { * @name $injector#has * * @description - * Allows the user to query if the particular service exist. + * Allows the user to query if the particular service exists. * - * @param {string} Name of the service to query. - * @returns {boolean} returns true if injector has given service. + * @param {string} name Name of the service to query. + * @returns {boolean} `true` if injector has given service. */ /** * @ngdoc method * @name $injector#instantiate * @description - * Create a new instance of JS type. The method takes a constructor function invokes the new - * operator and supplies all of the arguments to the constructor function as specified by the + * Create a new instance of JS type. The method takes a constructor function, invokes the new + * operator, and supplies all of the arguments to the constructor function as specified by the * constructor annotation. * * @param {Function} Type Annotated constructor function. @@ -3309,7 +4528,7 @@ function annotate(fn) { * function is invoked. There are three ways in which the function can be annotated with the needed * dependencies. * - * # Argument names + * #### Argument names * * The simplest form is to extract the dependencies from the arguments of the function. This is done * by converting the function into a string using `toString()` method and extracting the argument @@ -3324,10 +4543,12 @@ function annotate(fn) { * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * + * You can disallow this method by using strict injection mode. + * * This method does not work with code minification / obfuscation. For this reason the following * annotation strategies are supported. * - * # The `$inject` property + * #### The `$inject` property * * If a function has an `$inject` property and its value is an array of strings, then the strings * represent names of services to be injected into the function. @@ -3343,7 +4564,7 @@ function annotate(fn) { * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']); * ``` * - * # The array notation + * #### The array notation * * It is often desirable to inline Injected functions and that's when setting the `$inject` property * is very inconvenient. In these situations using the array notation to specify the dependencies in @@ -3376,14 +4597,53 @@ function annotate(fn) { * @param {Function|Array.} fn Function for which dependent service names need to * be retrieved as described above. * + * @param {boolean=} [strictDi=false] Disallow argument name annotation inference. + * * @returns {Array.} The names of the services which the function requires. */ - - +/** + * @ngdoc method + * @name $injector#loadNewModules + * + * @description + * + * **This is a dangerous API, which you use at your own risk!** + * + * Add the specified modules to the current injector. + * + * This method will add each of the injectables to the injector and execute all of the config and run + * blocks for each module passed to the method. + * + * If a module has already been loaded into the injector then it will not be loaded again. + * + * * The application developer is responsible for loading the code containing the modules; and for + * ensuring that lazy scripts are not downloaded and executed more often that desired. + * * Previously compiled HTML will not be affected by newly loaded directives, filters and components. + * * Modules cannot be unloaded. + * + * You can use {@link $injector#modules `$injector.modules`} to check whether a module has been loaded + * into the injector, which may indicate whether the script has been executed already. + * + * @example + * Here is an example of loading a bundle of modules, with a utility method called `getScript`: + * + * ```javascript + * app.factory('loadModule', function($injector) { + * return function loadModule(moduleName, bundleUrl) { + * return getScript(bundleUrl).then(function() { $injector.loadNewModules([moduleName]); }); + * }; + * }) + * ``` + * + * @param {Array=} mods an array of modules to load into the application. + * Each item in the array should be the name of a predefined module or a (DI annotated) + * function that will be invoked by the injector as a `config` block. + * See: {@link angular.module modules} + */ /** - * @ngdoc object + * @ngdoc service * @name $provide * * @description @@ -3392,7 +4652,7 @@ function annotate(fn) { * with the {@link auto.$injector $injector}. Many of these functions are also exposed on * {@link angular.Module}. * - * An Angular **service** is a singleton object created by a **service factory**. These **service + * An AngularJS **service** is a singleton object created by a **service factory**. These **service * factories** are functions which, in turn, are created by a **service provider**. * The **service providers** are constructor functions. When instantiated they must contain a * property called `$get`, which holds the **service factory** function. @@ -3406,18 +4666,20 @@ function annotate(fn) { * these cases the {@link auto.$provide $provide} service has additional helper methods to register * services without specifying a provider. * - * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the + * * {@link auto.$provide#provider provider(name, provider)} - registers a **service provider** with the * {@link auto.$injector $injector} - * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by + * * {@link auto.$provide#constant constant(name, obj)} - registers a value/object that can be accessed by * providers and services. - * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by + * * {@link auto.$provide#value value(name, obj)} - registers a value/object that can only be accessed by * services, not providers. - * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`, + * * {@link auto.$provide#factory factory(name, fn)} - registers a service **factory function** * that will be wrapped in a **service provider** object, whose `$get` property will contain the * given factory function. - * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class` + * * {@link auto.$provide#service service(name, Fn)} - registers a **constructor function** * that will be wrapped in a **service provider** object, whose `$get` property will instantiate * a new object using the given constructor function. + * * {@link auto.$provide#decorator decorator(name, decorFn)} - registers a **decorator function** that + * will be able to modify or replace the implementation of another service. * * See the individual methods for more information and examples. */ @@ -3442,6 +4704,9 @@ function annotate(fn) { * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the * console or not. * + * It is possible to inject other providers into the provider function, + * but the injected provider must have been defined before the one that requires it. + * * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key. * @param {(Object|function())} provider If the provider is: @@ -3530,8 +4795,8 @@ function annotate(fn) { * configure your service in a provider. * * @param {string} name The name of the instance. - * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand - * for `$provide.provider(name, {$get: $getFn})`. + * @param {Function|Array.} $getFn The injectable $getFn for the instance creation. + * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`. * @returns {Object} registered provider instance * * @example @@ -3559,14 +4824,27 @@ function annotate(fn) { * * Register a **service constructor**, which will be invoked with `new` to create the service * instance. - * This is short for registering a service where its provider's `$get` property is the service - * constructor function that will be used to instantiate the service instance. + * This is short for registering a service where its provider's `$get` property is a factory + * function that returns an instance instantiated by the injector from the service constructor + * function. + * + * Internally it looks a bit like this: + * + * ``` + * { + * $get: function() { + * return $injector.instantiate(constructor); + * } + * } + * ``` + * * * You should use {@link auto.$provide#service $provide.service(class)} if you define your service * as a type/class. * * @param {string} name The name of the instance. - * @param {Function} constructor A class (constructor function) that will be instantiated. + * @param {Function|Array.} constructor An injectable class (constructor function) + * that will be instantiated. * @returns {Object} registered provider instance * * @example @@ -3599,14 +4877,13 @@ function annotate(fn) { * @description * * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a - * number, an array, an object or a function. This is short for registering a service where its + * number, an array, an object or a function. This is short for registering a service where its * provider's `$get` property is a factory function that takes no arguments and returns the **value - * service**. + * service**. That also means it is not possible to inject other services into a value service. * * Value services are similar to constant services, except that they cannot be injected into a * module configuration function (see {@link angular.Module#config}) but they can be overridden by - * an Angular - * {@link auto.$provide#decorator decorator}. + * an AngularJS {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the instance. * @param {*} value The value. @@ -3631,10 +4908,13 @@ function annotate(fn) { * @name $provide#constant * @description * - * Register a **constant service**, such as a string, a number, an array, an object or a function, - * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be + * Register a **constant service** with the {@link auto.$injector $injector}, such as a string, + * a number, an array, an object or a function. Like the {@link auto.$provide#value value}, it is not + * possible to inject other services into a constant. + * + * But unlike {@link auto.$provide#value value}, a constant can be * injected into a module configuration function (see {@link angular.Module#config}) and it cannot - * be overridden by an Angular {@link auto.$provide#decorator decorator}. + * be overridden by an AngularJS {@link auto.$provide#decorator decorator}. * * @param {string} name The name of the constant. * @param {*} value The constant value. @@ -3659,18 +4939,20 @@ function annotate(fn) { * @name $provide#decorator * @description * - * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator - * intercepts the creation of a service, allowing it to override or modify the behaviour of the - * service. The object returned by the decorator may be the original service, or a new service - * object which replaces or wraps and delegates to the original service. + * Register a **decorator function** with the {@link auto.$injector $injector}. A decorator function + * intercepts the creation of a service, allowing it to override or modify the behavior of the + * service. The return value of the decorator function may be the original service, or a new service + * that replaces (or wraps and delegates to) the original service. + * + * You can find out more about using decorators in the {@link guide/decorators} guide. * * @param {string} name The name of the service to decorate. - * @param {function()} decorator This function will be invoked when the service needs to be - * instantiated and should return the decorated service instance. The function is called using + * @param {Function|Array.} decorator This function will be invoked when the service needs to be + * provided and should return the decorated service instance. The function is called using * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable. * Local injection arguments: * - * * `$delegate` - The original service instance, which can be monkey patched, configured, + * * `$delegate` - The original service instance, which can be replaced, monkey patched, configured, * decorated or delegated to. * * @example @@ -3685,11 +4967,12 @@ function annotate(fn) { */ -function createInjector(modulesToLoad) { +function createInjector(modulesToLoad, strictDi) { + strictDi = (strictDi === true); var INSTANTIATING = {}, providerSuffix = 'Provider', path = [], - loadedModules = new HashMap(), + loadedModules = new NgMap(), providerCache = { $provide: { provider: supportObject(provider), @@ -3701,18 +4984,32 @@ function createInjector(modulesToLoad) { } }, providerInjector = (providerCache.$injector = - createInternalInjector(providerCache, function() { - throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- ')); + createInternalInjector(providerCache, function(serviceName, caller) { + if (angular.isString(caller)) { + path.push(caller); + } + throw $injectorMinErr('unpr', 'Unknown provider: {0}', path.join(' <- ')); })), instanceCache = {}, - instanceInjector = (instanceCache.$injector = - createInternalInjector(instanceCache, function(servicename) { - var provider = providerInjector.get(servicename + providerSuffix); - return instanceInjector.invoke(provider.$get, provider); - })); + protoInstanceInjector = + createInternalInjector(instanceCache, function(serviceName, caller) { + var provider = providerInjector.get(serviceName + providerSuffix, caller); + return instanceInjector.invoke( + provider.$get, provider, undefined, serviceName); + }), + instanceInjector = protoInstanceInjector; + providerCache['$injector' + providerSuffix] = { $get: valueFn(protoInstanceInjector) }; + instanceInjector.modules = providerInjector.modules = createMap(); + var runBlocks = loadModules(modulesToLoad); + instanceInjector = protoInstanceInjector.get('$injector'); + instanceInjector.strictDi = strictDi; + forEach(runBlocks, function(fn) { if (fn) instanceInjector.invoke(fn); }); + + instanceInjector.loadNewModules = function(mods) { + forEach(loadModules(mods), function(fn) { if (fn) instanceInjector.invoke(fn); }); + }; - forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); }); return instanceInjector; @@ -3736,12 +5033,26 @@ function createInjector(modulesToLoad) { provider_ = providerInjector.instantiate(provider_); } if (!provider_.$get) { - throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name); + throw $injectorMinErr('pget', 'Provider \'{0}\' must define $get factory method.', name); } - return providerCache[name + providerSuffix] = provider_; + return (providerCache[name + providerSuffix] = provider_); } - function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); } + function enforceReturnValue(name, factory) { + return /** @this */ function enforcedReturnValue() { + var result = instanceInjector.invoke(factory, this); + if (isUndefined(result)) { + throw $injectorMinErr('undef', 'Provider \'{0}\' must return a value from $get factory method.', name); + } + return result; + }; + } + + function factory(name, factoryFn, enforce) { + return provider(name, { + $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn + }); + } function service(name, constructor) { return factory(name, ['$injector', function($injector) { @@ -3749,7 +5060,7 @@ function createInjector(modulesToLoad) { }]); } - function value(name, val) { return factory(name, valueFn(val)); } + function value(name, val) { return factory(name, valueFn(val), false); } function constant(name, value) { assertNotHasOwnProperty(name, 'constant'); @@ -3770,23 +5081,30 @@ function createInjector(modulesToLoad) { //////////////////////////////////// // Module Loading //////////////////////////////////// - function loadModules(modulesToLoad){ - var runBlocks = [], moduleFn, invokeQueue, i, ii; + function loadModules(modulesToLoad) { + assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array'); + var runBlocks = [], moduleFn; forEach(modulesToLoad, function(module) { if (loadedModules.get(module)) return; - loadedModules.put(module, true); + loadedModules.set(module, true); + + function runInvokeQueue(queue) { + var i, ii; + for (i = 0, ii = queue.length; i < ii; i++) { + var invokeArgs = queue[i], + provider = providerInjector.get(invokeArgs[0]); + + provider[invokeArgs[1]].apply(provider, invokeArgs[2]); + } + } try { if (isString(module)) { moduleFn = angularModule(module); + instanceInjector.modules[module] = moduleFn; runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks); - - for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) { - var invokeArgs = invokeQueue[i], - provider = providerInjector.get(invokeArgs[0]); - - provider[invokeArgs[1]].apply(provider, invokeArgs[2]); - } + runInvokeQueue(moduleFn._invokeQueue); + runInvokeQueue(moduleFn._configBlocks); } else if (isFunction(module)) { runBlocks.push(providerInjector.invoke(module)); } else if (isArray(module)) { @@ -3798,15 +5116,15 @@ function createInjector(modulesToLoad) { if (isArray(module)) { module = module[module.length - 1]; } - if (e.message && e.stack && e.stack.indexOf(e.message) == -1) { + if (e.message && e.stack && e.stack.indexOf(e.message) === -1) { // Safari & FF's stack traces don't contain error.message content // unlike those of Chrome and IE // So if stack doesn't contain message, we create a new string that contains both. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here. - /* jshint -W022 */ + // eslint-disable-next-line no-ex-assign e = e.message + '\n' + e.stack; } - throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}", + throw $injectorMinErr('modulerr', 'Failed to instantiate module {0} due to:\n{1}', module, e.stack || e.message || e); } }); @@ -3819,17 +5137,19 @@ function createInjector(modulesToLoad) { function createInternalInjector(cache, factory) { - function getService(serviceName) { + function getService(serviceName, caller) { if (cache.hasOwnProperty(serviceName)) { if (cache[serviceName] === INSTANTIATING) { - throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- ')); + throw $injectorMinErr('cdep', 'Circular dependency found: {0}', + serviceName + ' <- ' + path.join(' <- ')); } return cache[serviceName]; } else { try { path.unshift(serviceName); cache[serviceName] = INSTANTIATING; - return cache[serviceName] = factory(serviceName); + cache[serviceName] = factory(serviceName, caller); + return cache[serviceName]; } catch (err) { if (cache[serviceName] === INSTANTIATING) { delete cache[serviceName]; @@ -3841,52 +5161,74 @@ function createInjector(modulesToLoad) { } } - function invoke(fn, self, locals){ + + function injectionArgs(fn, locals, serviceName) { var args = [], - $inject = annotate(fn), - length, i, - key; + $inject = createInjector.$$annotate(fn, strictDi, serviceName); - for(i = 0, length = $inject.length; i < length; i++) { - key = $inject[i]; + for (var i = 0, length = $inject.length; i < length; i++) { + var key = $inject[i]; if (typeof key !== 'string') { throw $injectorMinErr('itkn', 'Incorrect injection token! Expected service name as string, got {0}', key); } - args.push( - locals && locals.hasOwnProperty(key) - ? locals[key] - : getService(key) - ); + args.push(locals && locals.hasOwnProperty(key) ? locals[key] : + getService(key, serviceName)); + } + return args; + } + + function isClass(func) { + // Support: IE 9-11 only + // IE 9-11 do not support classes and IE9 leaks with the code below. + if (msie || typeof func !== 'function') { + return false; + } + var result = func.$$ngIsClass; + if (!isBoolean(result)) { + result = func.$$ngIsClass = /^class\b/.test(stringifyFn(func)); + } + return result; + } + + function invoke(fn, self, locals, serviceName) { + if (typeof locals === 'string') { + serviceName = locals; + locals = null; } - if (!fn.$inject) { - // this means that we must be an array. - fn = fn[length]; + + var args = injectionArgs(fn, locals, serviceName); + if (isArray(fn)) { + fn = fn[fn.length - 1]; } - // http://jsperf.com/angularjs-invoke-apply-vs-switch - // #5388 - return fn.apply(self, args); + if (!isClass(fn)) { + // http://jsperf.com/angularjs-invoke-apply-vs-switch + // #5388 + return fn.apply(self, args); + } else { + args.unshift(null); + return new (Function.prototype.bind.apply(fn, args))(); + } } - function instantiate(Type, locals) { - var Constructor = function() {}, - instance, returnedValue; + function instantiate(Type, locals, serviceName) { // Check if Type is annotated and use just the given function at n-1 as parameter // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]); - Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype; - instance = new Constructor(); - returnedValue = invoke(Type, instance, locals); - - return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance; + var ctor = (isArray(Type) ? Type[Type.length - 1] : Type); + var args = injectionArgs(Type, locals, serviceName); + // Empty object at position 0 is ignored for invocation with `new`, but required. + args.unshift(null); + return new (Function.prototype.bind.apply(ctor, args))(); } + return { invoke: invoke, instantiate: instantiate, get: getService, - annotate: annotate, + annotate: createInjector.$$annotate, has: function(name) { return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name); } @@ -3894,100 +5236,274 @@ function createInjector(modulesToLoad) { } } +createInjector.$$annotate = annotate; + /** - * @ngdoc service - * @name $anchorScroll - * @kind function - * @requires $window - * @requires $location - * @requires $rootScope + * @ngdoc provider + * @name $anchorScrollProvider + * @this * * @description - * When called, it checks current value of `$location.hash()` and scroll to related element, - * according to rules specified in - * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document). - * - * It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor. - * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`. - * - * @example - - -
- Go to bottom - You're at the bottom! -
-
- - function ScrollCtrl($scope, $location, $anchorScroll) { - $scope.gotoBottom = function (){ - // set the location.hash to the id of - // the element you wish to scroll to. - $location.hash('bottom'); - - // call $anchorScroll() - $anchorScroll(); - }; - } - - - #scrollArea { - height: 350px; - overflow: auto; - } - - #bottom { - display: block; - margin-top: 2000px; - } - -
+ * Use `$anchorScrollProvider` to disable automatic scrolling whenever + * {@link ng.$location#hash $location.hash()} changes. */ function $AnchorScrollProvider() { var autoScrollingEnabled = true; + /** + * @ngdoc method + * @name $anchorScrollProvider#disableAutoScrolling + * + * @description + * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to + * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.
+ * Use this method to disable automatic scrolling. + * + * If automatic scrolling is disabled, one must explicitly call + * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the + * current hash. + */ this.disableAutoScrolling = function() { autoScrollingEnabled = false; }; + /** + * @ngdoc service + * @name $anchorScroll + * @kind function + * @requires $window + * @requires $location + * @requires $rootScope + * + * @description + * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the + * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified + * in the + * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#an-indicated-part-of-the-document). + * + * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to + * match any anchor whenever it changes. This can be disabled by calling + * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}. + * + * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a + * vertical scroll-offset (either fixed or dynamic). + * + * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of + * {@link ng.$location#hash $location.hash()} will be used. + * + * @property {(number|function|jqLite)} yOffset + * If set, specifies a vertical scroll-offset. This is often useful when there are fixed + * positioned elements at the top of the page, such as navbars, headers etc. + * + * `yOffset` can be specified in various ways: + * - **number**: A fixed number of pixels to be used as offset.

+ * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return + * a number representing the offset (in pixels).

+ * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from + * the top of the page to the element's bottom will be used as offset.
+ * **Note**: The element will be taken into account only as long as its `position` is set to + * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust + * their height and/or positioning according to the viewport's size. + * + *
+ *
+ * In order for `yOffset` to work properly, scrolling should take place on the document's root and + * not some child element. + *
+ * + * @example + + +
+ Go to bottom + You're at the bottom! +
+
+ + angular.module('anchorScrollExample', []) + .controller('ScrollController', ['$scope', '$location', '$anchorScroll', + function($scope, $location, $anchorScroll) { + $scope.gotoBottom = function() { + // set the location.hash to the id of + // the element you wish to scroll to. + $location.hash('bottom'); + + // call $anchorScroll() + $anchorScroll(); + }; + }]); + + + #scrollArea { + height: 280px; + overflow: auto; + } + + #bottom { + display: block; + margin-top: 2000px; + } + +
+ * + *
+ * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value). + * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details. + * + * @example + + + +
+ Anchor {{x}} of 5 +
+
+ + angular.module('anchorScrollOffsetExample', []) + .run(['$anchorScroll', function($anchorScroll) { + $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels + }]) + .controller('headerCtrl', ['$anchorScroll', '$location', '$scope', + function($anchorScroll, $location, $scope) { + $scope.gotoAnchor = function(x) { + var newHash = 'anchor' + x; + if ($location.hash() !== newHash) { + // set the $location.hash to `newHash` and + // $anchorScroll will automatically scroll to it + $location.hash('anchor' + x); + } else { + // call $anchorScroll() explicitly, + // since $location.hash hasn't changed + $anchorScroll(); + } + }; + } + ]); + + + body { + padding-top: 50px; + } + + .anchor { + border: 2px dashed DarkOrchid; + padding: 10px 10px 200px 10px; + } + + .fixed-header { + background-color: rgba(0, 0, 0, 0.2); + height: 50px; + position: fixed; + top: 0; left: 0; right: 0; + } + + .fixed-header > a { + display: inline-block; + margin: 5px 15px; + } + +
+ */ this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) { var document = $window.document; - // helper function to get first anchor from a NodeList - // can't use filter.filter, as it accepts only instances of Array - // and IE can't convert NodeList to an array using [].slice - // TODO(vojta): use filter if we change it to accept lists as well + // Helper function to get first anchor from a NodeList + // (using `Array#some()` instead of `angular#forEach()` since it's more performant + // and working in all supported browsers.) function getFirstAnchor(list) { var result = null; - forEach(list, function(element) { - if (!result && lowercase(element.nodeName) === 'a') result = element; + Array.prototype.some.call(list, function(element) { + if (nodeName_(element) === 'a') { + result = element; + return true; + } }); return result; } - function scroll() { - var hash = $location.hash(), elm; - - // empty hash, scroll to the top of the page - if (!hash) $window.scrollTo(0, 0); + function getYOffset() { - // element with given id - else if ((elm = document.getElementById(hash))) elm.scrollIntoView(); + var offset = scroll.yOffset; - // first anchor with given name :-D - else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView(); + if (isFunction(offset)) { + offset = offset(); + } else if (isElement(offset)) { + var elem = offset[0]; + var style = $window.getComputedStyle(elem); + if (style.position !== 'fixed') { + offset = 0; + } else { + offset = elem.getBoundingClientRect().bottom; + } + } else if (!isNumber(offset)) { + offset = 0; + } - // no element and hash == 'top', scroll to the top of the page - else if (hash === 'top') $window.scrollTo(0, 0); + return offset; + } + + function scrollTo(elem) { + if (elem) { + elem.scrollIntoView(); + + var offset = getYOffset(); + + if (offset) { + // `offset` is the number of pixels we should scroll UP in order to align `elem` properly. + // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the + // top of the viewport. + // + // IF the number of pixels from the top of `elem` to the end of the page's content is less + // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some + // way down the page. + // + // This is often the case for elements near the bottom of the page. + // + // In such cases we do not need to scroll the whole `offset` up, just the difference between + // the top of the element and the offset, which is enough to align the top of `elem` at the + // desired position. + var elemTop = elem.getBoundingClientRect().top; + $window.scrollBy(0, elemTop - offset); + } + } else { + $window.scrollTo(0, 0); + } + } + + function scroll(hash) { + // Allow numeric hashes + hash = isString(hash) ? hash : isNumber(hash) ? hash.toString() : $location.hash(); + var elm; + + // empty hash, scroll to the top of the page + if (!hash) scrollTo(null); + + // element with given id + else if ((elm = document.getElementById(hash))) scrollTo(elm); + + // first anchor with given name :-D + else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm); + + // no element and hash === 'top', scroll to the top of the page + else if (hash === 'top') scrollTo(null); } // does not scroll when user clicks on anchor link that is currently on // (no url change, no $location.hash() change), browser native does scroll if (autoScrollingEnabled) { $rootScope.$watch(function autoScrollWatch() {return $location.hash();}, - function autoScrollWatchAction() { - $rootScope.$evalAsync(scroll); + function autoScrollWatchAction(newVal, oldVal) { + // skip the initial scroll if $location.hash is empty + if (newVal === oldVal && newVal === '') return; + + jqLiteDocumentLoaded(function() { + $rootScope.$evalAsync(scroll); + }); }); } @@ -3996,6 +5512,169 @@ function $AnchorScrollProvider() { } var $animateMinErr = minErr('$animate'); +var ELEMENT_NODE = 1; +var NG_ANIMATE_CLASSNAME = 'ng-animate'; + +function mergeClasses(a,b) { + if (!a && !b) return ''; + if (!a) return b; + if (!b) return a; + if (isArray(a)) a = a.join(' '); + if (isArray(b)) b = b.join(' '); + return a + ' ' + b; +} + +function extractElementNode(element) { + for (var i = 0; i < element.length; i++) { + var elm = element[i]; + if (elm.nodeType === ELEMENT_NODE) { + return elm; + } + } +} + +function splitClasses(classes) { + if (isString(classes)) { + classes = classes.split(' '); + } + + // Use createMap() to prevent class assumptions involving property names in + // Object.prototype + var obj = createMap(); + forEach(classes, function(klass) { + // sometimes the split leaves empty string values + // incase extra spaces were applied to the options + if (klass.length) { + obj[klass] = true; + } + }); + return obj; +} + +// if any other type of options value besides an Object value is +// passed into the $animate.method() animation then this helper code +// will be run which will ignore it. While this patch is not the +// greatest solution to this, a lot of existing plugins depend on +// $animate to either call the callback (< 1.2) or return a promise +// that can be changed. This helper function ensures that the options +// are wiped clean incase a callback function is provided. +function prepareAnimateOptions(options) { + return isObject(options) + ? options + : {}; +} + +var $$CoreAnimateJsProvider = /** @this */ function() { + this.$get = noop; +}; + +// this is prefixed with Core since it conflicts with +// the animateQueueProvider defined in ngAnimate/animateQueue.js +var $$CoreAnimateQueueProvider = /** @this */ function() { + var postDigestQueue = new NgMap(); + var postDigestElements = []; + + this.$get = ['$$AnimateRunner', '$rootScope', + function($$AnimateRunner, $rootScope) { + return { + enabled: noop, + on: noop, + off: noop, + pin: noop, + + push: function(element, event, options, domOperation) { + if (domOperation) { + domOperation(); + } + + options = options || {}; + if (options.from) { + element.css(options.from); + } + if (options.to) { + element.css(options.to); + } + + if (options.addClass || options.removeClass) { + addRemoveClassesPostDigest(element, options.addClass, options.removeClass); + } + + var runner = new $$AnimateRunner(); + + // since there are no animations to run the runner needs to be + // notified that the animation call is complete. + runner.complete(); + return runner; + } + }; + + + function updateData(data, classes, value) { + var changed = false; + if (classes) { + classes = isString(classes) ? classes.split(' ') : + isArray(classes) ? classes : []; + forEach(classes, function(className) { + if (className) { + changed = true; + data[className] = value; + } + }); + } + return changed; + } + + function handleCSSClassChanges() { + forEach(postDigestElements, function(element) { + var data = postDigestQueue.get(element); + if (data) { + var existing = splitClasses(element.attr('class')); + var toAdd = ''; + var toRemove = ''; + forEach(data, function(status, className) { + var hasClass = !!existing[className]; + if (status !== hasClass) { + if (status) { + toAdd += (toAdd.length ? ' ' : '') + className; + } else { + toRemove += (toRemove.length ? ' ' : '') + className; + } + } + }); + + forEach(element, function(elm) { + if (toAdd) { + jqLiteAddClass(elm, toAdd); + } + if (toRemove) { + jqLiteRemoveClass(elm, toRemove); + } + }); + postDigestQueue.delete(element); + } + }); + postDigestElements.length = 0; + } + + + function addRemoveClassesPostDigest(element, add, remove) { + var data = postDigestQueue.get(element) || {}; + + var classesAdded = updateData(data, add, true); + var classesRemoved = updateData(data, remove, false); + + if (classesAdded || classesRemoved) { + + postDigestQueue.set(element, data); + postDigestElements.push(element); + + if (postDigestElements.length === 1) { + $rootScope.$$postDigest(handleCSSClassChanges); + } + } + } + }]; +}; /** * @ngdoc provider @@ -4003,20 +5682,20 @@ var $animateMinErr = minErr('$animate'); * * @description * Default implementation of $animate that doesn't perform any animations, instead just - * synchronously performs DOM - * updates and calls done() callbacks. + * synchronously performs DOM updates and resolves the returned runner promise. * - * In order to enable animations the ngAnimate module has to be loaded. + * In order to enable animations the `ngAnimate` module has to be loaded. * - * To see the functional implementation check out src/ngAnimate/animate.js + * To see the functional implementation check out `src/ngAnimate/animate.js`. */ -var $AnimateProvider = ['$provide', function($provide) { - +var $AnimateProvider = ['$provide', /** @this */ function($provide) { + var provider = this; + var classNameFilter = null; + var customFilter = null; - this.$$selectors = {}; + this.$$registeredAnimations = Object.create(null); - - /** + /** * @ngdoc method * @name $animateProvider#register * @@ -4025,36 +5704,91 @@ var $AnimateProvider = ['$provide', function($provide) { * animation object which contains callback functions for each event that is expected to be * animated. * - * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction` - * must be called once the element animation is complete. If a function is returned then the - * animation service will use this function to cancel the animation whenever a cancel event is - * triggered. + * * `eventFn`: `function(element, ... , doneFunction, options)` + * The element to animate, the `doneFunction` and the options fed into the animation. Depending + * on the type of animation additional arguments will be injected into the animation function. The + * list below explains the function signatures for the different animation methods: * + * - setClass: function(element, addedClasses, removedClasses, doneFunction, options) + * - addClass: function(element, addedClasses, doneFunction, options) + * - removeClass: function(element, removedClasses, doneFunction, options) + * - enter, leave, move: function(element, doneFunction, options) + * - animate: function(element, fromStyles, toStyles, doneFunction, options) + * + * Make sure to trigger the `doneFunction` once the animation is fully complete. * * ```js * return { - * eventFn : function(element, done) { - * //code to run the animation - * //once complete, then run done() - * return function cancellationFunction() { - * //code to cancel the animation - * } - * } - * } + * //enter, leave, move signature + * eventFn : function(element, done, options) { + * //code to run the animation + * //once complete, then run done() + * return function endFunction(wasCancelled) { + * //code to cancel the animation + * } + * } + * } * ``` * - * @param {string} name The name of the animation. + * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to). * @param {Function} factory The factory function that will be executed to return the animation * object. */ this.register = function(name, factory) { + if (name && name.charAt(0) !== '.') { + throw $animateMinErr('notcsel', 'Expecting class selector starting with \'.\' got \'{0}\'.', name); + } + var key = name + '-animation'; - if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel', - "Expecting class selector starting with '.' got '{0}'.", name); - this.$$selectors[name.substr(1)] = key; + provider.$$registeredAnimations[name.substr(1)] = key; $provide.factory(key, factory); }; + /** + * @ngdoc method + * @name $animateProvider#customFilter + * + * @description + * Sets and/or returns the custom filter function that is used to "filter" animations, i.e. + * determine if an animation is allowed or not. When no filter is specified (the default), no + * animation will be blocked. Setting the `customFilter` value will only allow animations for + * which the filter function's return value is truthy. + * + * This allows to easily create arbitrarily complex rules for filtering animations, such as + * allowing specific events only, or enabling animations on specific subtrees of the DOM, etc. + * Filtering animations can also boost performance for low-powered devices, as well as + * applications containing a lot of structural operations. + * + *
+ * **Best Practice:** + * Keep the filtering function as lean as possible, because it will be called for each DOM + * action (e.g. insertion, removal, class change) performed by "animation-aware" directives. + * See {@link guide/animations#which-directives-support-animations- here} for a list of built-in + * directives that support animations. + * Performing computationally expensive or time-consuming operations on each call of the + * filtering function can make your animations sluggish. + *
+ * + * **Note:** If present, `customFilter` will be checked before + * {@link $animateProvider#classNameFilter classNameFilter}. + * + * @param {Function=} filterFn - The filter function which will be used to filter all animations. + * If a falsy value is returned, no animation will be performed. The function will be called + * with the following arguments: + * - **node** `{DOMElement}` - The DOM element to be animated. + * - **event** `{String}` - The name of the animation event (e.g. `enter`, `leave`, `addClass` + * etc). + * - **options** `{Object}` - A collection of options/styles used for the animation. + * @return {Function} The current filter function or `null` if there is none set. + */ + this.customFilter = function(filterFn) { + if (arguments.length === 1) { + customFilter = isFunction(filterFn) ? filterFn : null; + } + + return customFilter; + }; + /** * @ngdoc method * @name $animateProvider#classNameFilter @@ -4062,384 +5796,984 @@ var $AnimateProvider = ['$provide', function($provide) { * @description * Sets and/or returns the CSS class regular expression that is checked when performing * an animation. Upon bootstrap the classNameFilter value is not set at all and will - * therefore enable $animate to attempt to perform an animation on any element. - * When setting the classNameFilter value, animations will only be performed on elements + * therefore enable $animate to attempt to perform an animation on any element that is triggered. + * When setting the `classNameFilter` value, animations will only be performed on elements * that successfully match the filter expression. This in turn can boost performance * for low-powered devices as well as applications containing a lot of structural operations. + * + * **Note:** If present, `classNameFilter` will be checked after + * {@link $animateProvider#customFilter customFilter}. If `customFilter` is present and returns + * false, `classNameFilter` will not be checked. + * * @param {RegExp=} expression The className expression which will be checked against all animations * @return {RegExp} The current CSS className expression value. If null then there is no expression value */ this.classNameFilter = function(expression) { - if(arguments.length === 1) { - this.$$classNameFilter = (expression instanceof RegExp) ? expression : null; + if (arguments.length === 1) { + classNameFilter = (expression instanceof RegExp) ? expression : null; + if (classNameFilter) { + var reservedRegex = new RegExp('[(\\s|\\/)]' + NG_ANIMATE_CLASSNAME + '[(\\s|\\/)]'); + if (reservedRegex.test(classNameFilter.toString())) { + classNameFilter = null; + throw $animateMinErr('nongcls', '$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME); + } + } } - return this.$$classNameFilter; + return classNameFilter; }; - this.$get = ['$timeout', '$$asyncCallback', function($timeout, $$asyncCallback) { - - function async(fn) { - fn && $$asyncCallback(fn); + this.$get = ['$$animateQueue', function($$animateQueue) { + function domInsert(element, parentElement, afterElement) { + // if for some reason the previous element was removed + // from the dom sometime before this code runs then let's + // just stick to using the parent element as the anchor + if (afterElement) { + var afterNode = extractElementNode(afterElement); + if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) { + afterElement = null; + } + } + if (afterElement) { + afterElement.after(element); + } else { + parentElement.prepend(element); + } } /** - * * @ngdoc service * @name $animate - * @description The $animate service provides rudimentary DOM manipulation functions to - * insert, remove and move elements within the DOM, as well as adding and removing classes. - * This service is the core service used by the ngAnimate $animator service which provides - * high-level animation hooks for CSS and JavaScript. - * - * $animate is available in the AngularJS core, however, the ngAnimate module must be included - * to enable full out animation support. Otherwise, $animate will only perform simple DOM - * manipulation operations. - * - * To learn more about enabling animation support, click here to visit the {@link ngAnimate - * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service - * page}. + * @description The $animate service exposes a series of DOM utility methods that provide support + * for animation hooks. The default behavior is the application of DOM operations, however, + * when an animation is detected (and animations are enabled), $animate will do the heavy lifting + * to ensure that animation runs with the triggered DOM operation. + * + * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't + * included and only when it is active then the animation hooks that `$animate` triggers will be + * functional. Once active then all structural `ng-` directives will trigger animations as they perform + * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`, + * `ngShow`, `ngHide` and `ngMessages` also provide support for animations. + * + * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives. + * + * To learn more about enabling animation support, click here to visit the + * {@link ngAnimate ngAnimate module page}. */ return { + // we don't call it directly since non-existant arguments may + // be interpreted as null within the sub enabled function /** * * @ngdoc method - * @name $animate#enter - * @function - * @description Inserts the element into the DOM either after the `after` element or within - * the `parent` element. Once complete, the done() callback will be fired (if provided). - * @param {DOMElement} element the element which will be inserted into the DOM - * @param {DOMElement} parent the parent element which will append the element as - * a child (if the after element is not present) - * @param {DOMElement} after the sibling element which will append the element - * after itself - * @param {Function=} done callback function that will be called after the element has been - * inserted into the DOM + * @name $animate#on + * @kind function + * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...) + * has fired on the given element or among any of its children. Once the listener is fired, the provided callback + * is fired with the following params: + * + * ```js + * $animate.on('enter', container, + * function callback(element, phase) { + * // cool we detected an enter animation within the container + * } + * ); + * ``` + * + *
+ * **Note**: Generally, the events that are fired correspond 1:1 to `$animate` method names, + * e.g. {@link ng.$animate#addClass addClass()} will fire `addClass`, and {@link ng.ngClass} + * will fire `addClass` if classes are added, and `removeClass` if classes are removed. + * However, there are two exceptions: + * + *
    + *
  • if both an {@link ng.$animate#addClass addClass()} and a + * {@link ng.$animate#removeClass removeClass()} action are performed during the same + * animation, the event fired will be `setClass`. This is true even for `ngClass`.
  • + *
  • an {@link ng.$animate#animate animate()} call that adds and removes classes will fire + * the `setClass` event, but if it either removes or adds classes, + * it will fire `animate` instead.
  • + *
+ * + *
+ * + * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...) + * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself + * as well as among its children + * @param {Function} callback the callback function that will be fired when the listener is triggered. + * + * The arguments present in the callback function are: + * * `element` - The captured DOM element that the animation was fired on. + * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends). + * * `data` - an object with these properties: + * * addClass - `{string|null}` - space-separated CSS classes to add to the element + * * removeClass - `{string|null}` - space-separated CSS classes to remove from the element + * * from - `{Object|null}` - CSS properties & values at the beginning of the animation + * * to - `{Object|null}` - CSS properties & values at the end of the animation + * + * Note that the callback does not trigger a scope digest. Wrap your call into a + * {@link $rootScope.Scope#$apply scope.$apply} to propagate changes to the scope. */ - enter : function(element, parent, after, done) { - if (after) { - after.after(element); - } else { - if (!parent || !parent[0]) { - parent = after.parent(); - } - parent.append(element); + on: $$animateQueue.on, + + /** + * + * @ngdoc method + * @name $animate#off + * @kind function + * @description Deregisters an event listener based on the event which has been associated with the provided element. This method + * can be used in three different ways depending on the arguments: + * + * ```js + * // remove all the animation event listeners listening for `enter` + * $animate.off('enter'); + * + * // remove listeners for all animation events from the container element + * $animate.off(container); + * + * // remove all the animation event listeners listening for `enter` on the given element and its children + * $animate.off('enter', container); + * + * // remove the event listener function provided by `callback` that is set + * // to listen for `enter` on the given `container` as well as its children + * $animate.off('enter', container, callback); + * ``` + * + * @param {string|DOMElement} event|container the animation event (e.g. enter, leave, move, + * addClass, removeClass, etc...), or the container element. If it is the element, all other + * arguments are ignored. + * @param {DOMElement=} container the container element the event listener was placed on + * @param {Function=} callback the callback function that was registered as the listener + */ + off: $$animateQueue.off, + + /** + * @ngdoc method + * @name $animate#pin + * @kind function + * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists + * outside of the DOM structure of the AngularJS application. By doing so, any animation triggered via `$animate` can be issued on the + * element despite being outside the realm of the application or within another application. Say for example if the application + * was bootstrapped on an element that is somewhere inside of the `` tag, but we wanted to allow for an element to be situated + * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind + * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association. + * + * Note that this feature is only active when the `ngAnimate` module is used. + * + * @param {DOMElement} element the external element that will be pinned + * @param {DOMElement} parentElement the host parent element that will be associated with the external element + */ + pin: $$animateQueue.pin, + + /** + * + * @ngdoc method + * @name $animate#enabled + * @kind function + * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This + * function can be called in four ways: + * + * ```js + * // returns true or false + * $animate.enabled(); + * + * // changes the enabled state for all animations + * $animate.enabled(false); + * $animate.enabled(true); + * + * // returns true or false if animations are enabled for an element + * $animate.enabled(element); + * + * // changes the enabled state for an element and its children + * $animate.enabled(element, true); + * $animate.enabled(element, false); + * ``` + * + * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state + * @param {boolean=} enabled whether or not the animations will be enabled for the element + * + * @return {boolean} whether or not animations are enabled + */ + enabled: $$animateQueue.enabled, + + /** + * @ngdoc method + * @name $animate#cancel + * @kind function + * @description Cancels the provided animation and applies the end state of the animation. + * Note that this does not cancel the underlying operation, e.g. the setting of classes or + * adding the element to the DOM. + * + * @param {animationRunner} animationRunner An animation runner returned by an $animate function. + * + * @example + + + angular.module('animationExample', ['ngAnimate']).component('cancelExample', { + templateUrl: 'template.html', + controller: function($element, $animate) { + this.runner = null; + + this.addClass = function() { + this.runner = $animate.addClass($element.find('div'), 'red'); + var ctrl = this; + this.runner.finally(function() { + ctrl.runner = null; + }); + }; + + this.removeClass = function() { + this.runner = $animate.removeClass($element.find('div'), 'red'); + var ctrl = this; + this.runner.finally(function() { + ctrl.runner = null; + }); + }; + + this.cancel = function() { + $animate.cancel(this.runner); + }; + } + }); + + +

+ + +
+ +
+

CSS-Animated Text
+

+
+ + + + + .red-add, .red-remove { + transition: all 4s cubic-bezier(0.250, 0.460, 0.450, 0.940); + } + + .red, + .red-add.red-add-active { + color: #FF0000; + font-size: 40px; + } + + .red-remove.red-remove-active { + font-size: 10px; + color: black; + } + + +
+ */ + cancel: function(runner) { + if (runner.cancel) { + runner.cancel(); } - async(done); }, /** * * @ngdoc method - * @name $animate#leave - * @function - * @description Removes the element from the DOM. Once complete, the done() callback will be - * fired (if provided). - * @param {DOMElement} element the element which will be removed from the DOM - * @param {Function=} done callback function that will be called after the element has been - * removed from the DOM + * @name $animate#enter + * @kind function + * @description Inserts the element into the DOM either after the `after` element (if provided) or + * as the first child within the `parent` element and then triggers an animation. + * A promise is returned that will be resolved during the next digest once the animation + * has completed. + * + * @param {DOMElement} element the element which will be inserted into the DOM + * @param {DOMElement} parent the parent element which will append the element as + * a child (so long as the after element is not present) + * @param {DOMElement=} after the sibling element after which the element will be appended + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **addClass** - `{string}` - space-separated CSS classes to add to element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **removeClass** - `{string}` - space-separated CSS classes to remove from element + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` + * + * @return {Runner} the animation runner */ - leave : function(element, done) { - element.remove(); - async(done); + enter: function(element, parent, after, options) { + parent = parent && jqLite(parent); + after = after && jqLite(after); + parent = parent || after.parent(); + domInsert(element, parent, after); + return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options)); }, /** * * @ngdoc method * @name $animate#move - * @function - * @description Moves the position of the provided element within the DOM to be placed - * either after the `after` element or inside of the `parent` element. Once complete, the - * done() callback will be fired (if provided). + * @kind function + * @description Inserts (moves) the element into its new position in the DOM either after + * the `after` element (if provided) or as the first child within the `parent` element + * and then triggers an animation. A promise is returned that will be resolved + * during the next digest once the animation has completed. + * + * @param {DOMElement} element the element which will be moved into the new DOM position + * @param {DOMElement} parent the parent element which will append the element as + * a child (so long as the after element is not present) + * @param {DOMElement=} after the sibling element after which the element will be appended + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **addClass** - `{string}` - space-separated CSS classes to add to element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **removeClass** - `{string}` - space-separated CSS classes to remove from element + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` * - * @param {DOMElement} element the element which will be moved around within the - * DOM - * @param {DOMElement} parent the parent element where the element will be - * inserted into (if the after element is not present) - * @param {DOMElement} after the sibling element where the element will be - * positioned next to - * @param {Function=} done the callback function (if provided) that will be fired after the - * element has been moved to its new position + * @return {Runner} the animation runner */ - move : function(element, parent, after, done) { - // Do not remove element before insert. Removing will cause data associated with the - // element to be dropped. Insert will implicitly do the remove. - this.enter(element, parent, after, done); + move: function(element, parent, after, options) { + parent = parent && jqLite(parent); + after = after && jqLite(after); + parent = parent || after.parent(); + domInsert(element, parent, after); + return $$animateQueue.push(element, 'move', prepareAnimateOptions(options)); }, /** - * * @ngdoc method - * @name $animate#addClass - * @function - * @description Adds the provided className CSS class value to the provided element. Once - * complete, the done() callback will be fired (if provided). - * @param {DOMElement} element the element which will have the className value - * added to it - * @param {string} className the CSS class which will be added to the element - * @param {Function=} done the callback function (if provided) that will be fired after the - * className value has been added to the element + * @name $animate#leave + * @kind function + * @description Triggers an animation and then removes the element from the DOM. + * When the function is called a promise is returned that will be resolved during the next + * digest once the animation has completed. + * + * @param {DOMElement} element the element which will be removed from the DOM + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **addClass** - `{string}` - space-separated CSS classes to add to element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **removeClass** - `{string}` - space-separated CSS classes to remove from element + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` + * + * @return {Runner} the animation runner */ - addClass : function(element, className, done) { - className = isString(className) ? - className : - isArray(className) ? className.join(' ') : ''; - forEach(element, function (element) { - jqLiteAddClass(element, className); + leave: function(element, options) { + return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() { + element.remove(); }); - async(done); }, /** + * @ngdoc method + * @name $animate#addClass + * @kind function + * + * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon + * execution, the addClass operation will only be handled after the next digest and it will not trigger an + * animation if element already contains the CSS class or if the class is removed at a later step. + * Note that class-based animations are treated differently compared to structural animations + * (like enter, move and leave) since the CSS classes may be added/removed at different points + * depending if CSS or JavaScript animations are used. * + * @param {DOMElement} element the element which the CSS classes will be applied to + * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces) + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **removeClass** - `{string}` - space-separated CSS classes to remove from element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` + * + * @return {Runner} animationRunner the animation runner + */ + addClass: function(element, className, options) { + options = prepareAnimateOptions(options); + options.addClass = mergeClasses(options.addclass, className); + return $$animateQueue.push(element, 'addClass', options); + }, + + /** * @ngdoc method * @name $animate#removeClass - * @function - * @description Removes the provided className CSS class value from the provided element. - * Once complete, the done() callback will be fired (if provided). - * @param {DOMElement} element the element which will have the className value - * removed from it - * @param {string} className the CSS class which will be removed from the element - * @param {Function=} done the callback function (if provided) that will be fired after the - * className value has been removed from the element + * @kind function + * + * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon + * execution, the removeClass operation will only be handled after the next digest and it will not trigger an + * animation if element does not contain the CSS class or if the class is added at a later step. + * Note that class-based animations are treated differently compared to structural animations + * (like enter, move and leave) since the CSS classes may be added/removed at different points + * depending if CSS or JavaScript animations are used. + * + * @param {DOMElement} element the element which the CSS classes will be applied to + * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces) + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **addClass** - `{string}` - space-separated CSS classes to add to element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` + * + * @return {Runner} the animation runner */ - removeClass : function(element, className, done) { - className = isString(className) ? - className : - isArray(className) ? className.join(' ') : ''; - forEach(element, function (element) { - jqLiteRemoveClass(element, className); - }); - async(done); + removeClass: function(element, className, options) { + options = prepareAnimateOptions(options); + options.removeClass = mergeClasses(options.removeClass, className); + return $$animateQueue.push(element, 'removeClass', options); }, /** - * * @ngdoc method * @name $animate#setClass - * @function - * @description Adds and/or removes the given CSS classes to and from the element. - * Once complete, the done() callback will be fired (if provided). - * @param {DOMElement} element the element which will it's CSS classes changed - * removed from it - * @param {string} add the CSS classes which will be added to the element - * @param {string} remove the CSS class which will be removed from the element - * @param {Function=} done the callback function (if provided) that will be fired after the - * CSS classes have been set on the element + * @kind function + * + * @description Performs both the addition and removal of a CSS classes on an element and (during the process) + * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and + * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has + * passed. Note that class-based animations are treated differently compared to structural animations + * (like enter, move and leave) since the CSS classes may be added/removed at different points + * depending if CSS or JavaScript animations are used. + * + * @param {DOMElement} element the element which the CSS classes will be applied to + * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces) + * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces) + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **addClass** - `{string}` - space-separated CSS classes to add to element + * - **removeClass** - `{string}` - space-separated CSS classes to remove from element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` + * + * @return {Runner} the animation runner */ - setClass : function(element, add, remove, done) { - forEach(element, function (element) { - jqLiteAddClass(element, add); - jqLiteRemoveClass(element, remove); - }); - async(done); + setClass: function(element, add, remove, options) { + options = prepareAnimateOptions(options); + options.addClass = mergeClasses(options.addClass, add); + options.removeClass = mergeClasses(options.removeClass, remove); + return $$animateQueue.push(element, 'setClass', options); }, - enabled : noop + /** + * @ngdoc method + * @name $animate#animate + * @kind function + * + * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element. + * If any detected CSS transition, keyframe or JavaScript matches the provided className value, then the animation will take + * on the provided styles. For example, if a transition animation is set for the given className, then the provided `from` and + * `to` styles will be applied alongside the given transition. If the CSS style provided in `from` does not have a corresponding + * style in `to`, the style in `from` is applied immediately, and no animation is run. + * If a JavaScript animation is detected then the provided styles will be given in as function parameters into the `animate` + * method (or as part of the `options` parameter): + * + * ```js + * ngModule.animation('.my-inline-animation', function() { + * return { + * animate : function(element, from, to, done, options) { + * //animation + * done(); + * } + * } + * }); + * ``` + * + * @param {DOMElement} element the element which the CSS styles will be applied to + * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation. + * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation. + * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If + * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element. + * (Note that if no animation is detected then this value will not be applied to the element.) + * @param {object=} options an optional collection of options/styles that will be applied to the element. + * The object can have the following properties: + * + * - **addClass** - `{string}` - space-separated CSS classes to add to element + * - **from** - `{Object}` - CSS properties & values at the beginning of animation. Must have matching `to` + * - **removeClass** - `{string}` - space-separated CSS classes to remove from element + * - **to** - `{Object}` - CSS properties & values at end of animation. Must have matching `from` + * + * @return {Runner} the animation runner + */ + animate: function(element, from, to, className, options) { + options = prepareAnimateOptions(options); + options.from = options.from ? extend(options.from, from) : from; + options.to = options.to ? extend(options.to, to) : to; + + className = className || 'ng-inline-animate'; + options.tempClasses = mergeClasses(options.tempClasses, className); + return $$animateQueue.push(element, 'animate', options); + } }; }]; }]; -function $$AsyncCallbackProvider(){ - this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) { - return $$rAF.supported - ? function(fn) { return $$rAF(fn); } - : function(fn) { - return $timeout(fn, 0, false); +var $$AnimateAsyncRunFactoryProvider = /** @this */ function() { + this.$get = ['$$rAF', function($$rAF) { + var waitQueue = []; + + function waitForTick(fn) { + waitQueue.push(fn); + if (waitQueue.length > 1) return; + $$rAF(function() { + for (var i = 0; i < waitQueue.length; i++) { + waitQueue[i](); + } + waitQueue = []; + }); + } + + return function() { + var passed = false; + waitForTick(function() { + passed = true; + }); + return function(callback) { + if (passed) { + callback(); + } else { + waitForTick(callback); + } }; + }; }]; -} +}; -/** - * ! This is a private undocumented service ! - * - * @name $browser - * @requires $log - * @description - * This object has two goals: - * - * - hide all the global state in the browser caused by the window object - * - abstract away all the browser specific features and inconsistencies - * - * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` - * service, which can be used for convenient testing of the application without the interaction with - * the real browser apis. - */ -/** +var $$AnimateRunnerFactoryProvider = /** @this */ function() { + this.$get = ['$q', '$sniffer', '$$animateAsyncRun', '$$isDocumentHidden', '$timeout', + function($q, $sniffer, $$animateAsyncRun, $$isDocumentHidden, $timeout) { + + var INITIAL_STATE = 0; + var DONE_PENDING_STATE = 1; + var DONE_COMPLETE_STATE = 2; + + AnimateRunner.chain = function(chain, callback) { + var index = 0; + + next(); + function next() { + if (index === chain.length) { + callback(true); + return; + } + + chain[index](function(response) { + if (response === false) { + callback(false); + return; + } + index++; + next(); + }); + } + }; + + AnimateRunner.all = function(runners, callback) { + var count = 0; + var status = true; + forEach(runners, function(runner) { + runner.done(onProgress); + }); + + function onProgress(response) { + status = status && response; + if (++count === runners.length) { + callback(status); + } + } + }; + + function AnimateRunner(host) { + this.setHost(host); + + var rafTick = $$animateAsyncRun(); + var timeoutTick = function(fn) { + $timeout(fn, 0, false); + }; + + this._doneCallbacks = []; + this._tick = function(fn) { + if ($$isDocumentHidden()) { + timeoutTick(fn); + } else { + rafTick(fn); + } + }; + this._state = 0; + } + + AnimateRunner.prototype = { + setHost: function(host) { + this.host = host || {}; + }, + + done: function(fn) { + if (this._state === DONE_COMPLETE_STATE) { + fn(); + } else { + this._doneCallbacks.push(fn); + } + }, + + progress: noop, + + getPromise: function() { + if (!this.promise) { + var self = this; + this.promise = $q(function(resolve, reject) { + self.done(function(status) { + if (status === false) { + reject(); + } else { + resolve(); + } + }); + }); + } + return this.promise; + }, + + then: function(resolveHandler, rejectHandler) { + return this.getPromise().then(resolveHandler, rejectHandler); + }, + + 'catch': function(handler) { + return this.getPromise()['catch'](handler); + }, + + 'finally': function(handler) { + return this.getPromise()['finally'](handler); + }, + + pause: function() { + if (this.host.pause) { + this.host.pause(); + } + }, + + resume: function() { + if (this.host.resume) { + this.host.resume(); + } + }, + + end: function() { + if (this.host.end) { + this.host.end(); + } + this._resolve(true); + }, + + cancel: function() { + if (this.host.cancel) { + this.host.cancel(); + } + this._resolve(false); + }, + + complete: function(response) { + var self = this; + if (self._state === INITIAL_STATE) { + self._state = DONE_PENDING_STATE; + self._tick(function() { + self._resolve(response); + }); + } + }, + + _resolve: function(response) { + if (this._state !== DONE_COMPLETE_STATE) { + forEach(this._doneCallbacks, function(fn) { + fn(response); + }); + this._doneCallbacks.length = 0; + this._state = DONE_COMPLETE_STATE; + } + } + }; + + return AnimateRunner; + }]; +}; + +/* exported $CoreAnimateCssProvider */ + +/** + * @ngdoc service + * @name $animateCss + * @kind object + * @this + * + * @description + * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included, + * then the `$animateCss` service will actually perform animations. + * + * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}. + */ +var $CoreAnimateCssProvider = function() { + this.$get = ['$$rAF', '$q', '$$AnimateRunner', function($$rAF, $q, $$AnimateRunner) { + + return function(element, initialOptions) { + // all of the animation functions should create + // a copy of the options data, however, if a + // parent service has already created a copy then + // we should stick to using that + var options = initialOptions || {}; + if (!options.$$prepared) { + options = copy(options); + } + + // there is no point in applying the styles since + // there is no animation that goes on at all in + // this version of $animateCss. + if (options.cleanupStyles) { + options.from = options.to = null; + } + + if (options.from) { + element.css(options.from); + options.from = null; + } + + var closed, runner = new $$AnimateRunner(); + return { + start: run, + end: run + }; + + function run() { + $$rAF(function() { + applyAnimationContents(); + if (!closed) { + runner.complete(); + } + closed = true; + }); + return runner; + } + + function applyAnimationContents() { + if (options.addClass) { + element.addClass(options.addClass); + options.addClass = null; + } + if (options.removeClass) { + element.removeClass(options.removeClass); + options.removeClass = null; + } + if (options.to) { + element.css(options.to); + options.to = null; + } + } + }; + }]; +}; + +/* global getHash: true, stripHash: false */ + +function getHash(url) { + var index = url.indexOf('#'); + return index === -1 ? '' : url.substr(index); +} + +function trimEmptyHash(url) { + return url.replace(/#$/, ''); +} + +/** + * ! This is a private undocumented service ! + * + * @name $browser + * @requires $log + * @description + * This object has two goals: + * + * - hide all the global state in the browser caused by the window object + * - abstract away all the browser specific features and inconsistencies + * + * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` + * service, which can be used for convenient testing of the application without the interaction with + * the real browser apis. + */ +/** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. - * @param {function()} XHR XMLHttpRequest constructor. - * @param {object} $log console.log or an object with the same interface. + * @param {object} $log window.console or an object with the same interface. * @param {object} $sniffer $sniffer service */ -function Browser(window, document, $log, $sniffer) { +function Browser(window, document, $log, $sniffer, $$taskTrackerFactory) { var self = this, - rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, - pendingDeferIds = {}; + pendingDeferIds = {}, + taskTracker = $$taskTrackerFactory($log); self.isMock = false; - var outstandingRequestCount = 0; - var outstandingRequestCallbacks = []; - - // TODO(vojta): remove this temporary api - self.$$completeOutstandingRequest = completeOutstandingRequest; - self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; - - /** - * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` - * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. - */ - function completeOutstandingRequest(fn) { - try { - fn.apply(null, sliceArgs(arguments, 1)); - } finally { - outstandingRequestCount--; - if (outstandingRequestCount === 0) { - while(outstandingRequestCallbacks.length) { - try { - outstandingRequestCallbacks.pop()(); - } catch (e) { - $log.error(e); - } - } - } - } - } - - /** - * @private - * Note: this method is used only by scenario runner - * TODO(vojta): prefix this method with $$ ? - * @param {function()} callback Function that will be called when no outstanding request - */ - self.notifyWhenNoOutstandingRequests = function(callback) { - // force browser to execute all pollFns - this is needed so that cookies and other pollers fire - // at some deterministic time in respect to the test runner's actions. Leaving things up to the - // regular poller would result in flaky tests. - forEach(pollFns, function(pollFn){ pollFn(); }); - - if (outstandingRequestCount === 0) { - callback(); - } else { - outstandingRequestCallbacks.push(callback); - } - }; - ////////////////////////////////////////////////////////////// - // Poll Watcher API + // Task-tracking API ////////////////////////////////////////////////////////////// - var pollFns = [], - pollTimeout; - /** - * @name $browser#addPollFn - * - * @param {function()} fn Poll function to add - * - * @description - * Adds a function to the list of functions that poller periodically executes, - * and starts polling if not started yet. - * - * @returns {function()} the added function - */ - self.addPollFn = function(fn) { - if (isUndefined(pollTimeout)) startPoller(100, setTimeout); - pollFns.push(fn); - return fn; - }; + // TODO(vojta): remove this temporary api + self.$$completeOutstandingRequest = taskTracker.completeTask; + self.$$incOutstandingRequestCount = taskTracker.incTaskCount; - /** - * @param {number} interval How often should browser call poll functions (ms) - * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. - * - * @description - * Configures the poller to run in the specified intervals, using the specified - * setTimeout fn and kicks it off. - */ - function startPoller(interval, setTimeout) { - (function check() { - forEach(pollFns, function(pollFn){ pollFn(); }); - pollTimeout = setTimeout(check, interval); - })(); - } + // TODO(vojta): prefix this method with $$ ? + self.notifyWhenNoOutstandingRequests = taskTracker.notifyWhenNoPendingTasks; ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// - var lastBrowserUrl = location.href, + var cachedState, lastHistoryState, + lastBrowserUrl = location.href, baseElement = document.find('base'), - newLocation = null; + pendingLocation = null, + getCurrentState = !$sniffer.history ? noop : function getCurrentState() { + try { + return history.state; + } catch (e) { + // MSIE can reportedly throw when there is no state (UNCONFIRMED). + } + }; + + cacheState(); /** * @name $browser#url * * @description * GETTER: - * Without any argument, this method just returns current value of location.href. + * Without any argument, this method just returns current value of `location.href` (with a + * trailing `#` stripped of if the hash is empty). * * SETTER: * With at least one argument, this method sets url to new value. - * If html5 history api supported, pushState/replaceState is used, otherwise - * location.href/location.replace is used. - * Returns its own instance to allow chaining + * If html5 history api supported, `pushState`/`replaceState` is used, otherwise + * `location.href`/`location.replace` is used. + * Returns its own instance to allow chaining. * - * NOTE: this api is intended for use only by the $location service. Please use the + * NOTE: this api is intended for use only by the `$location` service. Please use the * {@link ng.$location $location service} to change url. * * @param {string} url New url (when used as setter) - * @param {boolean=} replace Should new url replace current history record ? + * @param {boolean=} replace Should new url replace current history record? + * @param {object=} state State object to use with `pushState`/`replaceState` */ - self.url = function(url, replace) { + self.url = function(url, replace, state) { + // In modern browsers `history.state` is `null` by default; treating it separately + // from `undefined` would cause `$browser.url('/foo')` to change `history.state` + // to undefined via `pushState`. Instead, let's change `undefined` to `null` here. + if (isUndefined(state)) { + state = null; + } + // Android Browser BFCache causes location, history reference to become stale. if (location !== window.location) location = window.location; if (history !== window.history) history = window.history; // setter if (url) { - if (lastBrowserUrl == url) return; + var sameState = lastHistoryState === state; + + // Normalize the inputted URL + url = urlResolve(url).href; + + // Don't change anything if previous and current URLs and states match. This also prevents + // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode. + // See https://github.com/angular/angular.js/commit/ffb2701 + if (lastBrowserUrl === url && (!$sniffer.history || sameState)) { + return self; + } + var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url); lastBrowserUrl = url; - if ($sniffer.history) { - if (replace) history.replaceState(null, '', url); - else { - history.pushState(null, '', url); - // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 - baseElement.attr('href', baseElement.attr('href')); - } + lastHistoryState = state; + // Don't use history API if only the hash changed + // due to a bug in IE10/IE11 which leads + // to not firing a `hashchange` nor `popstate` event + // in some cases (see #9143). + if ($sniffer.history && (!sameBase || !sameState)) { + history[replace ? 'replaceState' : 'pushState'](state, '', url); + cacheState(); } else { - newLocation = url; + if (!sameBase) { + pendingLocation = url; + } if (replace) { location.replace(url); - } else { + } else if (!sameBase) { location.href = url; + } else { + location.hash = getHash(url); + } + if (location.href !== url) { + pendingLocation = url; } } + if (pendingLocation) { + pendingLocation = url; + } return self; // getter } else { - // - newLocation is a workaround for an IE7-9 issue with location.replace and location.href - // methods not updating location.href synchronously. - // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 - return newLocation || location.href.replace(/%27/g,"'"); + // - pendingLocation is needed as browsers don't allow to read out + // the new location.href if a reload happened or if there is a bug like in iOS 9 (see + // https://openradar.appspot.com/22186109). + return trimEmptyHash(pendingLocation || location.href); } }; + /** + * @name $browser#state + * + * @description + * This method is a getter. + * + * Return history.state or null if history.state is undefined. + * + * @returns {object} state + */ + self.state = function() { + return cachedState; + }; + var urlChangeListeners = [], urlChangeInit = false; - function fireUrlChange() { - newLocation = null; - if (lastBrowserUrl == self.url()) return; + function cacheStateAndFireUrlChange() { + pendingLocation = null; + fireStateOrUrlChange(); + } + + // This variable should be used *only* inside the cacheState function. + var lastCachedState = null; + function cacheState() { + // This should be the only place in $browser where `history.state` is read. + cachedState = getCurrentState(); + cachedState = isUndefined(cachedState) ? null : cachedState; + + // Prevent callbacks fo fire twice if both hashchange & popstate were fired. + if (equals(cachedState, lastCachedState)) { + cachedState = lastCachedState; + } + + lastCachedState = cachedState; + lastHistoryState = cachedState; + } + + function fireStateOrUrlChange() { + var prevLastHistoryState = lastHistoryState; + cacheState(); + + if (lastBrowserUrl === self.url() && prevLastHistoryState === cachedState) { + return; + } lastBrowserUrl = self.url(); + lastHistoryState = cachedState; forEach(urlChangeListeners, function(listener) { - listener(self.url()); + listener(self.url(), cachedState); }); } @@ -4449,7 +6783,7 @@ function Browser(window, document, $log, $sniffer) { * @description * Register callback function that will be called, when url changes. * - * It's only called when the url is changed from outside of angular: + * It's only called when the url is changed from outside of AngularJS: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link @@ -4459,7 +6793,7 @@ function Browser(window, document, $log, $sniffer) { * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the - * {@link ng.$location $location service} to monitor url changes in angular apps. + * {@link ng.$location $location service} to monitor url changes in AngularJS apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. @@ -4467,16 +6801,14 @@ function Browser(window, document, $log, $sniffer) { self.onUrlChange = function(callback) { // TODO(vojta): refactor to use node's syntax for events if (!urlChangeInit) { - // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) - // don't fire popstate when user change the address bar and don't fire hashchange when url + // We listen on both (hashchange/popstate) when available, as some browsers don't + // fire popstate when user changes the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event - if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange); + if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange); // hashchange event - if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange); - // polling - else self.addPollFn(fireUrlChange); + jqLite(window).on('hashchange', cacheStateAndFireUrlChange); urlChangeInit = true; } @@ -4485,6 +6817,23 @@ function Browser(window, document, $log, $sniffer) { return callback; }; + /** + * @private + * Remove popstate and hashchange handler from window. + * + * NOTE: this api is intended for use only by $rootScope. + */ + self.$$applicationDestroyed = function() { + jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange); + }; + + /** + * Checks whether the url has changed outside of AngularJS. + * Needs to be exported to be able to check for changes that have been done in sync, + * as hashchange/popstate events fire in async. + */ + self.$$checkUrlChange = fireStateOrUrlChange; + ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// @@ -4500,89 +6849,14 @@ function Browser(window, document, $log, $sniffer) { */ self.baseHref = function() { var href = baseElement.attr('href'); - return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : ''; - }; - - ////////////////////////////////////////////////////////////// - // Cookies API - ////////////////////////////////////////////////////////////// - var lastCookies = {}; - var lastCookieString = ''; - var cookiePath = self.baseHref(); - - /** - * @name $browser#cookies - * - * @param {string=} name Cookie name - * @param {string=} value Cookie value - * - * @description - * The cookies method provides a 'private' low level access to browser cookies. - * It is not meant to be used directly, use the $cookie service instead. - * - * The return values vary depending on the arguments that the method was called with as follows: - * - * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify - * it - * - cookies(name, value) -> set name to value, if value is undefined delete the cookie - * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that - * way) - * - * @returns {Object} Hash of all cookies (if called without any parameter) - */ - self.cookies = function(name, value) { - /* global escape: false, unescape: false */ - var cookieLength, cookieArray, cookie, i, index; - - if (name) { - if (value === undefined) { - rawDocument.cookie = escape(name) + "=;path=" + cookiePath + - ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; - } else { - if (isString(value)) { - cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + - ';path=' + cookiePath).length + 1; - - // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: - // - 300 cookies - // - 20 cookies per unique domain - // - 4096 bytes per cookie - if (cookieLength > 4096) { - $log.warn("Cookie '"+ name + - "' possibly not set or overflowed because it was too large ("+ - cookieLength + " > 4096 bytes)!"); - } - } - } - } else { - if (rawDocument.cookie !== lastCookieString) { - lastCookieString = rawDocument.cookie; - cookieArray = lastCookieString.split("; "); - lastCookies = {}; - - for (i = 0; i < cookieArray.length; i++) { - cookie = cookieArray[i]; - index = cookie.indexOf('='); - if (index > 0) { //ignore nameless cookies - name = unescape(cookie.substring(0, index)); - // the first value that is seen for a cookie is the most - // specific one. values for the same cookie name that - // follow are for less specific paths. - if (lastCookies[name] === undefined) { - lastCookies[name] = unescape(cookie.substring(index + 1)); - } - } - } - } - return lastCookies; - } + return href ? href.replace(/^(https?:)?\/\/[^/]*/, '') : ''; }; - /** * @name $browser#defer * @param {function()} fn A function, who's execution should be deferred. - * @param {number=} [delay=0] of milliseconds to defer the function execution. + * @param {number=} [delay=0] Number of milliseconds to defer the function execution. + * @param {string=} [taskType=DEFAULT_TASK_TYPE] The type of task that is deferred. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description @@ -4593,14 +6867,19 @@ function Browser(window, document, $log, $sniffer) { * via `$browser.defer.flush()`. * */ - self.defer = function(fn, delay) { + self.defer = function(fn, delay, taskType) { var timeoutId; - outstandingRequestCount++; + + delay = delay || 0; + taskType = taskType || taskTracker.DEFAULT_TASK_TYPE; + + taskTracker.incTaskCount(taskType); timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; - completeOutstandingRequest(fn); - }, delay || 0); - pendingDeferIds[timeoutId] = true; + taskTracker.completeTask(fn, taskType); + }, delay); + pendingDeferIds[timeoutId] = taskType; + return timeoutId; }; @@ -4616,10 +6895,11 @@ function Browser(window, document, $log, $sniffer) { * canceled. */ self.defer.cancel = function(deferId) { - if (pendingDeferIds[deferId]) { + if (pendingDeferIds.hasOwnProperty(deferId)) { + var taskType = pendingDeferIds[deferId]; delete pendingDeferIds[deferId]; clearTimeout(deferId); - completeOutstandingRequest(noop); + taskTracker.completeTask(noop, taskType); return true; } return false; @@ -4627,16 +6907,18 @@ function Browser(window, document, $log, $sniffer) { } -function $BrowserProvider(){ - this.$get = ['$window', '$log', '$sniffer', '$document', - function( $window, $log, $sniffer, $document){ - return new Browser($window, $document, $log, $sniffer); - }]; +/** @this */ +function $BrowserProvider() { + this.$get = ['$window', '$log', '$sniffer', '$document', '$$taskTrackerFactory', + function($window, $log, $sniffer, $document, $$taskTrackerFactory) { + return new Browser($window, $document, $log, $sniffer, $$taskTrackerFactory); + }]; } /** * @ngdoc service * @name $cacheFactory + * @this * * @description * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to @@ -4673,7 +6955,7 @@ function $BrowserProvider(){ * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory. * * @example - +
@@ -4701,8 +6983,10 @@ function $BrowserProvider(){ $scope.keys = []; $scope.cache = $cacheFactory('cacheId'); $scope.put = function(key, value) { - $scope.cache.put(key, value); - $scope.keys.push(key); + if (angular.isUndefined($scope.cache.get(key))) { + $scope.keys.push(key); + } + $scope.cache.put(key, angular.isUndefined(value) ? null : value); }; }]); @@ -4720,14 +7004,14 @@ function $CacheFactoryProvider() { function cacheFactory(cacheId, options) { if (cacheId in caches) { - throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId); + throw minErr('$cacheFactory')('iid', 'CacheId \'{0}\' is already taken!', cacheId); } var size = 0, stats = extend({}, options, {id: cacheId}), - data = {}, + data = createMap(), capacity = (options && options.capacity) || Number.MAX_VALUE, - lruHash = {}, + lruHash = createMap(), freshEnd = null, staleEnd = null; @@ -4737,8 +7021,8 @@ function $CacheFactoryProvider() { * * @description * A cache object used to store and retrieve data, primarily used by - * {@link $http $http} and the {@link ng.directive:script script} directive to cache - * templates and other data. + * {@link $templateRequest $templateRequest} and the {@link ng.directive:script script} + * directive to cache templates and other data. * * ```js * angular.module('superCache') @@ -4770,12 +7054,12 @@ function $CacheFactoryProvider() { * })); * ``` */ - return caches[cacheId] = { + return (caches[cacheId] = { /** * @ngdoc method * @name $cacheFactory.Cache#put - * @function + * @kind function * * @description * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be @@ -4791,13 +7075,13 @@ function $CacheFactoryProvider() { * @returns {*} the value stored. */ put: function(key, value) { + if (isUndefined(value)) return; if (capacity < Number.MAX_VALUE) { var lruEntry = lruHash[key] || (lruHash[key] = {key: key}); refresh(lruEntry); } - if (isUndefined(value)) return; if (!(key in data)) size++; data[key] = value; @@ -4811,7 +7095,7 @@ function $CacheFactoryProvider() { /** * @ngdoc method * @name $cacheFactory.Cache#get - * @function + * @kind function * * @description * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object. @@ -4835,7 +7119,7 @@ function $CacheFactoryProvider() { /** * @ngdoc method * @name $cacheFactory.Cache#remove - * @function + * @kind function * * @description * Removes an entry from the {@link $cacheFactory.Cache Cache} object. @@ -4848,13 +7132,15 @@ function $CacheFactoryProvider() { if (!lruEntry) return; - if (lruEntry == freshEnd) freshEnd = lruEntry.p; - if (lruEntry == staleEnd) staleEnd = lruEntry.n; + if (lruEntry === freshEnd) freshEnd = lruEntry.p; + if (lruEntry === staleEnd) staleEnd = lruEntry.n; link(lruEntry.n,lruEntry.p); delete lruHash[key]; } + if (!(key in data)) return; + delete data[key]; size--; }, @@ -4863,15 +7149,15 @@ function $CacheFactoryProvider() { /** * @ngdoc method * @name $cacheFactory.Cache#removeAll - * @function + * @kind function * * @description * Clears the cache object of any entries. */ removeAll: function() { - data = {}; + data = createMap(); size = 0; - lruHash = {}; + lruHash = createMap(); freshEnd = staleEnd = null; }, @@ -4879,7 +7165,7 @@ function $CacheFactoryProvider() { /** * @ngdoc method * @name $cacheFactory.Cache#destroy - * @function + * @kind function * * @description * Destroys the {@link $cacheFactory.Cache Cache} object entirely, @@ -4896,7 +7182,7 @@ function $CacheFactoryProvider() { /** * @ngdoc method * @name $cacheFactory.Cache#info - * @function + * @kind function * * @description * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}. @@ -4912,17 +7198,17 @@ function $CacheFactoryProvider() { info: function() { return extend({}, stats, {size: size}); } - }; + }); /** * makes the `entry` the freshEnd of the LRU linked list */ function refresh(entry) { - if (entry != freshEnd) { + if (entry !== freshEnd) { if (!staleEnd) { staleEnd = entry; - } else if (staleEnd == entry) { + } else if (staleEnd === entry) { staleEnd = entry.n; } @@ -4938,7 +7224,7 @@ function $CacheFactoryProvider() { * bidirectionally links two entries of the LRU linked list */ function link(nextEntry, prevEntry) { - if (nextEntry != prevEntry) { + if (nextEntry !== prevEntry) { if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify } @@ -4951,7 +7237,7 @@ function $CacheFactoryProvider() { * @name $cacheFactory#info * * @description - * Get information about all the of the caches that have been created + * Get information about all the caches that have been created * * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info` */ @@ -4986,11 +7272,15 @@ function $CacheFactoryProvider() { /** * @ngdoc service * @name $templateCache + * @this * * @description + * `$templateCache` is a {@link $cacheFactory.Cache Cache object} created by the + * {@link ng.$cacheFactory $cacheFactory}. + * * The first time a template is used, it is loaded in the template cache for quick retrieval. You - * can load templates directly into the cache in a `script` tag, or by consuming the - * `$templateCache` service directly. + * can load templates directly into the cache in a `script` tag, by using {@link $templateRequest}, + * or by consuming the `$templateCache` service directly. * * Adding via the `script` tag: * @@ -5001,9 +7291,10 @@ function $CacheFactoryProvider() { * ``` * * **Note:** the `script` tag containing the template does not need to be included in the `head` of - * the document, but it must be below the `ng-app` definition. + * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (e.g. + * element with {@link ngApp} attribute), otherwise the template will be ignored. * - * Adding via the $templateCache service: + * Adding via the `$templateCache` service: * * ```js * var myApp = angular.module('myApp', []); @@ -5012,18 +7303,18 @@ function $CacheFactoryProvider() { * }); * ``` * - * To retrieve the template later, simply use it in your HTML: - * ```html - *
+ * To retrieve the template later, simply use it in your component: + * ```js + * myApp.component('myComponent', { + * templateUrl: 'templateId.html' + * }); * ``` * - * or get it via Javascript: + * or get it via the `$templateCache` service: * ```js * $templateCache.get('templateId.html') * ``` * - * See {@link ng.$cacheFactory $cacheFactory}. - * */ function $TemplateCacheProvider() { this.$get = ['$cacheFactory', function($cacheFactory) { @@ -5031,6 +7322,17 @@ function $TemplateCacheProvider() { }]; } +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Any commits to this file should be reviewed with security in mind. * + * Changes to this file can potentially create security vulnerabilities. * + * An approval from 2 Core members with history of modifying * + * this file is required. * + * * + * Does the change somehow allow for arbitrary javascript to be executed? * + * Or allows for someone to change the prototype of built-in objects? * + * Or gives undesired access to variables like document or window? * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE! * * DOM-related variables: @@ -5052,7 +7354,7 @@ function $TemplateCacheProvider() { /** * @ngdoc service * @name $compile - * @function + * @kind function * * @description * Compiles an HTML string or DOM into a template and produces a template function, which @@ -5072,8 +7374,9 @@ function $TemplateCacheProvider() { * There are many different options for a directive. * * The difference resides in the return value of the factory function. - * You can either return a "Directive Definition Object" (see below) that defines the directive properties, - * or just the `postLink` function (all other properties will have the default values). + * You can either return a {@link $compile#directive-definition-object Directive Definition Object (see below)} + * that defines the directive properties, or just the `postLink` function (all other properties will have + * the default values). * *
* **Best Practice:** It's recommended to use the "directive definition object" form. @@ -5086,32 +7389,34 @@ function $TemplateCacheProvider() { * * myModule.directive('directiveName', function factory(injectables) { * var directiveDefinitionObject = { - * priority: 0, - * template: '
', // or // function(tElement, tAttrs) { ... }, + * {@link $compile#-priority- priority}: 0, + * {@link $compile#-template- template}: '
', // or // function(tElement, tAttrs) { ... }, * // or - * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... }, - * replace: false, - * transclude: false, - * restrict: 'A', - * scope: false, - * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, - * controllerAs: 'stringAlias', - * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], - * compile: function compile(tElement, tAttrs, transclude) { + * // {@link $compile#-templateurl- templateUrl}: 'directive.html', // or // function(tElement, tAttrs) { ... }, + * {@link $compile#-transclude- transclude}: false, + * {@link $compile#-restrict- restrict}: 'A', + * {@link $compile#-templatenamespace- templateNamespace}: 'html', + * {@link $compile#-scope- scope}: false, + * {@link $compile#-controller- controller}: function($scope, $element, $attrs, $transclude, otherInjectables) { ... }, + * {@link $compile#-controlleras- controllerAs}: 'stringIdentifier', + * {@link $compile#-bindtocontroller- bindToController}: false, + * {@link $compile#-require- require}: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'], + * {@link $compile#-multielement- multiElement}: false, + * {@link $compile#-compile- compile}: function compile(tElement, tAttrs, transclude) { * return { - * pre: function preLink(scope, iElement, iAttrs, controller) { ... }, - * post: function postLink(scope, iElement, iAttrs, controller) { ... } + * {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... }, + * {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... } * } * // or * // return function postLink( ... ) { ... } * }, * // or - * // link: { - * // pre: function preLink(scope, iElement, iAttrs, controller) { ... }, - * // post: function postLink(scope, iElement, iAttrs, controller) { ... } + * // {@link $compile#-link- link}: { + * // {@link $compile#pre-linking-function pre}: function preLink(scope, iElement, iAttrs, controller) { ... }, + * // {@link $compile#post-linking-function post}: function postLink(scope, iElement, iAttrs, controller) { ... } * // } * // or - * // link: function postLink( ... ) { ... } + * // {@link $compile#-link- link}: function postLink( ... ) { ... } * }; * return directiveDefinitionObject; * }); @@ -5136,13 +7441,140 @@ function $TemplateCacheProvider() { * }); * ``` * + * ### Life-cycle hooks + * Directive controllers can provide the following methods that are called by AngularJS at points in the life-cycle of the + * directive: + * * `$onInit()` - Called on each controller after all the controllers on an element have been constructed and + * had their bindings initialized (and before the pre & post linking functions for the directives on + * this element). This is a good place to put initialization code for your controller. + * * `$onChanges(changesObj)` - Called whenever one-way (`<`) or interpolation (`@`) bindings are updated. The + * `changesObj` is a hash whose keys are the names of the bound properties that have changed, and the values are an + * object of the form `{ currentValue, previousValue, isFirstChange() }`. Use this hook to trigger updates within a + * component such as cloning the bound value to prevent accidental mutation of the outer value. Note that this will + * also be called when your bindings are initialized. + * * `$doCheck()` - Called on each turn of the digest cycle. Provides an opportunity to detect and act on + * changes. Any actions that you wish to take in response to the changes that you detect must be + * invoked from this hook; implementing this has no effect on when `$onChanges` is called. For example, this hook + * could be useful if you wish to perform a deep equality check, or to check a Date object, changes to which would not + * be detected by AngularJS's change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments; + * if detecting changes, you must store the previous value(s) for comparison to the current values. + * * `$onDestroy()` - Called on a controller when its containing scope is destroyed. Use this hook for releasing + * external resources, watches and event handlers. Note that components have their `$onDestroy()` hooks called in + * the same order as the `$scope.$broadcast` events are triggered, which is top down. This means that parent + * components will have their `$onDestroy()` hook called before child components. + * * `$postLink()` - Called after this controller's element and its children have been linked. Similar to the post-link + * function this hook can be used to set up DOM event handlers and do direct DOM manipulation. + * Note that child elements that contain `templateUrl` directives will not have been compiled and linked since + * they are waiting for their template to load asynchronously and their own compilation and linking has been + * suspended until that occurs. + * + * #### Comparison with life-cycle hooks in the new Angular + * The new Angular also uses life-cycle hooks for its components. While the AngularJS life-cycle hooks are similar there are + * some differences that you should be aware of, especially when it comes to moving your code from AngularJS to Angular: + * + * * AngularJS hooks are prefixed with `$`, such as `$onInit`. Angular hooks are prefixed with `ng`, such as `ngOnInit`. + * * AngularJS hooks can be defined on the controller prototype or added to the controller inside its constructor. + * In Angular you can only define hooks on the prototype of the Component class. + * * Due to the differences in change-detection, you may get many more calls to `$doCheck` in AngularJS than you would to + * `ngDoCheck` in Angular. + * * Changes to the model inside `$doCheck` will trigger new turns of the digest loop, which will cause the changes to be + * propagated throughout the application. + * Angular does not allow the `ngDoCheck` hook to trigger a change outside of the component. It will either throw an + * error or do nothing depending upon the state of `enableProdMode()`. + * + * #### Life-cycle hook examples + * + * This example shows how you can check for mutations to a Date object even though the identity of the object + * has not changed. + * + * + * + * angular.module('do-check-module', []) + * .component('app', { + * template: + * 'Month: ' + + * 'Date: {{ $ctrl.date }}' + + * '', + * controller: function() { + * this.date = new Date(); + * this.month = this.date.getMonth(); + * this.updateDate = function() { + * this.date.setMonth(this.month); + * }; + * } + * }) + * .component('test', { + * bindings: { date: '<' }, + * template: + * '
{{ $ctrl.log | json }}
', + * controller: function() { + * var previousValue; + * this.log = []; + * this.$doCheck = function() { + * var currentValue = this.date && this.date.valueOf(); + * if (previousValue !== currentValue) { + * this.log.push('doCheck: date mutated: ' + this.date); + * previousValue = currentValue; + * } + * }; + * } + * }); + *
+ * + * + * + *
* + * This example show how you might use `$doCheck` to trigger changes in your component's inputs even if the + * actual identity of the component doesn't change. (Be aware that cloning and deep equality checks on large + * arrays or objects can have a negative impact on your application performance.) * - * ### Directive Definition Object + * + * + *
+ * + * + *
{{ items }}
+ * + *
+ *
+ * + * angular.module('do-check-module', []) + * .component('test', { + * bindings: { items: '<' }, + * template: + * '
{{ $ctrl.log | json }}
', + * controller: function() { + * this.log = []; + * + * this.$doCheck = function() { + * if (this.items_ref !== this.items) { + * this.log.push('doCheck: items changed'); + * this.items_ref = this.items; + * } + * if (!angular.equals(this.items_clone, this.items)) { + * this.log.push('doCheck: items mutated'); + * this.items_clone = angular.copy(this.items); + * } + * }; + * } + * }); + *
+ *
+ * + * + * ### Directive Definition Object * * The directive definition object provides instructions to the {@link ng.$compile * compiler}. The attributes are: * + * #### `multiElement` + * When this property is set to true (default is `false`), the HTML compiler will collect DOM nodes between + * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them + * together as the directive elements. It is recommended that this feature be used on directives + * which are not strictly behavioral (such as {@link ngClick}), and which + * do not manipulate or replace child nodes (such as {@link ngInclude}). + * * #### `priority` * When there are multiple directives defined on a single DOM element, sometimes it * is necessary to specify the order in which the directives are applied. The `priority` is used @@ -5154,136 +7586,300 @@ function $TemplateCacheProvider() { * #### `terminal` * If set to true then the current `priority` will be the last set of directives * which will execute (any directives at the current priority will still execute - * as the order of execution on same `priority` is undefined). + * as the order of execution on same `priority` is undefined). Note that expressions + * and other directives used in the directive's template will also be excluded from execution. * * #### `scope` - * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the - * same element request a new scope, only one new scope is created. The new scope rule does not - * apply for the root of the template since the root of the template always gets a new scope. + * The scope property can be `false`, `true`, or an object: + * + * * **`false` (default):** No scope will be created for the directive. The directive will use its + * parent's scope. * - * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from - * normal scope in that it does not prototypically inherit from the parent scope. This is useful - * when creating reusable components, which should not accidentally read or modify data in the - * parent scope. + * * **`true`:** A new child scope that prototypically inherits from its parent will be created for + * the directive's element. If multiple directives on the same element request a new scope, + * only one new scope is created. * - * The 'isolate' scope takes an object hash which defines a set of local scope properties - * derived from the parent scope. These local properties are useful for aliasing values for - * templates. Locals definition is a hash of local scope property to its source: + * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's template. + * The 'isolate' scope differs from normal scope in that it does not prototypically + * inherit from its parent scope. This is useful when creating reusable components, which should not + * accidentally read or modify data in the parent scope. Note that an isolate scope + * directive without a `template` or `templateUrl` will not apply the isolate scope + * to its children elements. + * + * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the + * directive's element. These local properties are useful for aliasing values for templates. The keys in + * the object hash map to the name of the property on the isolate scope; the values define how the property + * is bound to the parent scope, via matching attributes on the directive's element: * * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is - * always a string since DOM attributes are strings. If no `attr` name is specified then the - * attribute name is assumed to be the same as the local name. - * Given `` and widget definition - * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect - * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the - * `localName` property on the widget scope. The `name` is read from the parent scope (not - * component scope). - * - * * `=` or `=attr` - set up bi-directional binding between a local scope property and the - * parent scope property of name defined via the value of the `attr` attribute. If no `attr` - * name is specified then the attribute name is assumed to be the same as the local name. - * Given `` and widget definition of - * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the + * always a string since DOM attributes are strings. If no `attr` name is specified then the + * attribute name is assumed to be the same as the local name. Given `` and the isolate scope definition `scope: { localName:'@myAttr' }`, + * the directive's scope property `localName` will reflect the interpolated value of `hello + * {{name}}`. As the `name` attribute changes so will the `localName` property on the directive's + * scope. The `name` is read from the parent scope (not the directive's scope). + * + * * `=` or `=attr` - set up a bidirectional binding between a local scope property and an expression + * passed via the attribute `attr`. The expression is evaluated in the context of the parent scope. + * If no `attr` name is specified then the attribute name is assumed to be the same as the local + * name. Given `` and the isolate scope definition `scope: { + * localModel: '=myAttr' }`, the property `localModel` on the directive's scope will reflect the + * value of `parentModel` on the parent scope. Changes to `parentModel` will be reflected in + * `localModel` and vice versa. If the binding expression is non-assignable, or if the attribute + * isn't optional and doesn't exist, an exception + * ({@link error/$compile/nonassign `$compile:nonassign`}) will be thrown upon discovering changes + * to the local value, since it will be impossible to sync them back to the parent scope. + * + * By default, the {@link ng.$rootScope.Scope#$watch `$watch`} + * method is used for tracking changes, and the equality check is based on object identity. + * However, if an object literal or an array literal is passed as the binding expression, the + * equality check is done by value (using the {@link angular.equals} function). It's also possible + * to watch the evaluated value shallowly with {@link ng.$rootScope.Scope#$watchCollection + * `$watchCollection`}: use `=*` or `=*attr` + * + * * `<` or `` and directive definition of + * `scope: { localModel:'` and the isolate scope definition `scope: { + * localFn:'&myAttr' }`, the isolate scope property `localFn` will point to a function wrapper for + * the `count = count + value` expression. Often it's desirable to pass data from the isolated scope + * via an expression to the parent scope. This can be done by passing a map of local variable names + * and values into the expression wrapper fn. For example, if the expression is `increment(amount)` + * then we can specify the amount value by calling the `localFn` as `localFn({amount: 22})`. + * + * All 4 kinds of bindings (`@`, `=`, `<`, and `&`) can be made optional by adding `?` to the expression. + * The marker must come after the mode and before the attribute name. + * See the {@link error/$compile/iscp Invalid Isolate Scope Definition error} for definition examples. + * This is useful to refine the interface directives provide. + * One subtle difference between optional and non-optional happens **when the binding attribute is not + * set**: + * - the binding is optional: the property will not be defined + * - the binding is not optional: the property is defined + * + * ```js + *app.directive('testDir', function() { + return { + scope: { + notoptional: '=', + optional: '=?', + }, + bindToController: true, + controller: function() { + this.$onInit = function() { + console.log(this.hasOwnProperty('notoptional')) // true + console.log(this.hasOwnProperty('optional')) // false + } + } + } + }) + *``` + * + * + * ##### Combining directives with different scope defintions + * + * In general it's possible to apply more than one directive to one element, but there might be limitations + * depending on the type of scope required by the directives. The following points will help explain these limitations. + * For simplicity only two directives are taken into account, but it is also applicable for several directives: + * + * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope + * * **child scope** + **no scope** => Both directives will share one single child scope + * * **child scope** + **child scope** => Both directives will share one single child scope + * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use + * its parent's scope + * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot + * be applied to the same element. + * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives + * cannot be applied to the same element. + * * - * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope. - * If no `attr` name is specified then the attribute name is assumed to be the same as the - * local name. Given `` and widget definition of - * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to - * a function wrapper for the `count = count + value` expression. Often it's desirable to - * pass data from the isolated scope via an expression and to the parent scope, this can be - * done by passing a map of local variable names and values into the expression wrapper fn. - * For example, if the expression is `increment(amount)` then we can specify the amount value - * by calling the `localFn` as `localFn({amount: 22})`. + * #### `bindToController` + * This property is used to bind scope properties directly to the controller. It can be either + * `true` or an object hash with the same format as the `scope` property. * + * When an isolate scope is used for a directive (see above), `bindToController: true` will + * allow a component to have its properties bound to the controller, rather than to scope. + * + * After the controller is instantiated, the initial values of the isolate scope bindings will be bound to the controller + * properties. You can access these bindings once they have been initialized by providing a controller method called + * `$onInit`, which is called after all the controllers on an element have been constructed and had their bindings + * initialized. + * + * It is also possible to set `bindToController` to an object hash with the same format as the `scope` property. + * This will set up the scope bindings to the controller directly. Note that `scope` can still be used + * to define which kind of scope is created. By default, no scope is created. Use `scope: {}` to create an isolate + * scope (useful for component directives). + * + * If both `bindToController` and `scope` are defined and have object hashes, `bindToController` overrides `scope`. * * * #### `controller` * Controller constructor function. The controller is instantiated before the - * pre-linking phase and it is shared with other directives (see + * pre-linking phase and can be accessed by other directives (see * `require` attribute). This allows the directives to communicate with each other and augment * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals: * * * `$scope` - Current scope associated with the element * * `$element` - Current element * * `$attrs` - Current attributes object for the element - * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope. - * The scope can be overridden by an optional first argument. - * `function([scope], cloneLinkingFn)`. - * + * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope: + * `function([scope], cloneLinkingFn, futureParentElement, slotName)`: + * * `scope`: (optional) override the scope. + * * `cloneLinkingFn`: (optional) argument to create clones of the original transcluded content. + * * `futureParentElement` (optional): + * * defines the parent to which the `cloneLinkingFn` will add the cloned elements. + * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`. + * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements) + * and when the `cloneLinkingFn` is passed, + * as those elements need to created and cloned in a special way when they are defined outside their + * usual containers (e.g. like ``). + * * See also the `directive.templateNamespace` property. + * * `slotName`: (optional) the name of the slot to transclude. If falsy (e.g. `null`, `undefined` or `''`) + * then the default transclusion is provided. + * The `$transclude` function also has a method on it, `$transclude.isSlotFilled(slotName)`, which returns + * `true` if the specified slot contains content (i.e. one or more DOM nodes). * * #### `require` * Require another directive and inject its controller as the fourth argument to the linking function. The - * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the - * injected argument will be an array in corresponding order. If no such directive can be - * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with: + * `require` property can be a string, an array or an object: + * * a **string** containing the name of the directive to pass to the linking function + * * an **array** containing the names of directives to pass to the linking function. The argument passed to the + * linking function will be an array of controllers in the same order as the names in the `require` property + * * an **object** whose property values are the names of the directives to pass to the linking function. The argument + * passed to the linking function will also be an object with matching keys, whose values will hold the corresponding + * controllers. + * + * If the `require` property is an object and `bindToController` is truthy, then the required controllers are + * bound to the controller using the keys of the `require` property. This binding occurs after all the controllers + * have been constructed but before `$onInit` is called. + * If the name of the required controller is the same as the local name (the key), the name can be + * omitted. For example, `{parentDir: '^^'}` is equivalent to `{parentDir: '^^parentDir'}`. + * See the {@link $compileProvider#component} helper for an example of how this can be used. + * If no such required directive(s) can be found, or if the directive does not have a controller, then an error is + * raised (unless no link function is specified and the required controllers are not being bound to the directive + * controller, in which case error checking is skipped). The name can be prefixed with: * * * (no prefix) - Locate the required controller on the current element. Throw an error if not found. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found. - * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found. - * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the - * `link` fn if not found. + * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found. + * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found. + * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass + * `null` to the `link` fn if not found. + * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass + * `null` to the `link` fn if not found. * * * #### `controllerAs` - * Controller alias at the directive scope. An alias for the controller so it - * can be referenced at the directive template. The directive needs to define a scope for this - * configuration to be used. Useful in the case when directive is used as component. + * Identifier name for a reference to the controller in the directive's scope. + * This allows the controller to be referenced from the directive template. This is especially + * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible + * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the + * `controllerAs` reference might overwrite a property that already exists on the parent scope. * * * #### `restrict` * String of subset of `EACM` which restricts the directive to a specific directive - * declaration style. If omitted, the default (attributes only) is used. + * declaration style. If omitted, the defaults (elements and attributes) are used. * - * * `E` - Element name: `` + * * `E` - Element name (default): `` * * `A` - Attribute (default): `
` * * `C` - Class: `
` * * `M` - Comment: `` * * + * #### `templateNamespace` + * String representing the document type used by the markup in the template. + * AngularJS needs this information as those elements need to be created and cloned + * in a special way when they are defined outside their usual containers like `` and ``. + * + * * `html` - All root nodes in the template are HTML. Root nodes may also be + * top-level elements such as `` or ``. + * * `svg` - The root nodes in the template are SVG elements (excluding ``). + * * `math` - The root nodes in the template are MathML elements (excluding ``). + * + * If no `templateNamespace` is specified, then the namespace is considered to be `html`. + * * #### `template` - * replace the current element with the contents of the HTML. The replacement process - * migrates all of the attributes / classes from the old element to the new one. See the - * {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive - * Directives Guide} for an example. + * HTML markup that may: + * * Replace the contents of the directive's element (default). + * * Replace the directive's element itself (if `replace` is true - DEPRECATED). + * * Wrap the contents of the directive's element (if `transclude` is true). * - * You can specify `template` as a string representing the template or as a function which takes - * two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and - * returns a string value representing the template. + * Value may be: + * + * * A string. For example `
{{delete_str}}
`. + * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile` + * function api below) and returns a string value. * * * #### `templateUrl` - * Same as `template` but the template is loaded from the specified URL. Because - * the template loading is asynchronous the compilation/linking is suspended until the template - * is loaded. + * This is similar to `template` but the template is loaded from the specified URL, asynchronously. + * + * Because template loading is asynchronous the compiler will suspend compilation of directives on that element + * for later when the template has been resolved. In the meantime it will continue to compile and link + * sibling and parent elements as though this element had not contained any directives. + * + * The compiler does not suspend the entire compilation to wait for templates to be loaded because this + * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the + * case when only one deeply nested directive has `templateUrl`. + * + * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}. * * You can specify `templateUrl` as a string representing the URL or as a function which takes two * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns * a string value representing the url. In either case, the template URL is passed through {@link - * api/ng.$sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}. + * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}. * * * #### `replace` - * specify where the template should be inserted. Defaults to `false`. + *
+ * **Note:** `replace` is deprecated in AngularJS and has been removed in the new Angular (v2+). + *
* - * * `true` - the template will replace the current element. - * * `false` - the template will replace the contents of the current element. + * Specifies what the template should replace. Defaults to `false`. * + * * `true` - the template will replace the directive's element. + * * `false` - the template will replace the contents of the directive's element. * - * #### `transclude` - * compile the content of the element and make it available to the directive. - * Typically used with {@link ng.directive:ngTransclude - * ngTransclude}. The advantage of transclusion is that the linking function receives a - * transclusion function which is pre-bound to the correct scope. In a typical setup the widget - * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate` - * scope. This makes it possible for the widget to have private state, and the transclusion to - * be bound to the parent (pre-`isolate`) scope. + * The replacement process migrates all of the attributes / classes from the old element to the new + * one. See the {@link guide/directive#template-expanding-directive + * Directives Guide} for an example. + * + * There are very few scenarios where element replacement is required for the application function, + * the main one being reusable custom components that are used within SVG contexts + * (because SVG doesn't work with custom elements in the DOM tree). * - * * `true` - transclude the content of the directive. - * * `'element'` - transclude the whole element including any directives defined at lower priority. + * #### `transclude` + * Extract the contents of the element where the directive appears and make it available to the directive. + * The contents are compiled and provided to the directive as a **transclusion function**. See the + * {@link $compile#transclusion Transclusion} section below. * * * #### `compile` @@ -5293,11 +7889,7 @@ function $TemplateCacheProvider() { * ``` * * The compile function deals with transforming the template DOM. Since most directives do not do - * template transformation, it is not used often. Examples that require compile functions are - * directives that transform template DOM, such as {@link - * api/ng.directive:ngRepeat ngRepeat}, or load the contents - * asynchronously, such as {@link ngRoute.directive:ngView ngView}. The - * compile function takes the following arguments. + * template transformation, it is not used often. The compile function takes the following arguments: * * * `tElement` - template element - The element where the directive has been declared. It is * safe to do template transformation on the element and child elements only. @@ -5316,15 +7908,15 @@ function $TemplateCacheProvider() { *
* **Note:** The compile function cannot handle directives that recursively use themselves in their - * own templates or compile functions. Compiling these directives results in an infinite loop and a + * own templates or compile functions. Compiling these directives results in an infinite loop and * stack overflow errors. * - * This can be avoided by manually using $compile in the postLink function to imperatively compile + * This can be avoided by manually using `$compile` in the postLink function to imperatively compile * a directive's template instead of relying on automatic template compilation via `template` or * `templateUrl` declaration or manual compilation inside the compile function. *
* - *
+ *
* **Note:** The `transclude` function that is passed to the compile function is deprecated, as it * e.g. does not know about the right outer scope. Please use the transclude function that is passed * to the link function instead. @@ -5361,15 +7953,23 @@ function $TemplateCacheProvider() { * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared * between all directive linking functions. * - * * `controller` - a controller instance - A controller instance if at least one directive on the - * element defines a controller. The controller is shared among all the directives, which allows - * the directives to use the controllers as a communication channel. + * * `controller` - the directive's required controller instance(s) - Instances are shared + * among all directives, which allows the directives to use the controllers as a communication + * channel. The exact value depends on the directive's `require` property: + * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one + * * `string`: the controller instance + * * `array`: array of controller instances * - * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. - * The scope can be overridden by an optional first argument. This is the same as the `$transclude` - * parameter of directive controllers. - * `function([scope], cloneLinkingFn)`. + * If a required controller cannot be found, and it is optional, the instance is `null`, + * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown. * + * Note that you can also require the directive's own controller - it will be made available like + * any other controller. + * + * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope. + * This is the same as the `$transclude` parameter of directive controllers, + * see {@link ng.$compile#-controller- the controller section for details}. + * `function([scope], cloneLinkingFn, futureParentElement)`. * * #### Pre-linking function * @@ -5378,18 +7978,166 @@ function $TemplateCacheProvider() { * * #### Post-linking function * - * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function. + * Executed after the child elements are linked. + * + * Note that child elements that contain `templateUrl` directives will not have been compiled + * and linked since they are waiting for their template to load asynchronously and their own + * compilation and linking has been suspended until that occurs. + * + * It is safe to do DOM transformation in the post-linking function on elements that are not waiting + * for their async templates to be resolved. + * + * + * ### Transclusion + * + * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and + * copying them to another part of the DOM, while maintaining their connection to the original AngularJS + * scope from where they were taken. + * + * Transclusion is used (often with {@link ngTransclude}) to insert the + * original contents of a directive's element into a specified place in the template of the directive. + * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded + * content has access to the properties on the scope from which it was taken, even if the directive + * has isolated scope. + * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}. + * + * This makes it possible for the widget to have private state for its template, while the transcluded + * content has access to its originating scope. + * + *
+ * **Note:** When testing an element transclude directive you must not place the directive at the root of the + * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives + * Testing Transclusion Directives}. + *
+ * + * There are three kinds of transclusion depending upon whether you want to transclude just the contents of the + * directive's element, the entire element or multiple parts of the element contents: + * + * * `true` - transclude the content (i.e. the child nodes) of the directive's element. + * * `'element'` - transclude the whole of the directive's element including any directives on this + * element that are defined at a lower priority than this directive. When used, the `template` + * property is ignored. + * * **`{...}` (an object hash):** - map elements of the content onto transclusion "slots" in the template. + * + * **Multi-slot transclusion** is declared by providing an object for the `transclude` property. + * + * This object is a map where the keys are the name of the slot to fill and the value is an element selector + * used to match the HTML to the slot. The element selector should be in normalized form (e.g. `myElement`) + * and will match the standard element variants (e.g. `my-element`, `my:element`, `data-my-element`, etc). + * + * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}. + * + * If the element selector is prefixed with a `?` then that slot is optional. + * + * For example, the transclude object `{ slotA: '?myCustomElement' }` maps `` elements to + * the `slotA` slot, which can be accessed via the `$transclude` function or via the {@link ngTransclude} directive. + * + * Slots that are not marked as optional (`?`) will trigger a compile time error if there are no matching elements + * in the transclude content. If you wish to know if an optional slot was filled with content, then you can call + * `$transclude.isSlotFilled(slotName)` on the transclude function passed to the directive's link function and + * injectable into the directive's controller. + * + * + * #### Transclusion Functions + * + * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion + * function** to the directive's `link` function and `controller`. This transclusion function is a special + * **linking function** that will return the compiled contents linked to a new transclusion scope. + * + *
+ * If you are just using {@link ngTransclude} then you don't need to worry about this function, since + * ngTransclude will deal with it for us. + *
+ * + * If you want to manually control the insertion and removal of the transcluded content in your directive + * then you must use this transclude function. When you call a transclude function it returns a jqLite/JQuery + * object that contains the compiled DOM, which is linked to the correct transclusion scope. + * + * When you call a transclusion function you can pass in a **clone attach function**. This function accepts + * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded + * content and the `scope` is the newly created transclusion scope, which the clone will be linked to. + * + *
+ * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a transclude function + * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope. + *
+ * + * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone + * attach function**: + * + * ```js + * var transcludedContent, transclusionScope; + * + * $transclude(function(clone, scope) { + * element.append(clone); + * transcludedContent = clone; + * transclusionScope = scope; + * }); + * ``` + * + * Later, if you want to remove the transcluded content from your DOM then you should also destroy the + * associated transclusion scope: + * + * ```js + * transcludedContent.remove(); + * transclusionScope.$destroy(); + * ``` + * + *
+ * **Best Practice**: if you intend to add and remove transcluded content manually in your directive + * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it), + * then you are also responsible for calling `$destroy` on the transclusion scope. + *
+ * + * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat} + * automatically destroy their transcluded clones as necessary so you do not need to worry about this if + * you are simply using {@link ngTransclude} to inject the transclusion into your directive. + * + * + * #### Transclusion Scopes + * + * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion + * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed + * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it + * was taken. + * + * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look + * like this: + * + * ```html + *
+ *
+ *
+ *
+ *
+ *
+ * ``` + * + * The `$parent` scope hierarchy will look like this: + * + ``` + - $rootScope + - isolate + - transclusion + ``` + * + * but the scopes will inherit prototypically from different scopes to their `$parent`. + * + ``` + - $rootScope + - transclusion + - isolate + ``` + * * - * * ### Attributes * * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the * `link()` or `compile()` functions. It has a variety of uses. * - * accessing *Normalized attribute names:* - * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'. - * the attributes object allows for normalized access to - * the attributes. + * * *Accessing normalized attribute names:* Directives like `ngBind` can be expressed in many ways: + * `ng:bind`, `data-ng-bind`, or `x-ng-bind`. The attributes object allows for normalized access + * to the attributes. * * * *Directive inter-communication:* All directives share the same instance of the attributes * object which allows the directives to use the attributes object as inter directive @@ -5418,51 +8166,49 @@ function $TemplateCacheProvider() { * } * ``` * - * Below is an example using `$compileProvider`. + * ## Example * *
* **Note**: Typically directives are registered with `module.directive`. The example below is * to illustrate how `$compile` works. *
* - + -
-
-
+
+
+
@@ -5470,11 +8216,11 @@ function $TemplateCacheProvider() { it('should auto compile', function() { var textarea = $('textarea'); var output = $('div[compile]'); - // The initial state reads 'Hello Angular'. - expect(output.getText()).toBe('Hello Angular'); + // The initial state reads 'Hello AngularJS'. + expect(output.getText()).toBe('Hello AngularJS'); textarea.clear(); textarea.sendKeys('{{name}}!'); - expect(output.getText()).toBe('Angular!'); + expect(output.getText()).toBe('AngularJS!'); }); @@ -5482,94 +8228,614 @@ function $TemplateCacheProvider() { * * * @param {string|DOMElement} element Element or HTML string to compile into a template function. - * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives. + * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED. + * + *
+ * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it + * e.g. will not use the right outer scope. Please pass the transclude function as a + * `parentBoundTranscludeFn` to the link function instead. + *
+ * * @param {number} maxPriority only apply directives lower than given priority (Only effects the * root element(s), not their children) - * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template + * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template * (a DOM element/tree) to a scope. Where: * * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the * `template` and call the `cloneAttachFn` function allowing the caller to attach the * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is - * called as:
`cloneAttachFn(clonedElement, scope)` where: + * called as:
`cloneAttachFn(clonedElement, scope)` where: * * * `clonedElement` - is a clone of the original `element` passed into the compiler. * * `scope` - is the current scope with which the linking function is working with. * + * * `options` - An optional object hash with linking options. If `options` is provided, then the following + * keys may be used to control linking behavior: + * + * * `parentBoundTranscludeFn` - the transclude function made available to + * directives; if given, it will be passed through to the link functions of + * directives found in `element` during compilation. + * * `transcludeControllers` - an object hash with keys that map controller names + * to a hash with the key `instance`, which maps to the controller instance; + * if given, it will make the controllers available to directives on the compileNode: + * ``` + * { + * parent: { + * instance: parentControllerInstance + * } + * } + * ``` + * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add + * the cloned elements; only needed for transcludes that are allowed to contain non HTML + * elements (e.g. SVG elements). See also the `directive.controller` property. + * * Calling the linking function returns the element of the template. It is either the original * element passed in, or the clone of the element if the `cloneAttachFn` is provided. * - * After linking the view is not updated until after a call to $digest which typically is done by - * Angular automatically. + * After linking the view is not updated until after a call to `$digest`, which typically is done by + * AngularJS automatically. * * If you need access to the bound view, there are two ways to do it: * * - If you are not asking the linking function to clone the template, create the DOM element(s) * before you send them to the compiler and keep this reference around. * ```js - * var element = $compile('

{{total}}

')(scope); + * var element = angular.element('

{{total}}

'); + * $compile(element)(scope); * ``` * * - if on the other hand, you need the element to be cloned, the view reference from the original * example would not point to the clone, but rather to the original template that was cloned. In - * this case, you can access the clone via the cloneAttachFn: + * this case, you can access the clone either via the `cloneAttachFn` or the value returned by the + * linking function: * ```js - * var templateElement = angular.element('

{{total}}

'), - * scope = ....; - * + * var templateElement = angular.element('

{{total}}

'); * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) { - * //attach the clone to DOM document at the right place + * // Attach the clone to DOM document at the right place. * }); * - * //now we have reference to the cloned DOM via `clonedElement` + * // Now we have reference to the cloned DOM via `clonedElement`. + * // NOTE: The `clonedElement` returned by the linking function is the same as the + * // `clonedElement` passed to `cloneAttachFn`. * ``` * * * For information on how the compiler works, see the - * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide. + * {@link guide/compiler AngularJS HTML Compiler} section of the Developer Guide. + * + * @knownIssue + * + * ### Double Compilation + * + Double compilation occurs when an already compiled part of the DOM gets + compiled again. This is an undesired effect and can lead to misbehaving directives, performance issues, + and memory leaks. Refer to the Compiler Guide {@link guide/compiler#double-compilation-and-how-to-avoid-it + section on double compilation} for an in-depth explanation and ways to avoid it. + + * @knownIssue + + ### Issues with `replace: true` + * + *
+ * **Note**: {@link $compile#-replace- `replace: true`} is deprecated and not recommended to use, + * mainly due to the issues listed here. It has been completely removed in the new Angular. + *
+ * + * #### Attribute values are not merged + * + * When a `replace` directive encounters the same attribute on the original and the replace node, + * it will simply deduplicate the attribute and join the values with a space or with a `;` in case of + * the `style` attribute. + * ```html + * Original Node: + * Replace Template: + * Result: + * ``` + * + * That means attributes that contain AngularJS expressions will not be merged correctly, e.g. + * {@link ngShow} or {@link ngClass} will cause a {@link $parse} error: + * + * ```html + * Original Node: + * Replace Template: + * Result: + * ``` + * + * See issue [#5695](https://github.com/angular/angular.js/issues/5695). + * + * #### Directives are not deduplicated before compilation + * + * When the original node and the replace template declare the same directive(s), they will be + * {@link guide/compiler#double-compilation-and-how-to-avoid-it compiled twice} because the compiler + * does not deduplicate them. In many cases, this is not noticeable, but e.g. {@link ngModel} will + * attach `$formatters` and `$parsers` twice. + * + * See issue [#2573](https://github.com/angular/angular.js/issues/2573). + * + * #### `transclude: element` in the replace template root can have unexpected effects + * + * When the replace template has a directive at the root node that uses + * {@link $compile#-transclude- `transclude: element`}, e.g. + * {@link ngIf} or {@link ngRepeat}, the DOM structure or scope inheritance can be incorrect. + * See the following issues: + * + * - Incorrect scope on replaced element: + * [#9837](https://github.com/angular/angular.js/issues/9837) + * - Different DOM between `template` and `templateUrl`: + * [#10612](https://github.com/angular/angular.js/issues/14326) + * + */ + +/** + * @ngdoc directive + * @name ngProp + * @restrict A + * @element ANY + * + * @usage + * + * ```html + * + * + * ``` + * + * or with uppercase letters in property (e.g. "propName"): + * + * + * ```html + * + * + * ``` + * + * + * @description + * The `ngProp` directive binds an expression to a DOM element property. + * `ngProp` allows writing to arbitrary properties by including + * the property name in the attribute, e.g. `ng-prop-value="'my value'"` binds 'my value' to + * the `value` property. + * + * Usually, it's not necessary to write to properties in AngularJS, as the built-in directives + * handle the most common use cases (instead of the above example, you would use {@link ngValue}). + * + * However, [custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements) + * often use custom properties to hold data, and `ngProp` can be used to provide input to these + * custom elements. + * + * ## Binding to camelCase properties + * + * Since HTML attributes are case-insensitive, camelCase properties like `innerHTML` must be escaped. + * AngularJS uses the underscore (_) in front of a character to indicate that it is uppercase, so + * `innerHTML` must be written as `ng-prop-inner_h_t_m_l="expression"` (Note that this is just an + * example, and for binding HTML {@link ngBindHtml} should be used. + * + * ## Security + * + * Binding expressions to arbitrary properties poses a security risk, as properties like `innerHTML` + * can insert potentially dangerous HTML into the application, e.g. script tags that execute + * malicious code. + * For this reason, `ngProp` applies Strict Contextual Escaping with the {@link ng.$sce $sce service}. + * This means vulnerable properties require their content to be "trusted", based on the + * context of the property. For example, the `innerHTML` is in the `HTML` context, and the + * `iframe.src` property is in the `RESOURCE_URL` context, which requires that values written to + * this property are trusted as a `RESOURCE_URL`. + * + * This can be set explicitly by calling $sce.trustAs(type, value) on the value that is + * trusted before passing it to the `ng-prop-*` directive. There are exist shorthand methods for + * each context type in the form of {@link ng.$sce#trustAsResourceUrl $sce.trustAsResourceUrl()} et al. + * + * In some cases you can also rely upon automatic sanitization of untrusted values - see below. + * + * Based on the context, other options may exist to mark a value as trusted / configure the behavior + * of {@link ng.$sce}. For example, to restrict the `RESOURCE_URL` context to specific origins, use + * the {@link $sceDelegateProvider#trustedResourceUrlList trustedResourceUrlList()} + * and {@link $sceDelegateProvider#bannedResourceUrlList bannedResourceUrlList()}. + * + * {@link ng.$sce#what-trusted-context-types-are-supported- Find out more about the different context types}. + * + * ### HTML Sanitization + * + * By default, `$sce` will throw an error if it detects untrusted HTML content, and will not bind the + * content. + * However, if you include the {@link ngSanitize ngSanitize module}, it will try to sanitize the + * potentially dangerous HTML, e.g. strip non-trusted tags and attributes when binding to + * `innerHTML`. + * + * @example + * ### Binding to different contexts + * + * + * + * angular.module('exampleNgProp', []) + * .component('main', { + * templateUrl: 'main.html', + * controller: function($sce) { + * this.safeContent = 'Safe content'; + * this.unsafeContent = ''; + * this.trustedUnsafeContent = $sce.trustAsHtml(this.unsafeContent); + * } + * }); + * + * + *
+ *
+ * Binding to a property without security context: + *
+ * innerText (safeContent) + *
+ * + *
+ * "Safe" content that requires a security context will throw because the contents could potentially be dangerous ... + *
+ * innerHTML (safeContent) + *
+ * + *
+ * ... so that actually dangerous content cannot be executed: + *
+ * innerHTML (unsafeContent) + *
+ * + *
+ * ... but unsafe Content that has been trusted explicitly works - only do this if you are 100% sure! + *
+ * innerHTML (trustedUnsafeContent) + *
+ *
+ *
+ * + *
+ *
+ * + * .prop-unit { + * margin-bottom: 10px; + * } + * + * .prop-binding { + * min-height: 30px; + * border: 1px solid blue; + * } + * + * .prop-note { + * font-family: Monospace; + * } + * + *
+ * + * + * @example + * ### Binding to innerHTML with ngSanitize + * + * + * + * angular.module('exampleNgProp', ['ngSanitize']) + * .component('main', { + * templateUrl: 'main.html', + * controller: function($sce) { + * this.safeContent = 'Safe content'; + * this.unsafeContent = ''; + * this.trustedUnsafeContent = $sce.trustAsHtml(this.unsafeContent); + * } + * }); + * + * + *
+ *
+ * "Safe" content will be sanitized ... + *
+ * innerHTML (safeContent) + *
+ * + *
+ * ... as will dangerous content: + *
+ * innerHTML (unsafeContent) + *
+ * + *
+ * ... and content that has been trusted explicitly works the same as without ngSanitize: + *
+ * innerHTML (trustedUnsafeContent) + *
+ *
+ *
+ * + *
+ *
+ * + * .prop-unit { + * margin-bottom: 10px; + * } + * + * .prop-binding { + * min-height: 30px; + * border: 1px solid blue; + * } + * + * .prop-note { + * font-family: Monospace; + * } + * + *
+ * + */ + +/** @ngdoc directive + * @name ngOn + * @restrict A + * @element ANY + * + * @usage + * + * ```html + * + * + * ``` + * + * or with uppercase letters in property (e.g. "eventName"): + * + * + * ```html + * + * + * ``` + * + * @description + * The `ngOn` directive adds an event listener to a DOM element via + * {@link angular.element angular.element().on()}, and evaluates an expression when the event is + * fired. + * `ngOn` allows adding listeners for arbitrary events by including + * the event name in the attribute, e.g. `ng-on-drop="onDrop()"` executes the 'onDrop()' expression + * when the `drop` event is fired. + * + * AngularJS provides specific directives for many events, such as {@link ngClick}, so in most + * cases it is not necessary to use `ngOn`. However, AngularJS does not support all events + * (e.g. the `drop` event in the example above), and new events might be introduced in later DOM + * standards. + * + * Another use-case for `ngOn` is listening to + * [custom events](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events) + * fired by + * [custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements). + * + * ## Binding to camelCase properties + * + * Since HTML attributes are case-insensitive, camelCase properties like `myEvent` must be escaped. + * AngularJS uses the underscore (_) in front of a character to indicate that it is uppercase, so + * `myEvent` must be written as `ng-on-my_event="expression"`. + * + * @example + * ### Bind to built-in DOM events + * + * + * + * angular.module('exampleNgOn', []) + * .component('main', { + * templateUrl: 'main.html', + * controller: function() { + * this.clickCount = 0; + * this.mouseoverCount = 0; + * + * this.loadingState = 0; + * } + * }); + * + * + *
+ * This is equivalent to `ngClick` and `ngMouseover`:
+ *
+ * clickCount: {{$ctrl.clickCount}}
+ * mouseover: {{$ctrl.mouseoverCount}} + * + *
+ * + * For the `error` and `load` event on images no built-in AngularJS directives exist:
+ *
+ *
+ * Image is loading + * Image load error + * Image loaded successfully + *
+ *
+ *
+ * + *
+ *
+ *
+ * + * + * @example + * ### Bind to custom DOM events + * + * + * + * angular.module('exampleNgOn', []) + * .component('main', { + * templateUrl: 'main.html', + * controller: function() { + * this.eventLog = ''; + * + * this.listener = function($event) { + * this.eventLog = 'Event with type "' + $event.type + '" fired at ' + $event.detail; + * }; + * } + * }) + * .component('childComponent', { + * templateUrl: 'child.html', + * controller: function($element) { + * this.fireEvent = function() { + * var event = new CustomEvent('customtype', { detail: new Date()}); + * + * $element[0].dispatchEvent(event); + * }; + * } + * }); + * + * + *
+ * Event log: {{$ctrl.eventLog}} + *
+ * + + * + * + *
+ *
+ *
*/ var $compileMinErr = minErr('$compile'); +function UNINITIALIZED_VALUE() {} +var _UNINITIALIZED_VALUE = new UNINITIALIZED_VALUE(); + /** * @ngdoc provider * @name $compileProvider - * @function * * @description */ $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; +/** @this */ function $CompileProvider($provide, $$sanitizeUriProvider) { var hasDirectives = {}, Suffix = 'Directive', - COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/, - CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/; + COMMENT_DIRECTIVE_REGEXP = /^\s*directive:\s*([\w-]+)\s+(.*)$/, + CLASS_DIRECTIVE_REGEXP = /(([\w-]+)(?::([^;]+))?;?)/, + ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'), + REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/; // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes // The assumption is that future DOM event attribute names will begin with // 'on' and be composed of only English letters. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/; + var bindingCache = createMap(); - /** - * @ngdoc method - * @name $compileProvider#directive - * @function - * - * @description - * Register a new directive with the compiler. - * - * @param {string|Object} name Name of the directive in camel-case (i.e. ngBind which - * will match as ng-bind), or an object map of directives where the keys are the - * names and the values are the factories. - * @param {Function|Array} directiveFactory An injectable directive factory function. See - * {@link guide/directive} for more info. - * @returns {ng.$compileProvider} Self for chaining. - */ - this.directive = function registerDirective(name, directiveFactory) { - assertNotHasOwnProperty(name, 'directive'); - if (isString(name)) { - assertArg(directiveFactory, 'directiveFactory'); + function parseIsolateBindings(scope, directiveName, isController) { + var LOCAL_REGEXP = /^([@&]|[=<](\*?))(\??)\s*([\w$]*)$/; + + var bindings = createMap(); + + forEach(scope, function(definition, scopeName) { + definition = definition.trim(); + + if (definition in bindingCache) { + bindings[scopeName] = bindingCache[definition]; + return; + } + var match = definition.match(LOCAL_REGEXP); + + if (!match) { + throw $compileMinErr('iscp', + 'Invalid {3} for directive \'{0}\'.' + + ' Definition: {... {1}: \'{2}\' ...}', + directiveName, scopeName, definition, + (isController ? 'controller bindings definition' : + 'isolate scope definition')); + } + + bindings[scopeName] = { + mode: match[1][0], + collection: match[2] === '*', + optional: match[3] === '?', + attrName: match[4] || scopeName + }; + if (match[4]) { + bindingCache[definition] = bindings[scopeName]; + } + }); + + return bindings; + } + + function parseDirectiveBindings(directive, directiveName) { + var bindings = { + isolateScope: null, + bindToController: null + }; + if (isObject(directive.scope)) { + if (directive.bindToController === true) { + bindings.bindToController = parseIsolateBindings(directive.scope, + directiveName, true); + bindings.isolateScope = {}; + } else { + bindings.isolateScope = parseIsolateBindings(directive.scope, + directiveName, false); + } + } + if (isObject(directive.bindToController)) { + bindings.bindToController = + parseIsolateBindings(directive.bindToController, directiveName, true); + } + if (bindings.bindToController && !directive.controller) { + // There is no controller + throw $compileMinErr('noctrl', + 'Cannot bind to controller without directive \'{0}\'s controller.', + directiveName); + } + return bindings; + } + + function assertValidDirectiveName(name) { + var letter = name.charAt(0); + if (!letter || letter !== lowercase(letter)) { + throw $compileMinErr('baddir', 'Directive/Component name \'{0}\' is invalid. The first character must be a lowercase letter', name); + } + if (name !== name.trim()) { + throw $compileMinErr('baddir', + 'Directive/Component name \'{0}\' is invalid. The name should not contain leading or trailing whitespaces', + name); + } + } + + function getDirectiveRequire(directive) { + var require = directive.require || (directive.controller && directive.name); + + if (!isArray(require) && isObject(require)) { + forEach(require, function(value, key) { + var match = value.match(REQUIRE_PREFIX_REGEXP); + var name = value.substring(match[0].length); + if (!name) require[key] = match[0] + key; + }); + } + + return require; + } + + function getDirectiveRestrict(restrict, name) { + if (restrict && !(isString(restrict) && /[EACM]/.test(restrict))) { + throw $compileMinErr('badrestrict', + 'Restrict property \'{0}\' of directive \'{1}\' is invalid', + restrict, + name); + } + + return restrict || 'EA'; + } + + /** + * @ngdoc method + * @name $compileProvider#directive + * @kind function + * + * @description + * Register a new directive with the compiler. + * + * @param {string|Object} name Name of the directive in camel-case (i.e. `ngBind` which will match + * as `ng-bind`), or an object map of directives where the keys are the names and the values + * are the factories. + * @param {Function|Array} directiveFactory An injectable directive factory function. See the + * {@link guide/directive directive guide} and the {@link $compile compile API} for more info. + * @returns {ng.$compileProvider} Self for chaining. + */ + this.directive = function registerDirective(name, directiveFactory) { + assertArg(name, 'name'); + assertNotHasOwnProperty(name, 'directive'); + if (isString(name)) { + assertValidDirectiveName(name); + assertArg(directiveFactory, 'directiveFactory'); if (!hasDirectives.hasOwnProperty(name)) { hasDirectives[name] = []; $provide.factory(name + Suffix, ['$injector', '$exceptionHandler', @@ -5586,8 +8852,9 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { directive.priority = directive.priority || 0; directive.index = index; directive.name = directive.name || name; - directive.require = directive.require || (directive.controller && directive.name); - directive.restrict = directive.restrict || 'A'; + directive.require = getDirectiveRequire(directive); + directive.restrict = getDirectiveRestrict(directive.restrict, name); + directive.$$moduleName = directiveFactory.$$moduleName; directives.push(directive); } catch (e) { $exceptionHandler(e); @@ -5603,85 +8870,626 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { return this; }; + /** + * @ngdoc method + * @name $compileProvider#component + * @module ng + * @param {string|Object} name Name of the component in camelCase (i.e. `myComp` which will match ``), + * or an object map of components where the keys are the names and the values are the component definition objects. + * @param {Object} options Component definition object (a simplified + * {@link ng.$compile#directive-definition-object directive definition object}), + * with the following properties (all optional): + * + * - `controller` – `{(string|function()=}` – controller constructor function that should be + * associated with newly created scope or the name of a {@link ng.$compile#-controller- + * registered controller} if passed as a string. An empty `noop` function by default. + * - `controllerAs` – `{string=}` – identifier name for to reference the controller in the component's scope. + * If present, the controller will be published to scope under the `controllerAs` name. + * If not present, this will default to be `$ctrl`. + * - `template` – `{string=|function()=}` – html template as a string or a function that + * returns an html template as a string which should be used as the contents of this component. + * Empty string by default. + * + * If `template` is a function, then it is {@link auto.$injector#invoke injected} with + * the following locals: + * + * - `$element` - Current element + * - `$attrs` - Current attributes object for the element + * + * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html + * template that should be used as the contents of this component. + * + * If `templateUrl` is a function, then it is {@link auto.$injector#invoke injected} with + * the following locals: + * + * - `$element` - Current element + * - `$attrs` - Current attributes object for the element + * + * - `bindings` – `{object=}` – defines bindings between DOM attributes and component properties. + * Component properties are always bound to the component controller and not to the scope. + * See {@link ng.$compile#-bindtocontroller- `bindToController`}. + * - `transclude` – `{boolean=}` – whether {@link $compile#transclusion content transclusion} is enabled. + * Disabled by default. + * - `require` - `{Object=}` - requires the controllers of other directives and binds them to + * this component's controller. The object keys specify the property names under which the required + * controllers (object values) will be bound. See {@link ng.$compile#-require- `require`}. + * - `$...` – additional properties to attach to the directive factory function and the controller + * constructor function. (This is used by the component router to annotate) + * + * @returns {ng.$compileProvider} the compile provider itself, for chaining of function calls. + * @description + * Register a **component definition** with the compiler. This is a shorthand for registering a special + * type of directive, which represents a self-contained UI component in your application. Such components + * are always isolated (i.e. `scope: {}`) and are always restricted to elements (i.e. `restrict: 'E'`). + * + * Component definitions are very simple and do not require as much configuration as defining general + * directives. Component definitions usually consist only of a template and a controller backing it. + * + * In order to make the definition easier, components enforce best practices like use of `controllerAs`, + * `bindToController`. They always have **isolate scope** and are restricted to elements. + * + * Here are a few examples of how you would usually define components: + * + * ```js + * var myMod = angular.module(...); + * myMod.component('myComp', { + * template: '
My name is {{$ctrl.name}}
', + * controller: function() { + * this.name = 'shahar'; + * } + * }); + * + * myMod.component('myComp', { + * template: '
My name is {{$ctrl.name}}
', + * bindings: {name: '@'} + * }); + * + * myMod.component('myComp', { + * templateUrl: 'views/my-comp.html', + * controller: 'MyCtrl', + * controllerAs: 'ctrl', + * bindings: {name: '@'} + * }); + * + * ``` + * For more examples, and an in-depth guide, see the {@link guide/component component guide}. + * + *
+ * See also {@link ng.$compileProvider#directive $compileProvider.directive()}. + */ + this.component = function registerComponent(name, options) { + if (!isString(name)) { + forEach(name, reverseParams(bind(this, registerComponent))); + return this; + } + + var controller = options.controller || function() {}; + + function factory($injector) { + function makeInjectable(fn) { + if (isFunction(fn) || isArray(fn)) { + return /** @this */ function(tElement, tAttrs) { + return $injector.invoke(fn, this, {$element: tElement, $attrs: tAttrs}); + }; + } else { + return fn; + } + } + + var template = (!options.template && !options.templateUrl ? '' : options.template); + var ddo = { + controller: controller, + controllerAs: identifierForController(options.controller) || options.controllerAs || '$ctrl', + template: makeInjectable(template), + templateUrl: makeInjectable(options.templateUrl), + transclude: options.transclude, + scope: {}, + bindToController: options.bindings || {}, + restrict: 'E', + require: options.require + }; + + // Copy annotations (starting with $) over to the DDO + forEach(options, function(val, key) { + if (key.charAt(0) === '$') ddo[key] = val; + }); + + return ddo; + } + + // TODO(pete) remove the following `forEach` before we release 1.6.0 + // The component-router@0.2.0 looks for the annotations on the controller constructor + // Nothing in AngularJS looks for annotations on the factory function but we can't remove + // it from 1.5.x yet. + + // Copy any annotation properties (starting with $) over to the factory and controller constructor functions + // These could be used by libraries such as the new component router + forEach(options, function(val, key) { + if (key.charAt(0) === '$') { + factory[key] = val; + // Don't try to copy over annotations to named controller + if (isFunction(controller)) controller[key] = val; + } + }); + + factory.$inject = ['$injector']; + + return this.directive(name, factory); + }; + /** * @ngdoc method - * @name $compileProvider#aHrefSanitizationWhitelist - * @function + * @name $compileProvider#aHrefSanitizationTrustedUrlList + * @kind function * * @description - * Retrieves or overrides the default regular expression that is used for whitelisting of safe + * Retrieves or overrides the default regular expression that is used for determining trusted safe * urls during a[href] sanitization. * - * The sanitization is a security measure aimed at prevent XSS attacks via html links. + * The sanitization is a security measure aimed at preventing XSS attacks via html links. * * Any url about to be assigned to a[href] via data-binding is first normalized and turned into - * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist` + * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationTrustedUrlList` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * - * @param {RegExp=} regexp New regexp to whitelist urls with. + * @param {RegExp=} regexp New regexp to trust urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ - this.aHrefSanitizationWhitelist = function(regexp) { + this.aHrefSanitizationTrustedUrlList = function(regexp) { if (isDefined(regexp)) { - $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp); + $$sanitizeUriProvider.aHrefSanitizationTrustedUrlList(regexp); return this; } else { - return $$sanitizeUriProvider.aHrefSanitizationWhitelist(); + return $$sanitizeUriProvider.aHrefSanitizationTrustedUrlList(); } }; /** * @ngdoc method - * @name $compileProvider#imgSrcSanitizationWhitelist - * @function + * @name $compileProvider#aHrefSanitizationWhitelist + * @kind function + * + * @deprecated + * sinceVersion="1.8.1" + * + * This method is deprecated. Use {@link $compileProvider#aHrefSanitizationTrustedUrlList + * aHrefSanitizationTrustedUrlList} instead. + */ + Object.defineProperty(this, 'aHrefSanitizationWhitelist', { + get: function() { + return this.aHrefSanitizationTrustedUrlList; + }, + set: function(value) { + this.aHrefSanitizationTrustedUrlList = value; + } + }); + + + /** + * @ngdoc method + * @name $compileProvider#imgSrcSanitizationTrustedUrlList + * @kind function * * @description - * Retrieves or overrides the default regular expression that is used for whitelisting of safe + * Retrieves or overrides the default regular expression that is used for determining trusted safe * urls during img[src] sanitization. * * The sanitization is a security measure aimed at prevent XSS attacks via html links. * * Any url about to be assigned to img[src] via data-binding is first normalized and turned into - * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist` + * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationTrustedUrlList` * regular expression. If a match is found, the original url is written into the dom. Otherwise, * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM. * - * @param {RegExp=} regexp New regexp to whitelist urls with. + * @param {RegExp=} regexp New regexp to trust urls with. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for * chaining otherwise. */ - this.imgSrcSanitizationWhitelist = function(regexp) { + this.imgSrcSanitizationTrustedUrlList = function(regexp) { if (isDefined(regexp)) { - $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp); + $$sanitizeUriProvider.imgSrcSanitizationTrustedUrlList(regexp); return this; } else { - return $$sanitizeUriProvider.imgSrcSanitizationWhitelist(); + return $$sanitizeUriProvider.imgSrcSanitizationTrustedUrlList(); + } + }; + + + /** + * @ngdoc method + * @name $compileProvider#imgSrcSanitizationWhitelist + * @kind function + * + * @deprecated + * sinceVersion="1.8.1" + * + * This method is deprecated. Use {@link $compileProvider#imgSrcSanitizationTrustedUrlList + * imgSrcSanitizationTrustedUrlList} instead. + */ + Object.defineProperty(this, 'imgSrcSanitizationWhitelist', { + get: function() { + return this.imgSrcSanitizationTrustedUrlList; + }, + set: function(value) { + this.imgSrcSanitizationTrustedUrlList = value; + } + }); + + /** + * @ngdoc method + * @name $compileProvider#debugInfoEnabled + * + * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the + * current debugInfoEnabled state + * @returns {*} current value if used as getter or itself (chaining) if used as setter + * + * @kind function + * + * @description + * Call this method to enable/disable various debug runtime information in the compiler such as adding + * binding information and a reference to the current scope on to DOM elements. + * If enabled, the compiler will add the following to DOM elements that have been bound to the scope + * * `ng-binding` CSS class + * * `ng-scope` and `ng-isolated-scope` CSS classes + * * `$binding` data property containing an array of the binding expressions + * * Data properties used by the {@link angular.element#methods `scope()`/`isolateScope()` methods} to return + * the element's scope. + * * Placeholder comments will contain information about what directive and binding caused the placeholder. + * E.g. ``. + * + * You may want to disable this in production for a significant performance boost. See + * {@link guide/production#disabling-debug-data Disabling Debug Data} for more. + * + * The default value is true. + */ + var debugInfoEnabled = true; + this.debugInfoEnabled = function(enabled) { + if (isDefined(enabled)) { + debugInfoEnabled = enabled; + return this; + } + return debugInfoEnabled; + }; + + /** + * @ngdoc method + * @name $compileProvider#strictComponentBindingsEnabled + * + * @param {boolean=} enabled update the strictComponentBindingsEnabled state if provided, + * otherwise return the current strictComponentBindingsEnabled state. + * @returns {*} current value if used as getter or itself (chaining) if used as setter + * + * @kind function + * + * @description + * Call this method to enable / disable the strict component bindings check. If enabled, the + * compiler will enforce that all scope / controller bindings of a + * {@link $compileProvider#directive directive} / {@link $compileProvider#component component} + * that are not set as optional with `?`, must be provided when the directive is instantiated. + * If not provided, the compiler will throw the + * {@link error/$compile/missingattr $compile:missingattr error}. + * + * The default value is false. + */ + var strictComponentBindingsEnabled = false; + this.strictComponentBindingsEnabled = function(enabled) { + if (isDefined(enabled)) { + strictComponentBindingsEnabled = enabled; + return this; + } + return strictComponentBindingsEnabled; + }; + + var TTL = 10; + /** + * @ngdoc method + * @name $compileProvider#onChangesTtl + * @description + * + * Sets the number of times `$onChanges` hooks can trigger new changes before giving up and + * assuming that the model is unstable. + * + * The current default is 10 iterations. + * + * In complex applications it's possible that dependencies between `$onChanges` hooks and bindings will result + * in several iterations of calls to these hooks. However if an application needs more than the default 10 + * iterations to stabilize then you should investigate what is causing the model to continuously change during + * the `$onChanges` hook execution. + * + * Increasing the TTL could have performance implications, so you should not change it without proper justification. + * + * @param {number} limit The number of `$onChanges` hook iterations. + * @returns {number|object} the current limit (or `this` if called as a setter for chaining) + */ + this.onChangesTtl = function(value) { + if (arguments.length) { + TTL = value; + return this; + } + return TTL; + }; + + var commentDirectivesEnabledConfig = true; + /** + * @ngdoc method + * @name $compileProvider#commentDirectivesEnabled + * @description + * + * It indicates to the compiler + * whether or not directives on comments should be compiled. + * Defaults to `true`. + * + * Calling this function with false disables the compilation of directives + * on comments for the whole application. + * This results in a compilation performance gain, + * as the compiler doesn't have to check comments when looking for directives. + * This should however only be used if you are sure that no comment directives are used in + * the application (including any 3rd party directives). + * + * @param {boolean} enabled `false` if the compiler may ignore directives on comments + * @returns {boolean|object} the current value (or `this` if called as a setter for chaining) + */ + this.commentDirectivesEnabled = function(value) { + if (arguments.length) { + commentDirectivesEnabledConfig = value; + return this; + } + return commentDirectivesEnabledConfig; + }; + + + var cssClassDirectivesEnabledConfig = true; + /** + * @ngdoc method + * @name $compileProvider#cssClassDirectivesEnabled + * @description + * + * It indicates to the compiler + * whether or not directives on element classes should be compiled. + * Defaults to `true`. + * + * Calling this function with false disables the compilation of directives + * on element classes for the whole application. + * This results in a compilation performance gain, + * as the compiler doesn't have to check element classes when looking for directives. + * This should however only be used if you are sure that no class directives are used in + * the application (including any 3rd party directives). + * + * @param {boolean} enabled `false` if the compiler may ignore directives on element classes + * @returns {boolean|object} the current value (or `this` if called as a setter for chaining) + */ + this.cssClassDirectivesEnabled = function(value) { + if (arguments.length) { + cssClassDirectivesEnabledConfig = value; + return this; + } + return cssClassDirectivesEnabledConfig; + }; + + + /** + * The security context of DOM Properties. + * @private + */ + var PROP_CONTEXTS = createMap(); + + /** + * @ngdoc method + * @name $compileProvider#addPropertySecurityContext + * @description + * + * Defines the security context for DOM properties bound by ng-prop-*. + * + * @param {string} elementName The element name or '*' to match any element. + * @param {string} propertyName The DOM property name. + * @param {string} ctx The {@link $sce} security context in which this value is safe for use, e.g. `$sce.URL` + * @returns {object} `this` for chaining + */ + this.addPropertySecurityContext = function(elementName, propertyName, ctx) { + var key = (elementName.toLowerCase() + '|' + propertyName.toLowerCase()); + + if (key in PROP_CONTEXTS && PROP_CONTEXTS[key] !== ctx) { + throw $compileMinErr('ctxoverride', 'Property context \'{0}.{1}\' already set to \'{2}\', cannot override to \'{3}\'.', elementName, propertyName, PROP_CONTEXTS[key], ctx); } + + PROP_CONTEXTS[key] = ctx; + return this; }; + /* Default property contexts. + * + * Copy of https://github.com/angular/angular/blob/6.0.6/packages/compiler/src/schema/dom_security_schema.ts#L31-L58 + * Changing: + * - SecurityContext.* => SCE_CONTEXTS/$sce.* + * - STYLE => CSS + * - various URL => MEDIA_URL + * - *|formAction, form|action URL => RESOURCE_URL (like the attribute) + */ + (function registerNativePropertyContexts() { + function registerContext(ctx, values) { + forEach(values, function(v) { PROP_CONTEXTS[v.toLowerCase()] = ctx; }); + } + + registerContext(SCE_CONTEXTS.HTML, [ + 'iframe|srcdoc', + '*|innerHTML', + '*|outerHTML' + ]); + registerContext(SCE_CONTEXTS.CSS, ['*|style']); + registerContext(SCE_CONTEXTS.URL, [ + 'area|href', 'area|ping', + 'a|href', 'a|ping', + 'blockquote|cite', + 'body|background', + 'del|cite', + 'input|src', + 'ins|cite', + 'q|cite' + ]); + registerContext(SCE_CONTEXTS.MEDIA_URL, [ + 'audio|src', + 'img|src', 'img|srcset', + 'source|src', 'source|srcset', + 'track|src', + 'video|src', 'video|poster' + ]); + registerContext(SCE_CONTEXTS.RESOURCE_URL, [ + '*|formAction', + 'applet|code', 'applet|codebase', + 'base|href', + 'embed|src', + 'frame|src', + 'form|action', + 'head|profile', + 'html|manifest', + 'iframe|src', + 'link|href', + 'media|src', + 'object|codebase', 'object|data', + 'script|src' + ]); + })(); + + this.$get = [ - '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse', - '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri', - function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse, - $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) { + '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse', + '$controller', '$rootScope', '$sce', '$animate', + function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse, + $controller, $rootScope, $sce, $animate) { + + var SIMPLE_ATTR_NAME = /^\w/; + var specialAttrHolder = window.document.createElement('div'); + + + var commentDirectivesEnabled = commentDirectivesEnabledConfig; + var cssClassDirectivesEnabled = cssClassDirectivesEnabledConfig; + + + var onChangesTtl = TTL; + // The onChanges hooks should all be run together in a single digest + // When changes occur, the call to trigger their hooks will be added to this queue + var onChangesQueue; + + // This function is called in a $$postDigest to trigger all the onChanges hooks in a single digest + function flushOnChangesQueue() { + try { + if (!(--onChangesTtl)) { + // We have hit the TTL limit so reset everything + onChangesQueue = undefined; + throw $compileMinErr('infchng', '{0} $onChanges() iterations reached. Aborting!\n', TTL); + } + // We must run this hook in an apply since the $$postDigest runs outside apply + $rootScope.$apply(function() { + for (var i = 0, ii = onChangesQueue.length; i < ii; ++i) { + try { + onChangesQueue[i](); + } catch (e) { + $exceptionHandler(e); + } + } + // Reset the queue to trigger a new schedule next time there is a change + onChangesQueue = undefined; + }); + } finally { + onChangesTtl++; + } + } + + + function sanitizeSrcset(value, invokeType) { + if (!value) { + return value; + } + if (!isString(value)) { + throw $compileMinErr('srcset', 'Can\'t pass trusted values to `{0}`: "{1}"', invokeType, value.toString()); + } + + // Such values are a bit too complex to handle automatically inside $sce. + // Instead, we sanitize each of the URIs individually, which works, even dynamically. + + // It's not possible to work around this using `$sce.trustAsMediaUrl`. + // If you want to programmatically set explicitly trusted unsafe URLs, you should use + // `$sce.trustAsHtml` on the whole `img` tag and inject it into the DOM using the + // `ng-bind-html` directive. + + var result = ''; + + // first check if there are spaces because it's not the same pattern + var trimmedSrcset = trim(value); + // ( 999x ,| 999w ,| ,|, ) + var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/; + var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/; + + // split srcset into tuple of uri and descriptor except for the last item + var rawUris = trimmedSrcset.split(pattern); + + // for each tuples + var nbrUrisWith2parts = Math.floor(rawUris.length / 2); + for (var i = 0; i < nbrUrisWith2parts; i++) { + var innerIdx = i * 2; + // sanitize the uri + result += $sce.getTrustedMediaUrl(trim(rawUris[innerIdx])); + // add the descriptor + result += ' ' + trim(rawUris[innerIdx + 1]); + } + + // split the last item into uri and descriptor + var lastTuple = trim(rawUris[i * 2]).split(/\s/); + + // sanitize the last uri + result += $sce.getTrustedMediaUrl(trim(lastTuple[0])); + + // and add the last descriptor if any + if (lastTuple.length === 2) { + result += (' ' + trim(lastTuple[1])); + } + return result; + } + + + function Attributes(element, attributesToCopy) { + if (attributesToCopy) { + var keys = Object.keys(attributesToCopy); + var i, l, key; + + for (i = 0, l = keys.length; i < l; i++) { + key = keys[i]; + this[key] = attributesToCopy[key]; + } + } else { + this.$attr = {}; + } - var Attributes = function(element, attr) { this.$$element = element; - this.$attr = attr || {}; - }; + } Attributes.prototype = { + /** + * @ngdoc method + * @name $compile.directive.Attributes#$normalize + * @kind function + * + * @description + * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or + * `data-`) to its normalized, camelCase form. + * + * Also there is special case for Moz prefix starting with upper case letter. + * + * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives} + * + * @param {string} name Name to normalize + */ $normalize: directiveNormalize, /** * @ngdoc method * @name $compile.directive.Attributes#$addClass - * @function + * @kind function * * @description * Adds the CSS class value specified by the classVal parameter to the element. If animations @@ -5689,8 +9497,8 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { * * @param {string} classVal The className value that will be added to the element */ - $addClass : function(classVal) { - if(classVal && classVal.length > 0) { + $addClass: function(classVal) { + if (classVal && classVal.length > 0) { $animate.addClass(this.$$element, classVal); } }, @@ -5698,7 +9506,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { /** * @ngdoc method * @name $compile.directive.Attributes#$removeClass - * @function + * @kind function * * @description * Removes the CSS class value specified by the classVal parameter from the element. If @@ -5706,8 +9514,8 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { * * @param {string} classVal The className value that will be removed from the element */ - $removeClass : function(classVal) { - if(classVal && classVal.length > 0) { + $removeClass: function(classVal) { + if (classVal && classVal.length > 0) { $animate.removeClass(this.$$element, classVal); } }, @@ -5715,7 +9523,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { /** * @ngdoc method * @name $compile.directive.Attributes#$updateClass - * @function + * @kind function * * @description * Adds and removes the appropriate CSS class values to the element based on the difference @@ -5724,16 +9532,15 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { * @param {string} newClasses The current CSS className value * @param {string} oldClasses The former CSS className value */ - $updateClass : function(newClasses, oldClasses) { + $updateClass: function(newClasses, oldClasses) { var toAdd = tokenDifference(newClasses, oldClasses); - var toRemove = tokenDifference(oldClasses, newClasses); + if (toAdd && toAdd.length) { + $animate.addClass(this.$$element, toAdd); + } - if(toAdd.length === 0) { + var toRemove = tokenDifference(oldClasses, newClasses); + if (toRemove && toRemove.length) { $animate.removeClass(this.$$element, toRemove); - } else if(toRemove.length === 0) { - $animate.addClass(this.$$element, toAdd); - } else { - $animate.setClass(this.$$element, toAdd, toRemove); } }, @@ -5748,16 +9555,21 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { */ $set: function(key, value, writeAttr, attrName) { // TODO: decide whether or not to throw an error if "class" - //is set through this function since it may cause $updateClass to - //become unstable. + // is set through this function since it may cause $updateClass to + // become unstable. - var booleanKey = getBooleanAttrName(this.$$element[0], key), - normalizedVal, + var node = this.$$element[0], + booleanKey = getBooleanAttrName(node, key), + aliasedKey = getAliasedAttrName(key), + observer = key, nodeName; if (booleanKey) { this.$$element.prop(key, value); attrName = booleanKey; + } else if (aliasedKey) { + this[aliasedKey] = value; + observer = aliasedKey; } this[key] = value; @@ -5774,36 +9586,50 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { nodeName = nodeName_(this.$$element); - // sanitize a[href] and img[src] values - if ((nodeName === 'A' && key === 'href') || - (nodeName === 'IMG' && key === 'src')) { - this[key] = value = $$sanitizeUri(value, key === 'src'); + // Sanitize img[srcset] values. + if (nodeName === 'img' && key === 'srcset') { + this[key] = value = sanitizeSrcset(value, '$set(\'srcset\', value)'); } if (writeAttr !== false) { - if (value === null || value === undefined) { + if (value === null || isUndefined(value)) { this.$$element.removeAttr(attrName); } else { - this.$$element.attr(attrName, value); + if (SIMPLE_ATTR_NAME.test(attrName)) { + // jQuery skips special boolean attrs treatment in XML nodes for + // historical reasons and hence AngularJS cannot freely call + // `.attr(attrName, false) with such attributes. To avoid issues + // in XHTML, call `removeAttr` in such cases instead. + // See https://github.com/jquery/jquery/issues/4249 + if (booleanKey && value === false) { + this.$$element.removeAttr(attrName); + } else { + this.$$element.attr(attrName, value); + } + } else { + setSpecialAttr(this.$$element[0], attrName, value); + } } } // fire observers var $$observers = this.$$observers; - $$observers && forEach($$observers[key], function(fn) { - try { - fn(value); - } catch (e) { - $exceptionHandler(e); - } - }); + if ($$observers) { + forEach($$observers[observer], function(fn) { + try { + fn(value); + } catch (e) { + $exceptionHandler(e); + } + }); + } }, /** * @ngdoc method * @name $compile.directive.Attributes#$observe - * @function + * @kind function * * @description * Observes an interpolated attribute. @@ -5815,34 +9641,95 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { * @param {string} key Normalized key. (ie ngAttribute) . * @param {function(interpolatedValue)} fn Function that will be called whenever the interpolated value of the attribute changes. - * See the {@link guide/directive#Attributes Directives} guide for more info. - * @returns {function()} the `fn` parameter. + * See the {@link guide/interpolation#how-text-and-attribute-bindings-work Interpolation + * guide} for more info. + * @returns {function()} Returns a deregistration function for this observer. */ $observe: function(key, fn) { var attrs = this, - $$observers = (attrs.$$observers || (attrs.$$observers = {})), + $$observers = (attrs.$$observers || (attrs.$$observers = createMap())), listeners = ($$observers[key] || ($$observers[key] = [])); listeners.push(fn); $rootScope.$evalAsync(function() { - if (!listeners.$$inter) { + if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) { // no one registered attribute interpolation function, so lets call it manually fn(attrs[key]); } }); - return fn; + + return function() { + arrayRemove(listeners, fn); + }; } }; + function setSpecialAttr(element, attrName, value) { + // Attributes names that do not start with letters (such as `(click)`) cannot be set using `setAttribute` + // so we have to jump through some hoops to get such an attribute + // https://github.com/angular/angular.js/pull/13318 + specialAttrHolder.innerHTML = ''; + var attributes = specialAttrHolder.firstChild.attributes; + var attribute = attributes[0]; + // We have to remove the attribute from its container element before we can add it to the destination element + attributes.removeNamedItem(attribute.name); + attribute.value = value; + element.attributes.setNamedItem(attribute); + } + + function safeAddClass($element, className) { + try { + $element.addClass(className); + } catch (e) { + // ignore, since it means that we are trying to set class on + // SVG element, where class name is read-only. + } + } + + var startSymbol = $interpolate.startSymbol(), endSymbol = $interpolate.endSymbol(), - denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}') + denormalizeTemplate = (startSymbol === '{{' && endSymbol === '}}') ? identity : function denormalizeTemplate(template) { return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol); }, - NG_ATTR_BINDING = /^ngAttr[A-Z]/; + NG_PREFIX_BINDING = /^ng(Attr|Prop|On)([A-Z].*)$/; + var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/; + + compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) { + var bindings = $element.data('$binding') || []; + + if (isArray(binding)) { + bindings = bindings.concat(binding); + } else { + bindings.push(binding); + } + $element.data('$binding', bindings); + } : noop; + + compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) { + safeAddClass($element, 'ng-binding'); + } : noop; + + compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) { + var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope'; + $element.data(dataName, scope); + } : noop; + + compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) { + safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope'); + } : noop; + + compile.$$createComment = function(directiveName, comment) { + var content = ''; + if (debugInfoEnabled) { + content = ' ' + (directiveName || '') + ': '; + if (comment) content += comment + ' '; + } + return window.document.createComment(content); + }; return compile; @@ -5855,50 +9742,84 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { // modify it. $compileNodes = jqLite($compileNodes); } - // We can not compile top level text elements since text nodes can be merged and we will - // not be able to attach scope data to them, so we will wrap them in - forEach($compileNodes, function(node, index){ - if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) { - $compileNodes[index] = node = jqLite(node).wrap('').parent()[0]; - } - }); var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority, ignoreDirective, previousCompileContext); - safeAddClass($compileNodes, 'ng-scope'); - return function publicLinkFn(scope, cloneConnectFn, transcludeControllers){ + compile.$$addScopeClass($compileNodes); + var namespace = null; + return function publicLinkFn(scope, cloneConnectFn, options) { + if (!$compileNodes) { + throw $compileMinErr('multilink', 'This element has already been linked.'); + } assertArg(scope, 'scope'); - // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart - // and sometimes changes the structure of the DOM. - var $linkNode = cloneConnectFn - ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!! - : $compileNodes; - - forEach(transcludeControllers, function(instance, name) { - $linkNode.data('$' + name + 'Controller', instance); - }); - // Attach scope only to non-text nodes. - for(var i = 0, ii = $linkNode.length; i
').append($compileNodes).html()) + ); + } else if (cloneConnectFn) { + // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart + // and sometimes changes the structure of the DOM. + $linkNode = JQLitePrototype.clone.call($compileNodes); + } else { + $linkNode = $compileNodes; + } + + if (transcludeControllers) { + for (var controllerName in transcludeControllers) { + $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance); } } + compile.$$addScopeInfo($linkNode, scope); + if (cloneConnectFn) cloneConnectFn($linkNode, scope); - if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode); + if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn); + + if (!cloneConnectFn) { + $compileNodes = compositeLinkFn = null; + } return $linkNode; }; } - function safeAddClass($element, className) { - try { - $element.addClass(className); - } catch(e) { - // ignore, since it means that we are trying to set class on - // SVG element, where class name is read-only. + function detectNamespaceForChildElements(parentElement) { + // TODO: Make this detect MathML as well... + var node = parentElement && parentElement[0]; + if (!node) { + return 'html'; + } else { + return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html'; } } @@ -5920,12 +9841,23 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, previousCompileContext) { var linkFns = [], - attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound; + // `nodeList` can be either an element's `.childNodes` (live NodeList) + // or a jqLite/jQuery collection or an array + notLiveList = isArray(nodeList) || (nodeList instanceof jqLite), + attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound; + for (var i = 0; i < nodeList.length; i++) { attrs = new Attributes(); - // we must always refer to nodeList[i] since the nodes can be replaced underneath us. + // Support: IE 11 only + // Workaround for #11781 and #14924 + if (msie === 11) { + mergeConsecutiveTextNodes(nodeList, i, notLiveList); + } + + // We must always refer to `nodeList[i]` hereafter, + // since the nodes can be replaced underneath us. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined, ignoreDirective); @@ -5935,7 +9867,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { : null; if (nodeLinkFn && nodeLinkFn.scope) { - safeAddClass(jqLite(nodeList[i]), 'ng-scope'); + compile.$$addScopeClass(attrs.$$element); } childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || @@ -5943,10 +9875,16 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { !childNodes.length) ? null : compileNodes(childNodes, - nodeLinkFn ? nodeLinkFn.transclude : transcludeFn); + nodeLinkFn ? ( + (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement) + && nodeLinkFn.transclude) : transcludeFn); + + if (nodeLinkFn || childLinkFn) { + linkFns.push(i, nodeLinkFn, childLinkFn); + linkFnFound = true; + nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn; + } - linkFns.push(nodeLinkFn, childLinkFn); - linkFnFound = linkFnFound || nodeLinkFn || childLinkFn; //use the previous context only for the first element in the virtual group previousCompileContext = null; } @@ -5954,60 +9892,115 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { // return a linking function if we have found anything, null otherwise return linkFnFound ? compositeLinkFn : null; - function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) { - var nodeLinkFn, childLinkFn, node, $node, childScope, childTranscludeFn, i, ii, n; + function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) { + var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn; + var stableNodeList; + - // copy nodeList so that linking doesn't break due to live list updates. - var nodeListLength = nodeList.length, - stableNodeList = new Array(nodeListLength); - for (i = 0; i < nodeListLength; i++) { - stableNodeList[i] = nodeList[i]; + if (nodeLinkFnFound) { + // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our + // offsets don't get screwed up + var nodeListLength = nodeList.length; + stableNodeList = new Array(nodeListLength); + + // create a sparse array by only copying the elements which have a linkFn + for (i = 0; i < linkFns.length; i += 3) { + idx = linkFns[i]; + stableNodeList[idx] = nodeList[idx]; + } + } else { + stableNodeList = nodeList; } - for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) { - node = stableNodeList[n]; + for (i = 0, ii = linkFns.length; i < ii;) { + node = stableNodeList[linkFns[i++]]; nodeLinkFn = linkFns[i++]; childLinkFn = linkFns[i++]; - $node = jqLite(node); if (nodeLinkFn) { if (nodeLinkFn.scope) { childScope = scope.$new(); - $node.data('$scope', childScope); + compile.$$addScopeInfo(jqLite(node), childScope); } else { childScope = scope; } - childTranscludeFn = nodeLinkFn.transclude; - if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) { - nodeLinkFn(childLinkFn, childScope, node, $rootElement, - createBoundTranscludeFn(scope, childTranscludeFn || transcludeFn) - ); + + if (nodeLinkFn.transcludeOnThisElement) { + childBoundTranscludeFn = createBoundTranscludeFn( + scope, nodeLinkFn.transclude, parentBoundTranscludeFn); + + } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) { + childBoundTranscludeFn = parentBoundTranscludeFn; + + } else if (!parentBoundTranscludeFn && transcludeFn) { + childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn); + } else { - nodeLinkFn(childLinkFn, childScope, node, $rootElement, boundTranscludeFn); + childBoundTranscludeFn = null; } + + nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn); + } else if (childLinkFn) { - childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn); + childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn); } } } } - function createBoundTranscludeFn(scope, transcludeFn) { - return function boundTranscludeFn(transcludedScope, cloneFn, controllers) { - var scopeCreated = false; + function mergeConsecutiveTextNodes(nodeList, idx, notLiveList) { + var node = nodeList[idx]; + var parent = node.parentNode; + var sibling; + + if (node.nodeType !== NODE_TYPE_TEXT) { + return; + } + + while (true) { + sibling = parent ? node.nextSibling : nodeList[idx + 1]; + if (!sibling || sibling.nodeType !== NODE_TYPE_TEXT) { + break; + } + + node.nodeValue = node.nodeValue + sibling.nodeValue; + + if (sibling.parentNode) { + sibling.parentNode.removeChild(sibling); + } + if (notLiveList && sibling === nodeList[idx + 1]) { + nodeList.splice(idx + 1, 1); + } + } + } + + function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) { + function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) { if (!transcludedScope) { - transcludedScope = scope.$new(); + transcludedScope = scope.$new(false, containingScope); transcludedScope.$$transcluded = true; - scopeCreated = true; } - var clone = transcludeFn(transcludedScope, cloneFn, controllers); - if (scopeCreated) { - clone.on('$destroy', bind(transcludedScope, transcludedScope.$destroy)); + return transcludeFn(transcludedScope, cloneFn, { + parentBoundTranscludeFn: previousBoundTranscludeFn, + transcludeControllers: controllers, + futureParentElement: futureParentElement + }); + } + + // We need to attach the transclusion slots onto the `boundTranscludeFn` + // so that they are available inside the `controllersBoundTransclude` function + var boundSlots = boundTranscludeFn.$$slots = createMap(); + for (var slotName in transcludeFn.$$slots) { + if (transcludeFn.$$slots[slotName]) { + boundSlots[slotName] = createBoundTranscludeFn(scope, transcludeFn.$$slots[slotName], previousBoundTranscludeFn); + } else { + boundSlots[slotName] = null; } - return clone; - }; + } + + return boundTranscludeFn; } /** @@ -6024,52 +10017,96 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { var nodeType = node.nodeType, attrsMap = attrs.$attr, match, + nodeName, className; - switch(nodeType) { - case 1: /* Element */ + switch (nodeType) { + case NODE_TYPE_ELEMENT: /* Element */ + + nodeName = nodeName_(node); + // use the node name: addDirective(directives, - directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective); + directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective); // iterate over the attributes - for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes, + for (var attr, name, nName, value, ngPrefixMatch, nAttrs = node.attributes, j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) { var attrStartName = false; var attrEndName = false; + var isNgAttr = false, isNgProp = false, isNgEvent = false; + var multiElementMatch; + attr = nAttrs[j]; - if (!msie || msie >= 8 || attr.specified) { - name = attr.name; - // support ngAttr attribute binding - ngAttrName = directiveNormalize(name); - if (NG_ATTR_BINDING.test(ngAttrName)) { - name = snake_case(ngAttrName.substr(6), '-'); - } + name = attr.name; + value = attr.value; + + nName = directiveNormalize(name.toLowerCase()); + + // Support ng-attr-*, ng-prop-* and ng-on-* + if ((ngPrefixMatch = nName.match(NG_PREFIX_BINDING))) { + isNgAttr = ngPrefixMatch[1] === 'Attr'; + isNgProp = ngPrefixMatch[1] === 'Prop'; + isNgEvent = ngPrefixMatch[1] === 'On'; + + // Normalize the non-prefixed name + name = name.replace(PREFIX_REGEXP, '') + .toLowerCase() + .substr(4 + ngPrefixMatch[1].length).replace(/_(.)/g, function(match, letter) { + return letter.toUpperCase(); + }); - var directiveNName = ngAttrName.replace(/(Start|End)$/, ''); - if (ngAttrName === directiveNName + 'Start') { - attrStartName = name; - attrEndName = name.substr(0, name.length - 5) + 'end'; - name = name.substr(0, name.length - 6); - } + // Support *-start / *-end multi element directives + } else if ((multiElementMatch = nName.match(MULTI_ELEMENT_DIR_RE)) && directiveIsMultiElement(multiElementMatch[1])) { + attrStartName = name; + attrEndName = name.substr(0, name.length - 5) + 'end'; + name = name.substr(0, name.length - 6); + } + + if (isNgProp || isNgEvent) { + attrs[nName] = value; + attrsMap[nName] = attr.name; + if (isNgProp) { + addPropertyDirective(node, directives, nName, name); + } else { + addEventDirective(directives, nName, name); + } + } else { + // Update nName for cases where a prefix was removed + // NOTE: the .toLowerCase() is unnecessary and causes https://github.com/angular/angular.js/issues/16624 for ng-attr-* nName = directiveNormalize(name.toLowerCase()); attrsMap[nName] = name; - attrs[nName] = value = trim(attr.value); - if (getBooleanAttrName(node, nName)) { - attrs[nName] = true; // presence means true + + if (isNgAttr || !attrs.hasOwnProperty(nName)) { + attrs[nName] = value; + if (getBooleanAttrName(node, nName)) { + attrs[nName] = true; // presence means true + } } - addAttrInterpolateDirective(node, directives, value, nName); + + addAttrInterpolateDirective(node, directives, value, nName, isNgAttr); addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, attrEndName); } } + if (nodeName === 'input' && node.getAttribute('type') === 'hidden') { + // Hidden input elements can have strange behaviour when navigating back to the page + // This tells the browser not to try to cache and reinstate previous values + node.setAttribute('autocomplete', 'off'); + } + // use class as directive + if (!cssClassDirectivesEnabled) break; className = node.className; + if (isObject(className)) { + // Maybe SVGAnimatedString + className = className.animVal; + } if (isString(className) && className !== '') { - while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) { + while ((match = CLASS_DIRECTIVE_REGEXP.exec(className))) { nName = directiveNormalize(match[2]); if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) { attrs[nName] = trim(match[3]); @@ -6078,23 +10115,12 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { } } break; - case 3: /* Text Node */ + case NODE_TYPE_TEXT: /* Text Node */ addTextInterpolateDirective(directives, node.nodeValue); break; - case 8: /* Comment */ - try { - match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); - if (match) { - nName = directiveNormalize(match[1]); - if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { - attrs[nName] = trim(match[2]); - } - } - } catch (e) { - // turns out that under some circumstances IE9 throws errors when one attempts to read - // comment's node value. - // Just ignore it and continue. (Can't seem to reproduce in test case.) - } + case NODE_TYPE_COMMENT: /* Comment */ + if (!commentDirectivesEnabled) break; + collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective); break; } @@ -6102,8 +10128,26 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { return directives; } + function collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective) { + // function created because of performance, try/catch disables + // the optimization of the whole function #14848 + try { + var match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue); + if (match) { + var nName = directiveNormalize(match[1]); + if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) { + attrs[nName] = trim(match[2]); + } + } + } catch (e) { + // turns out that under some circumstances IE9 throws errors when one attempts to read + // comment's node value. + // Just ignore it and continue. (Can't seem to reproduce in test case.) + } + } + /** - * Given a node with an directive-start it collects all of the siblings until it finds + * Given a node with a directive-start it collects all of the siblings until it finds * directive-end. * @param node * @param attrStart @@ -6114,14 +10158,13 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { var nodes = []; var depth = 0; if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) { - var startNode = node; do { if (!node) { throw $compileMinErr('uterdir', - "Unterminated attribute, found '{0}' but no matching '{1}' found.", + 'Unterminated attribute, found \'{0}\' but no matching \'{1}\' found.', attrStart, attrEnd); } - if (node.nodeType == 1 /** Element **/) { + if (node.nodeType === NODE_TYPE_ELEMENT) { if (node.hasAttribute(attrStart)) depth++; if (node.hasAttribute(attrEnd)) depth--; } @@ -6144,12 +10187,41 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { * @returns {Function} */ function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) { - return function(scope, element, attrs, controllers, transcludeFn) { + return function groupedElementsLink(scope, element, attrs, controllers, transcludeFn) { element = groupScan(element[0], attrStart, attrEnd); return linkFn(scope, element, attrs, controllers, transcludeFn); }; } + /** + * A function generator that is used to support both eager and lazy compilation + * linking function. + * @param eager + * @param $compileNodes + * @param transcludeFn + * @param maxPriority + * @param ignoreDirective + * @param previousCompileContext + * @returns {Function} + */ + function compilationGenerator(eager, $compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) { + var compiled; + + if (eager) { + return compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext); + } + return /** @this */ function lazyCompilation() { + if (!compiled) { + compiled = compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext); + + // Null out all of these references in order to make them eligible for garbage collection + // since this is a potentially long lived closure + $compileNodes = transcludeFn = previousCompileContext = null; + } + return compiled.apply(this, arguments); + }; + } + /** * Once the directives have been collected, their compile functions are executed. This method * is responsible for inlining directive templates as well as terminating the application @@ -6179,12 +10251,13 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { previousCompileContext = previousCompileContext || {}; var terminalPriority = -Number.MAX_VALUE, - newScopeDirective, + newScopeDirective = previousCompileContext.newScopeDirective, controllerDirectives = previousCompileContext.controllerDirectives, newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective, templateDirective = previousCompileContext.templateDirective, nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective, hasTranscludeDirective = false, + hasTemplate = false, hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective, $compileNode = templateAttrs.$$element = jqLite(compileNode), directive, @@ -6193,10 +10266,12 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { replaceDirective = originalReplaceDirective, childTranscludeFn = transcludeFn, linkFn, + didScanForMultipleTransclusion = false, + mightHaveMultipleTransclusionError = false, directiveValue; // executes all directives on the current element - for(var i = 0, ii = directives.length; i < ii; i++) { + for (var i = 0, ii = directives.length; i < ii; i++) { directive = directives[i]; var attrStart = directive.$$start; var attrEnd = directive.$$end; @@ -6211,31 +10286,63 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { break; // prevent further processing of directives } - if (directiveValue = directive.scope) { - newScopeDirective = newScopeDirective || directive; + directiveValue = directive.scope; + + if (directiveValue) { // skip the check for directives with async templates, we'll check the derived sync // directive when the template arrives if (!directive.templateUrl) { - assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, - $compileNode); if (isObject(directiveValue)) { + // This directive is trying to add an isolated scope. + // Check that there is no scope of any kind already + assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective, + directive, $compileNode); newIsolateScopeDirective = directive; + } else { + // This directive is trying to add a child scope. + // Check that there is no isolated scope already + assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive, + $compileNode); } } + + newScopeDirective = newScopeDirective || directive; } directiveName = directive.name; + // If we encounter a condition that can result in transclusion on the directive, + // then scan ahead in the remaining directives for others that may cause a multiple + // transclusion error to be thrown during the compilation process. If a matching directive + // is found, then we know that when we encounter a transcluded directive, we need to eagerly + // compile the `transclude` function rather than doing it lazily in order to throw + // exceptions at the correct time + if (!didScanForMultipleTransclusion && ((directive.replace && (directive.templateUrl || directive.template)) + || (directive.transclude && !directive.$$tlb))) { + var candidateDirective; + + for (var scanningIndex = i + 1; (candidateDirective = directives[scanningIndex++]);) { + if ((candidateDirective.transclude && !candidateDirective.$$tlb) + || (candidateDirective.replace && (candidateDirective.templateUrl || candidateDirective.template))) { + mightHaveMultipleTransclusionError = true; + break; + } + } + + didScanForMultipleTransclusion = true; + } + if (!directive.templateUrl && directive.controller) { - directiveValue = directive.controller; - controllerDirectives = controllerDirectives || {}; - assertNoDuplicate("'" + directiveName + "' controller", + controllerDirectives = controllerDirectives || createMap(); + assertNoDuplicate('\'' + directiveName + '\' controller', controllerDirectives[directiveName], directive, $compileNode); controllerDirectives[directiveName] = directive; } - if (directiveValue = directive.transclude) { + directiveValue = directive.transclude; + + if (directiveValue) { hasTranscludeDirective = true; // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion. @@ -6246,17 +10353,16 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { nonTlbTranscludeDirective = directive; } - if (directiveValue == 'element') { + if (directiveValue === 'element') { hasElementTranscludeDirective = true; terminalPriority = directive.priority; - $template = groupScan(compileNode, attrStart, attrEnd); + $template = $compileNode; $compileNode = templateAttrs.$$element = - jqLite(document.createComment(' ' + directiveName + ': ' + - templateAttrs[directiveName] + ' ')); + jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName])); compileNode = $compileNode[0]; - replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode); + replaceWith(jqCollection, sliceArgs($template), compileNode); - childTranscludeFn = compile($template, transcludeFn, terminalPriority, + childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, terminalPriority, replaceDirective && replaceDirective.name, { // Don't pass in: // - controllerDirectives - otherwise we'll create duplicates controllers @@ -6268,13 +10374,77 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { nonTlbTranscludeDirective: nonTlbTranscludeDirective }); } else { - $template = jqLite(jqLiteClone(compileNode)).contents(); + + var slots = createMap(); + + if (!isObject(directiveValue)) { + $template = jqLite(jqLiteClone(compileNode)).contents(); + } else { + + // We have transclusion slots, + // collect them up, compile them and store their transclusion functions + $template = window.document.createDocumentFragment(); + + var slotMap = createMap(); + var filledSlots = createMap(); + + // Parse the element selectors + forEach(directiveValue, function(elementSelector, slotName) { + // If an element selector starts with a ? then it is optional + var optional = (elementSelector.charAt(0) === '?'); + elementSelector = optional ? elementSelector.substring(1) : elementSelector; + + slotMap[elementSelector] = slotName; + + // We explicitly assign `null` since this implies that a slot was defined but not filled. + // Later when calling boundTransclusion functions with a slot name we only error if the + // slot is `undefined` + slots[slotName] = null; + + // filledSlots contains `true` for all slots that are either optional or have been + // filled. This is used to check that we have not missed any required slots + filledSlots[slotName] = optional; + }); + + // Add the matching elements into their slot + forEach($compileNode.contents(), function(node) { + var slotName = slotMap[directiveNormalize(nodeName_(node))]; + if (slotName) { + filledSlots[slotName] = true; + slots[slotName] = slots[slotName] || window.document.createDocumentFragment(); + slots[slotName].appendChild(node); + } else { + $template.appendChild(node); + } + }); + + // Check for required slots that were not filled + forEach(filledSlots, function(filled, slotName) { + if (!filled) { + throw $compileMinErr('reqslot', 'Required transclusion slot `{0}` was not filled.', slotName); + } + }); + + for (var slotName in slots) { + if (slots[slotName]) { + // Only define a transclusion function if the slot was filled + var slotCompileNodes = jqLite(slots[slotName].childNodes); + slots[slotName] = compilationGenerator(mightHaveMultipleTransclusionError, slotCompileNodes, transcludeFn); + } + } + + $template = jqLite($template.childNodes); + } + $compileNode.empty(); // clear contents - childTranscludeFn = compile($template, transcludeFn); + childTranscludeFn = compilationGenerator(mightHaveMultipleTransclusionError, $template, transcludeFn, undefined, + undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope}); + childTranscludeFn.$$slots = slots; } } if (directive.template) { + hasTemplate = true; assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; @@ -6289,13 +10459,13 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (jqLiteIsTextNode(directiveValue)) { $template = []; } else { - $template = jqLite(directiveValue); + $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue))); } compileNode = $template[0]; - if ($template.length != 1 || compileNode.nodeType !== 1) { + if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { throw $compileMinErr('tplrt', - "Template for directive '{0}' must have exactly one root element. {1}", + 'Template for directive \'{0}\' must have exactly one root element. {1}', directiveName, ''); } @@ -6311,8 +10481,11 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs); var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1)); - if (newIsolateScopeDirective) { - markDirectivesAsIsolate(templateDirectives); + if (newIsolateScopeDirective || newScopeDirective) { + // The original directive caused the current element to be replaced but this element + // also needs to have a new scope, so we need to tell the template directives + // that they would need to get their scope from further up, if they require transclusion + markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective); } directives = directives.concat(templateDirectives).concat(unprocessedDirectives); mergeTemplateAttributes(templateAttrs, newTemplateAttrs); @@ -6324,6 +10497,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { } if (directive.templateUrl) { + hasTemplate = true; assertNoDuplicate('template', templateDirective, directive, $compileNode); templateDirective = directive; @@ -6331,9 +10505,11 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { replaceDirective = directive; } + // eslint-disable-next-line no-func-assign nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode, - templateAttrs, jqCollection, childTranscludeFn, preLinkFns, postLinkFns, { + templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, { controllerDirectives: controllerDirectives, + newScopeDirective: (newScopeDirective !== directive) && newScopeDirective, newIsolateScopeDirective: newIsolateScopeDirective, templateDirective: templateDirective, nonTlbTranscludeDirective: nonTlbTranscludeDirective @@ -6342,10 +10518,11 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { } else if (directive.compile) { try { linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn); + var context = directive.$$originalDirective || directive; if (isFunction(linkFn)) { - addLinkFns(null, linkFn, attrStart, attrEnd); + addLinkFns(null, bind(context, linkFn), attrStart, attrEnd); } else if (linkFn) { - addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd); + addLinkFns(bind(context, linkFn.pre), bind(context, linkFn.post), attrStart, attrEnd); } } catch (e) { $exceptionHandler(e, startingTag($compileNode)); @@ -6360,7 +10537,10 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { } nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true; - nodeLinkFn.transclude = hasTranscludeDirective && childTranscludeFn; + nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective; + nodeLinkFn.templateOnThisElement = hasTemplate; + nodeLinkFn.transclude = childTranscludeFn; + previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective; // might be normal or delayed nodeLinkFn depending on if templateUrl is present @@ -6372,6 +10552,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (pre) { if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd); pre.require = directive.require; + pre.directiveName = directiveName; if (newIsolateScopeDirective === directive || directive.$$isolateScope) { pre = cloneAndAnnotateFn(pre, {isolateScope: true}); } @@ -6380,6 +10561,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (post) { if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd); post.require = directive.require; + post.directiveName = directiveName; if (newIsolateScopeDirective === directive || directive.$$isolateScope) { post = cloneAndAnnotateFn(post, {isolateScope: true}); } @@ -6387,180 +10569,113 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { } } - - function getControllers(require, $element, elementControllers) { - var value, retrievalMethod = 'data', optional = false; - if (isString(require)) { - while((value = require.charAt(0)) == '^' || value == '?') { - require = require.substr(1); - if (value == '^') { - retrievalMethod = 'inheritedData'; - } - optional = optional || value == '?'; - } - value = null; - - if (elementControllers && retrievalMethod === 'data') { - value = elementControllers[require]; - } - value = value || $element[retrievalMethod]('$' + require + 'Controller'); - - if (!value && !optional) { - throw $compileMinErr('ctreq', - "Controller '{0}', required by directive '{1}', can't be found!", - require, directiveName); - } - return value; - } else if (isArray(require)) { - value = []; - forEach(require, function(require) { - value.push(getControllers(require, $element, elementControllers)); - }); - } - return value; - } - - function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { - var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn; + var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element, + attrs, scopeBindingInfo; if (compileNode === linkNode) { attrs = templateAttrs; + $element = templateAttrs.$$element; } else { - attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr)); + $element = jqLite(linkNode); + attrs = new Attributes($element, templateAttrs); } - $element = attrs.$$element; + controllerScope = scope; if (newIsolateScopeDirective) { - var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/; - var $linkNode = jqLite(linkNode); - isolateScope = scope.$new(true); + } else if (newScopeDirective) { + controllerScope = scope.$parent; + } - if (templateDirective && (templateDirective === newIsolateScopeDirective.$$originalDirective)) { - $linkNode.data('$isolateScope', isolateScope) ; - } else { - $linkNode.data('$isolateScopeNoTemplate', isolateScope); - } - - - - safeAddClass($linkNode, 'ng-isolate-scope'); - - forEach(newIsolateScopeDirective.scope, function(definition, scopeName) { - var match = definition.match(LOCAL_REGEXP) || [], - attrName = match[3] || scopeName, - optional = (match[2] == '?'), - mode = match[1], // @, =, or & - lastValue, - parentGet, parentSet, compare; + if (boundTranscludeFn) { + // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn` + // is later passed as `parentBoundTranscludeFn` to `publicLinkFn` + transcludeFn = controllersBoundTransclude; + transcludeFn.$$boundTransclude = boundTranscludeFn; + // expose the slots on the `$transclude` function + transcludeFn.isSlotFilled = function(slotName) { + return !!boundTranscludeFn.$$slots[slotName]; + }; + } - isolateScope.$$isolateBindings[scopeName] = mode + attrName; + if (controllerDirectives) { + elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective); + } - switch (mode) { + if (newIsolateScopeDirective) { + // Initialize isolate scope bindings for new isolate scope directive. + compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective || + templateDirective === newIsolateScopeDirective.$$originalDirective))); + compile.$$addScopeClass($element, true); + isolateScope.$$isolateBindings = + newIsolateScopeDirective.$$isolateBindings; + scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope, + isolateScope.$$isolateBindings, + newIsolateScopeDirective); + if (scopeBindingInfo.removeWatches) { + isolateScope.$on('$destroy', scopeBindingInfo.removeWatches); + } + } - case '@': - attrs.$observe(attrName, function(value) { - isolateScope[scopeName] = value; - }); - attrs.$$observers[attrName].$$scope = scope; - if( attrs[attrName] ) { - // If the attribute has been provided then we trigger an interpolation to ensure - // the value is there for use in the link fn - isolateScope[scopeName] = $interpolate(attrs[attrName])(scope); - } - break; + // Initialize bindToController bindings + for (var name in elementControllers) { + var controllerDirective = controllerDirectives[name]; + var controller = elementControllers[name]; + var bindings = controllerDirective.$$bindings.bindToController; - case '=': - if (optional && !attrs[attrName]) { - return; - } - parentGet = $parse(attrs[attrName]); - if (parentGet.literal) { - compare = equals; - } else { - compare = function(a,b) { return a === b; }; - } - parentSet = parentGet.assign || function() { - // reset the change, or we will throw this exception on every $digest - lastValue = isolateScope[scopeName] = parentGet(scope); - throw $compileMinErr('nonassign', - "Expression '{0}' used with directive '{1}' is non-assignable!", - attrs[attrName], newIsolateScopeDirective.name); - }; - lastValue = isolateScope[scopeName] = parentGet(scope); - isolateScope.$watch(function parentValueWatch() { - var parentValue = parentGet(scope); - if (!compare(parentValue, isolateScope[scopeName])) { - // we are out of sync and need to copy - if (!compare(parentValue, lastValue)) { - // parent changed and it has precedence - isolateScope[scopeName] = parentValue; - } else { - // if the parent can be assigned then do so - parentSet(scope, parentValue = isolateScope[scopeName]); - } - } - return lastValue = parentValue; - }, null, parentGet.literal); - break; - - case '&': - parentGet = $parse(attrs[attrName]); - isolateScope[scopeName] = function(locals) { - return parentGet(scope, locals); - }; - break; + controller.instance = controller(); + $element.data('$' + controllerDirective.name + 'Controller', controller.instance); + controller.bindingInfo = + initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective); + } - default: - throw $compileMinErr('iscp', - "Invalid isolate scope definition for directive '{0}'." + - " Definition: {... {1}: '{2}' ...}", - newIsolateScopeDirective.name, scopeName, definition); - } - }); - } - transcludeFn = boundTranscludeFn && controllersBoundTransclude; - if (controllerDirectives) { - forEach(controllerDirectives, function(directive) { - var locals = { - $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, - $element: $element, - $attrs: attrs, - $transclude: transcludeFn - }, controllerInstance; - - controller = directive.controller; - if (controller == '@') { - controller = attrs[directive.name]; - } + // Bind the required controllers to the controller, if `require` is an object and `bindToController` is truthy + forEach(controllerDirectives, function(controllerDirective, name) { + var require = controllerDirective.require; + if (controllerDirective.bindToController && !isArray(require) && isObject(require)) { + extend(elementControllers[name].instance, getControllers(name, require, $element, elementControllers)); + } + }); - controllerInstance = $controller(controller, locals); - // For directives with element transclusion the element is a comment, - // but jQuery .data doesn't support attaching data to comment nodes as it's hard to - // clean up (http://bugs.jquery.com/ticket/8335). - // Instead, we save the controllers for the element in a local hash and attach to .data - // later, once we have the actual element. - elementControllers[directive.name] = controllerInstance; - if (!hasElementTranscludeDirective) { - $element.data('$' + directive.name + 'Controller', controllerInstance); + // Handle the init and destroy lifecycle hooks on all controllers that have them + forEach(elementControllers, function(controller) { + var controllerInstance = controller.instance; + if (isFunction(controllerInstance.$onChanges)) { + try { + controllerInstance.$onChanges(controller.bindingInfo.initialChanges); + } catch (e) { + $exceptionHandler(e); } - - if (directive.controllerAs) { - locals.$scope[directive.controllerAs] = controllerInstance; + } + if (isFunction(controllerInstance.$onInit)) { + try { + controllerInstance.$onInit(); + } catch (e) { + $exceptionHandler(e); } - }); - } + } + if (isFunction(controllerInstance.$doCheck)) { + controllerScope.$watch(function() { controllerInstance.$doCheck(); }); + controllerInstance.$doCheck(); + } + if (isFunction(controllerInstance.$onDestroy)) { + controllerScope.$on('$destroy', function callOnDestroyHook() { + controllerInstance.$onDestroy(); + }); + } + }); // PRELINKING - for(i = 0, ii = preLinkFns.length; i < ii; i++) { - try { - linkFn = preLinkFns[i]; - linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs, - linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn); - } catch (e) { - $exceptionHandler(e, startingTag($element)); - } + for (i = 0, ii = preLinkFns.length; i < ii; i++) { + linkFn = preLinkFns[i]; + invokeLinkFn(linkFn, + linkFn.isolateScope ? isolateScope : scope, + $element, + attrs, + linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), + transcludeFn + ); } // RECURSION @@ -6570,25 +10685,38 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) { scopeToChild = isolateScope; } - childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); + if (childLinkFn) { + childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn); + } // POSTLINKING - for(i = postLinkFns.length - 1; i >= 0; i--) { - try { - linkFn = postLinkFns[i]; - linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs, - linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn); - } catch (e) { - $exceptionHandler(e, startingTag($element)); - } + for (i = postLinkFns.length - 1; i >= 0; i--) { + linkFn = postLinkFns[i]; + invokeLinkFn(linkFn, + linkFn.isolateScope ? isolateScope : scope, + $element, + attrs, + linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), + transcludeFn + ); } + // Trigger $postLink lifecycle hooks + forEach(elementControllers, function(controller) { + var controllerInstance = controller.instance; + if (isFunction(controllerInstance.$postLink)) { + controllerInstance.$postLink(); + } + }); + // This is the function that is injected as `$transclude`. - function controllersBoundTransclude(scope, cloneAttachFn) { + // Note: all arguments are optional! + function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) { var transcludeControllers; - - // no scope passed - if (arguments.length < 2) { + // No scope passed in: + if (!isScope(scope)) { + slotName = futureParentElement; + futureParentElement = cloneAttachFn; cloneAttachFn = scope; scope = undefined; } @@ -6596,16 +10724,118 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (hasElementTranscludeDirective) { transcludeControllers = elementControllers; } - - return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers); + if (!futureParentElement) { + futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element; + } + if (slotName) { + // slotTranscludeFn can be one of three things: + // * a transclude function - a filled slot + // * `null` - an optional slot that was not filled + // * `undefined` - a slot that was not declared (i.e. invalid) + var slotTranscludeFn = boundTranscludeFn.$$slots[slotName]; + if (slotTranscludeFn) { + return slotTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild); + } else if (isUndefined(slotTranscludeFn)) { + throw $compileMinErr('noslot', + 'No parent directive that requires a transclusion with slot name "{0}". ' + + 'Element: {1}', + slotName, startingTag($element)); + } + } else { + return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild); + } } } } - function markDirectivesAsIsolate(directives) { - // mark all directives as needing isolate scope. + function getControllers(directiveName, require, $element, elementControllers) { + var value; + + if (isString(require)) { + var match = require.match(REQUIRE_PREFIX_REGEXP); + var name = require.substring(match[0].length); + var inheritType = match[1] || match[3]; + var optional = match[2] === '?'; + + //If only parents then start at the parent element + if (inheritType === '^^') { + $element = $element.parent(); + //Otherwise attempt getting the controller from elementControllers in case + //the element is transcluded (and has no data) and to avoid .data if possible + } else { + value = elementControllers && elementControllers[name]; + value = value && value.instance; + } + + if (!value) { + var dataName = '$' + name + 'Controller'; + + if (inheritType === '^^' && $element[0] && $element[0].nodeType === NODE_TYPE_DOCUMENT) { + // inheritedData() uses the documentElement when it finds the document, so we would + // require from the element itself. + value = null; + } else { + value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName); + } + } + + if (!value && !optional) { + throw $compileMinErr('ctreq', + 'Controller \'{0}\', required by directive \'{1}\', can\'t be found!', + name, directiveName); + } + } else if (isArray(require)) { + value = []; + for (var i = 0, ii = require.length; i < ii; i++) { + value[i] = getControllers(directiveName, require[i], $element, elementControllers); + } + } else if (isObject(require)) { + value = {}; + forEach(require, function(controller, property) { + value[property] = getControllers(directiveName, controller, $element, elementControllers); + }); + } + + return value || null; + } + + function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective) { + var elementControllers = createMap(); + for (var controllerKey in controllerDirectives) { + var directive = controllerDirectives[controllerKey]; + var locals = { + $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope, + $element: $element, + $attrs: attrs, + $transclude: transcludeFn + }; + + var controller = directive.controller; + if (controller === '@') { + controller = attrs[directive.name]; + } + + var controllerInstance = $controller(controller, locals, true, directive.controllerAs); + + // For directives with element transclusion the element is a comment. + // In this case .data will not attach any data. + // Instead, we save the controllers for the element in a local hash and attach to .data + // later, once we have the actual element. + elementControllers[directive.name] = controllerInstance; + $element.data('$' + directive.name + 'Controller', controllerInstance.instance); + } + return elementControllers; + } + + // Depending upon the context in which a directive finds itself it might need to have a new isolated + // or child scope created. For instance: + // * if the directive has been pulled into a template because another directive with a higher priority + // asked for element transclusion + // * if the directive itself asks for transclusion but it is at the root of a template and the original + // element was replaced. See https://github.com/angular/angular.js/issues/12936 + function markDirectiveScope(directives, isolateScope, newScope) { for (var j = 0, jj = directives.length; j < jj; j++) { - directives[j] = inherit(directives[j], {$$isolateScope: true}); + directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope}); } } @@ -6628,25 +10858,51 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (name === ignoreDirective) return null; var match = null; if (hasDirectives.hasOwnProperty(name)) { - for(var directive, directives = $injector.get(name + Suffix), - i = 0, ii = directives.length; i directive.priority) && - directive.restrict.indexOf(location) != -1) { - if (startAttrName) { - directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); + for (var directive, directives = $injector.get(name + Suffix), + i = 0, ii = directives.length; i < ii; i++) { + directive = directives[i]; + if ((isUndefined(maxPriority) || maxPriority > directive.priority) && + directive.restrict.indexOf(location) !== -1) { + if (startAttrName) { + directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); + } + if (!directive.$$bindings) { + var bindings = directive.$$bindings = + parseDirectiveBindings(directive, directive.name); + if (isObject(bindings.isolateScope)) { + directive.$$isolateBindings = bindings.isolateScope; } - tDirectives.push(directive); - match = directive; } - } catch(e) { $exceptionHandler(e); } + tDirectives.push(directive); + match = directive; + } } } return match; } + /** + * looks up the directive and returns true if it is a multi-element directive, + * and therefore requires DOM nodes between -start and -end markers to be grouped + * together. + * + * @param {string} name name of the directive to look up. + * @returns true if directive was registered as multi-element. + */ + function directiveIsMultiElement(name) { + if (hasDirectives.hasOwnProperty(name)) { + for (var directive, directives = $injector.get(name + Suffix), + i = 0, ii = directives.length; i < ii; i++) { + directive = directives[i]; + if (directive.multiElement) { + return true; + } + } + } + return false; + } + /** * When the element is replaced with HTML template then the new attributes * on the template need to be merged with the existing attributes in the DOM. @@ -6657,14 +10913,17 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { */ function mergeTemplateAttributes(dst, src) { var srcAttr = src.$attr, - dstAttr = dst.$attr, - $element = dst.$$element; + dstAttr = dst.$attr; // reapply the old attributes to the new element forEach(dst, function(value, key) { - if (key.charAt(0) != '$') { - if (src[key]) { - value += (key === 'style' ? ';' : ' ') + src[key]; + if (key.charAt(0) !== '$') { + if (src[key] && src[key] !== value) { + if (value.length) { + value += (key === 'style' ? ';' : ' ') + src[key]; + } else { + value = src[key]; + } } dst.$set(key, value, true, srcAttr[key]); } @@ -6672,18 +10931,16 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { // copy the new attributes on the old attrs object forEach(src, function(value, key) { - if (key == 'class') { - safeAddClass($element, value); - dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value; - } else if (key == 'style') { - $element.attr('style', $element.attr('style') + ';' + value); - dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value; - // `dst` will never contain hasOwnProperty as DOM parser won't let it. - // You will get an "InvalidCharacterError: DOM Exception 5" error if you - // have an attribute like "has-own-property" or "data-has-own-property", etc. - } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) { + // Check if we already set this attribute in the loop above. + // `dst` will never contain hasOwnProperty as DOM parser won't let it. + // You will get an "InvalidCharacterError: DOM Exception 5" error if you + // have an attribute like "has-own-property" or "data-has-own-property", etc. + if (!dst.hasOwnProperty(key) && key.charAt(0) !== '$') { dst[key] = value; - dstAttr[key] = srcAttr[key]; + + if (key !== 'class' && key !== 'style') { + dstAttr[key] = srcAttr[key]; + } } }); } @@ -6696,18 +10953,18 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { afterTemplateChildLinkFn, beforeTemplateCompileNode = $compileNode[0], origAsyncDirective = directives.shift(), - // The fact that we have to copy and patch the directive seems wrong! - derivedSyncDirective = extend({}, origAsyncDirective, { + derivedSyncDirective = inherit(origAsyncDirective, { templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective }), templateUrl = (isFunction(origAsyncDirective.templateUrl)) ? origAsyncDirective.templateUrl($compileNode, tAttrs) - : origAsyncDirective.templateUrl; + : origAsyncDirective.templateUrl, + templateNamespace = origAsyncDirective.templateNamespace; $compileNode.empty(); - $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}). - success(function(content) { + $templateRequest(templateUrl) + .then(function(content) { var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn; content = denormalizeTemplate(content); @@ -6716,13 +10973,13 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (jqLiteIsTextNode(content)) { $template = []; } else { - $template = jqLite(content); + $template = removeComments(wrapTemplate(templateNamespace, trim(content))); } compileNode = $template[0]; - if ($template.length != 1 || compileNode.nodeType !== 1) { + if ($template.length !== 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { throw $compileMinErr('tplrt', - "Template for directive '{0}' must have exactly one root element. {1}", + 'Template for directive \'{0}\' must have exactly one root element. {1}', origAsyncDirective.name, templateUrl); } @@ -6731,7 +10988,9 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs); if (isObject(origAsyncDirective.scope)) { - markDirectivesAsIsolate(templateDirectives); + // the original directive that caused the template to be loaded async required + // an isolate scope + markDirectiveScope(templateDirectives, true); } directives = templateDirectives.concat(directives); mergeTemplateAttributes(tAttrs, tempTemplateAttrs); @@ -6746,20 +11005,21 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns, previousCompileContext); forEach($rootElement, function(node, i) { - if (node == compileNode) { + if (node === compileNode) { $rootElement[i] = $compileNode[0]; } }); afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn); - - while(linkQueue.length) { + while (linkQueue.length) { var scope = linkQueue.shift(), beforeTemplateLinkNode = linkQueue.shift(), linkRootElement = linkQueue.shift(), boundTranscludeFn = linkQueue.shift(), linkNode = $compileNode[0]; + if (scope.$$destroyed) continue; + if (beforeTemplateLinkNode !== beforeTemplateCompileNode) { var oldClasses = beforeTemplateLinkNode.className; @@ -6768,14 +11028,13 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { // it was cloned therefore we have to clone as well. linkNode = jqLiteClone(compileNode); } - replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode); // Copy in CSS classes from original node safeAddClass(jqLite(linkNode), oldClasses); } - if (afterTemplateNodeLinkFn.transclude) { - childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude); + if (afterTemplateNodeLinkFn.transcludeOnThisElement) { + childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); } else { childBoundTranscludeFn = boundTranscludeFn; } @@ -6783,19 +11042,25 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { childBoundTranscludeFn); } linkQueue = null; - }). - error(function(response, code, headers, config) { - throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url); + }).catch(function(error) { + if (isError(error)) { + $exceptionHandler(error); + } }); return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) { + var childBoundTranscludeFn = boundTranscludeFn; + if (scope.$$destroyed) return; if (linkQueue) { - linkQueue.push(scope); - linkQueue.push(node); - linkQueue.push(rootElement); - linkQueue.push(boundTranscludeFn); + linkQueue.push(scope, + node, + rootElement, + childBoundTranscludeFn); } else { - afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, boundTranscludeFn); + if (afterTemplateNodeLinkFn.transcludeOnThisElement) { + childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn); + } + afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn); } }; } @@ -6811,11 +11076,18 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { return a.index - b.index; } - function assertNoDuplicate(what, previousDirective, directive, element) { + + function wrapModuleNameIfDefined(moduleName) { + return moduleName ? + (' (module: ' + moduleName + ')') : + ''; + } + if (previousDirective) { - throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}', - previousDirective.name, directive.name, what, startingTag(element)); + throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}', + previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName), + directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element)); } } @@ -6825,72 +11097,175 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (interpolateFn) { directives.push({ priority: 0, - compile: valueFn(function textInterpolateLinkFn(scope, node) { - var parent = node.parent(), - bindings = parent.data('$binding') || []; - bindings.push(interpolateFn); - safeAddClass(parent.data('$binding', bindings), 'ng-binding'); - scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { - node[0].nodeValue = value; - }); - }) + compile: function textInterpolateCompileFn(templateNode) { + var templateNodeParent = templateNode.parent(), + hasCompileParent = !!templateNodeParent.length; + + // When transcluding a template that has bindings in the root + // we don't have a parent and thus need to add the class during linking fn. + if (hasCompileParent) compile.$$addBindingClass(templateNodeParent); + + return function textInterpolateLinkFn(scope, node) { + var parent = node.parent(); + if (!hasCompileParent) compile.$$addBindingClass(parent); + compile.$$addBindingInfo(parent, interpolateFn.expressions); + scope.$watch(interpolateFn, function interpolateFnWatchAction(value) { + node[0].nodeValue = value; + }); + }; + } }); } } - function getTrustedContext(node, attrNormalizedName) { - if (attrNormalizedName == "srcdoc") { + function wrapTemplate(type, template) { + type = lowercase(type || 'html'); + switch (type) { + case 'svg': + case 'math': + var wrapper = window.document.createElement('div'); + wrapper.innerHTML = '<' + type + '>' + template + ''; + return wrapper.childNodes[0].childNodes; + default: + return template; + } + } + + + function getTrustedAttrContext(nodeName, attrNormalizedName) { + if (attrNormalizedName === 'srcdoc') { return $sce.HTML; } - var tag = nodeName_(node); - // maction[xlink:href] can source SVG. It's not limited to . - if (attrNormalizedName == "xlinkHref" || - (tag == "FORM" && attrNormalizedName == "action") || - (tag != "IMG" && (attrNormalizedName == "src" || - attrNormalizedName == "ngSrc"))) { + // All nodes with src attributes require a RESOURCE_URL value, except for + // img and various html5 media nodes, which require the MEDIA_URL context. + if (attrNormalizedName === 'src' || attrNormalizedName === 'ngSrc') { + if (['img', 'video', 'audio', 'source', 'track'].indexOf(nodeName) === -1) { + return $sce.RESOURCE_URL; + } + return $sce.MEDIA_URL; + } else if (attrNormalizedName === 'xlinkHref') { + // Some xlink:href are okay, most aren't + if (nodeName === 'image') return $sce.MEDIA_URL; + if (nodeName === 'a') return $sce.URL; return $sce.RESOURCE_URL; + } else if ( + // Formaction + (nodeName === 'form' && attrNormalizedName === 'action') || + // If relative URLs can go where they are not expected to, then + // all sorts of trust issues can arise. + (nodeName === 'base' && attrNormalizedName === 'href') || + // links can be stylesheets or imports, which can run script in the current origin + (nodeName === 'link' && attrNormalizedName === 'href') + ) { + return $sce.RESOURCE_URL; + } else if (nodeName === 'a' && (attrNormalizedName === 'href' || + attrNormalizedName === 'ngHref')) { + return $sce.URL; + } + } + + function getTrustedPropContext(nodeName, propNormalizedName) { + var prop = propNormalizedName.toLowerCase(); + return PROP_CONTEXTS[nodeName + '|' + prop] || PROP_CONTEXTS['*|' + prop]; + } + + function sanitizeSrcsetPropertyValue(value) { + return sanitizeSrcset($sce.valueOf(value), 'ng-prop-srcset'); + } + function addPropertyDirective(node, directives, attrName, propName) { + if (EVENT_HANDLER_ATTR_REGEXP.test(propName)) { + throw $compileMinErr('nodomevents', 'Property bindings for HTML DOM event properties are disallowed'); + } + + var nodeName = nodeName_(node); + var trustedContext = getTrustedPropContext(nodeName, propName); + + var sanitizer = identity; + // Sanitize img[srcset] + source[srcset] values. + if (propName === 'srcset' && (nodeName === 'img' || nodeName === 'source')) { + sanitizer = sanitizeSrcsetPropertyValue; + } else if (trustedContext) { + sanitizer = $sce.getTrusted.bind($sce, trustedContext); } + + directives.push({ + priority: 100, + compile: function ngPropCompileFn(_, attr) { + var ngPropGetter = $parse(attr[attrName]); + var ngPropWatch = $parse(attr[attrName], function sceValueOf(val) { + // Unwrap the value to compare the actual inner safe value, not the wrapper object. + return $sce.valueOf(val); + }); + + return { + pre: function ngPropPreLinkFn(scope, $element) { + function applyPropValue() { + var propValue = ngPropGetter(scope); + $element[0][propName] = sanitizer(propValue); + } + + applyPropValue(); + scope.$watch(ngPropWatch, applyPropValue); + } + }; + } + }); + } + + function addEventDirective(directives, attrName, eventName) { + directives.push( + createEventDirective($parse, $rootScope, $exceptionHandler, attrName, eventName, /*forceAsync=*/false) + ); } + function addAttrInterpolateDirective(node, directives, value, name, isNgAttr) { + var nodeName = nodeName_(node); + var trustedContext = getTrustedAttrContext(nodeName, name); + var mustHaveExpression = !isNgAttr; + var allOrNothing = ALL_OR_NOTHING_ATTRS[name] || isNgAttr; - function addAttrInterpolateDirective(node, directives, value, name) { - var interpolateFn = $interpolate(value, true); + var interpolateFn = $interpolate(value, mustHaveExpression, trustedContext, allOrNothing); // no interpolation found -> ignore if (!interpolateFn) return; - - if (name === "multiple" && nodeName_(node) === "SELECT") { - throw $compileMinErr("selmulti", - "Binding to the 'multiple' attribute is not supported. Element: {0}", + if (name === 'multiple' && nodeName === 'select') { + throw $compileMinErr('selmulti', + 'Binding to the \'multiple\' attribute is not supported. Element: {0}', startingTag(node)); } + if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { + throw $compileMinErr('nodomevents', 'Interpolations for HTML DOM event attributes are disallowed'); + } + directives.push({ priority: 100, compile: function() { return { pre: function attrInterpolatePreLinkFn(scope, element, attr) { - var $$observers = (attr.$$observers || (attr.$$observers = {})); - - if (EVENT_HANDLER_ATTR_REGEXP.test(name)) { - throw $compileMinErr('nodomevents', - "Interpolations for HTML DOM event attributes are disallowed. Please use the " + - "ng- versions (such as ng-click instead of onclick) instead."); + var $$observers = (attr.$$observers || (attr.$$observers = createMap())); + + // If the attribute has changed since last $interpolate()ed + var newValue = attr[name]; + if (newValue !== value) { + // we need to interpolate again since the attribute value has been updated + // (e.g. by another directive's compile function) + // ensure unset/empty values make interpolateFn falsy + interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing); + value = newValue; } - // we need to interpolate again, in case the attribute value has been updated - // (e.g. by another directive's compile function) - interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name)); - // if attribute was updated so that there is no interpolation going on we don't want to // register any observers if (!interpolateFn) return; - // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the - // actual attr value + // initialize attr object so that it's ready in case we need the value for isolate + // scope initialization, otherwise the value would not be available from isolate + // directive's linking fn during linking phase attr[name] = interpolateFn(scope); + ($$observers[name] || ($$observers[name] = [])).$$inter = true; (attr.$$observers && attr.$$observers[name].$$scope || scope). $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) { @@ -6900,7 +11275,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { //skip animations when the first digest occurs (when //both the new and the old values are the same) since //the CSS classes are the non-interpolated values - if(name === 'class' && newValue != oldValue) { + if (name === 'class' && newValue !== oldValue) { attr.$updateClass(newValue, oldValue); } else { attr.$set(name, newValue); @@ -6930,8 +11305,8 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { i, ii; if ($rootElement) { - for(i = 0, ii = $rootElement.length; i < ii; i++) { - if ($rootElement[i] == firstElementToRemove) { + for (i = 0, ii = $rootElement.length; i < ii; i++) { + if ($rootElement[i] === firstElementToRemove) { $rootElement[i++] = newNode; for (var j = i, j2 = j + removeCount - 1, jj = $rootElement.length; @@ -6943,6 +11318,13 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { } } $rootElement.length -= removeCount - 1; + + // If the replaced element is also the jQuery .context then replace it + // .context is a deprecated jQuery api, so we should set it only when jQuery set it + // http://api.jquery.com/context/ + if ($rootElement.context === firstElementToRemove) { + $rootElement.context = newNode; + } break; } } @@ -6951,16 +11333,34 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (parent) { parent.replaceChild(newNode, firstElementToRemove); } - var fragment = document.createDocumentFragment(); - fragment.appendChild(firstElementToRemove); - newNode[jqLite.expando] = firstElementToRemove[jqLite.expando]; - for (var k = 1, kk = elementsToRemove.length; k < kk; k++) { - var element = elementsToRemove[k]; - jqLite(element).remove(); // must do this way to clean up expando - fragment.appendChild(element); - delete elementsToRemove[k]; + + // Append all the `elementsToRemove` to a fragment. This will... + // - remove them from the DOM + // - allow them to still be traversed with .nextSibling + // - allow a single fragment.qSA to fetch all elements being removed + var fragment = window.document.createDocumentFragment(); + for (i = 0; i < removeCount; i++) { + fragment.appendChild(elementsToRemove[i]); + } + + if (jqLite.hasData(firstElementToRemove)) { + // Copy over user data (that includes AngularJS's $scope etc.). Don't copy private + // data here because there's no public interface in jQuery to do that and copying over + // event listeners (which is the main use of private data) wouldn't work anyway. + jqLite.data(newNode, jqLite.data(firstElementToRemove)); + + // Remove $destroy event listeners from `firstElementToRemove` + jqLite(firstElementToRemove).off('$destroy'); } + // Cleanup any data/listeners on the elements and children. + // This includes invoking the $destroy event on any elements with listeners. + jqLite.cleanData(fragment.querySelectorAll('*')); + + // Update the jqLite collection to only contain the `newNode` + for (i = 1; i < removeCount; i++) { + delete elementsToRemove[i]; + } elementsToRemove[0] = newNode; elementsToRemove.length = 1; } @@ -6969,23 +11369,216 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { function cloneAndAnnotateFn(fn, annotation) { return extend(function() { return fn.apply(null, arguments); }, fn, annotation); } + + + function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) { + try { + linkFn(scope, $element, attrs, controllers, transcludeFn); + } catch (e) { + $exceptionHandler(e, startingTag($element)); + } + } + + function strictBindingsCheck(attrName, directiveName) { + if (strictComponentBindingsEnabled) { + throw $compileMinErr('missingattr', + 'Attribute \'{0}\' of \'{1}\' is non-optional and must be set!', + attrName, directiveName); + } + } + + // Set up $watches for isolate scope and controller bindings. + function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) { + var removeWatchCollection = []; + var initialChanges = {}; + var changes; + + forEach(bindings, function initializeBinding(definition, scopeName) { + var attrName = definition.attrName, + optional = definition.optional, + mode = definition.mode, // @, =, <, or & + lastValue, + parentGet, parentSet, compare, removeWatch; + + switch (mode) { + + case '@': + if (!optional && !hasOwnProperty.call(attrs, attrName)) { + strictBindingsCheck(attrName, directive.name); + destination[scopeName] = attrs[attrName] = undefined; + + } + removeWatch = attrs.$observe(attrName, function(value) { + if (isString(value) || isBoolean(value)) { + var oldValue = destination[scopeName]; + recordChanges(scopeName, value, oldValue); + destination[scopeName] = value; + } + }); + attrs.$$observers[attrName].$$scope = scope; + lastValue = attrs[attrName]; + if (isString(lastValue)) { + // If the attribute has been provided then we trigger an interpolation to ensure + // the value is there for use in the link fn + destination[scopeName] = $interpolate(lastValue)(scope); + } else if (isBoolean(lastValue)) { + // If the attributes is one of the BOOLEAN_ATTR then AngularJS will have converted + // the value to boolean rather than a string, so we special case this situation + destination[scopeName] = lastValue; + } + initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]); + removeWatchCollection.push(removeWatch); + break; + + case '=': + if (!hasOwnProperty.call(attrs, attrName)) { + if (optional) break; + strictBindingsCheck(attrName, directive.name); + attrs[attrName] = undefined; + } + if (optional && !attrs[attrName]) break; + + parentGet = $parse(attrs[attrName]); + if (parentGet.literal) { + compare = equals; + } else { + compare = simpleCompare; + } + parentSet = parentGet.assign || function() { + // reset the change, or we will throw this exception on every $digest + lastValue = destination[scopeName] = parentGet(scope); + throw $compileMinErr('nonassign', + 'Expression \'{0}\' in attribute \'{1}\' used with directive \'{2}\' is non-assignable!', + attrs[attrName], attrName, directive.name); + }; + lastValue = destination[scopeName] = parentGet(scope); + var parentValueWatch = function parentValueWatch(parentValue) { + if (!compare(parentValue, destination[scopeName])) { + // we are out of sync and need to copy + if (!compare(parentValue, lastValue)) { + // parent changed and it has precedence + destination[scopeName] = parentValue; + } else { + // if the parent can be assigned then do so + parentSet(scope, parentValue = destination[scopeName]); + } + } + lastValue = parentValue; + return lastValue; + }; + parentValueWatch.$stateful = true; + if (definition.collection) { + removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch); + } else { + removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal); + } + removeWatchCollection.push(removeWatch); + break; + + case '<': + if (!hasOwnProperty.call(attrs, attrName)) { + if (optional) break; + strictBindingsCheck(attrName, directive.name); + attrs[attrName] = undefined; + } + if (optional && !attrs[attrName]) break; + + parentGet = $parse(attrs[attrName]); + var isLiteral = parentGet.literal; + + var initialValue = destination[scopeName] = parentGet(scope); + initialChanges[scopeName] = new SimpleChange(_UNINITIALIZED_VALUE, destination[scopeName]); + + removeWatch = scope[definition.collection ? '$watchCollection' : '$watch'](parentGet, function parentValueWatchAction(newValue, oldValue) { + if (oldValue === newValue) { + if (oldValue === initialValue || (isLiteral && equals(oldValue, initialValue))) { + return; + } + oldValue = initialValue; + } + recordChanges(scopeName, newValue, oldValue); + destination[scopeName] = newValue; + }); + + removeWatchCollection.push(removeWatch); + break; + + case '&': + if (!optional && !hasOwnProperty.call(attrs, attrName)) { + strictBindingsCheck(attrName, directive.name); + } + // Don't assign Object.prototype method to scope + parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop; + + // Don't assign noop to destination if expression is not valid + if (parentGet === noop && optional) break; + + destination[scopeName] = function(locals) { + return parentGet(scope, locals); + }; + break; + } + }); + + function recordChanges(key, currentValue, previousValue) { + if (isFunction(destination.$onChanges) && !simpleCompare(currentValue, previousValue)) { + // If we have not already scheduled the top level onChangesQueue handler then do so now + if (!onChangesQueue) { + scope.$$postDigest(flushOnChangesQueue); + onChangesQueue = []; + } + // If we have not already queued a trigger of onChanges for this controller then do so now + if (!changes) { + changes = {}; + onChangesQueue.push(triggerOnChangesHook); + } + // If the has been a change on this property already then we need to reuse the previous value + if (changes[key]) { + previousValue = changes[key].previousValue; + } + // Store this change + changes[key] = new SimpleChange(previousValue, currentValue); + } + } + + function triggerOnChangesHook() { + destination.$onChanges(changes); + // Now clear the changes so that we schedule onChanges when more changes arrive + changes = undefined; + } + + return { + initialChanges: initialChanges, + removeWatches: removeWatchCollection.length && function removeWatches() { + for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) { + removeWatchCollection[i](); + } + } + }; + } }]; } -var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i; +function SimpleChange(previous, current) { + this.previousValue = previous; + this.currentValue = current; +} +SimpleChange.prototype.isFirstChange = function() { return this.previousValue === _UNINITIALIZED_VALUE; }; + + +var PREFIX_REGEXP = /^((?:x|data)[:\-_])/i; +var SPECIAL_CHARS_REGEXP = /[:\-_]+(.)/g; + /** * Converts all accepted directives format into proper directive name. - * All of these will become 'myDirective': - * my:Directive - * my-directive - * x-my-directive - * data-my:directive - * - * Also there is special case for Moz prefix starting with upper case letter. * @param name Name to normalize */ function directiveNormalize(name) { - return camelCase(name.replace(PREFIX_REGEXP, '')); + return name + .replace(PREFIX_REGEXP, '') + .replace(SPECIAL_CHARS_REGEXP, function(_, letter, offset) { + return offset ? letter.toUpperCase() : letter; + }); } /** @@ -6995,23 +11588,27 @@ function directiveNormalize(name) { * @description * A shared object between directive compile / linking functions which contains normalized DOM * element attributes. The values reflect current binding state `{{ }}`. The normalization is - * needed since all of these are treated as equivalent in Angular: + * needed since all of these are treated as equivalent in AngularJS: * + * ``` * + * ``` */ /** * @ngdoc property * @name $compile.directive.Attributes#$attr - * @returns {object} A map of DOM element attribute names to the normalized name. This is - * needed to do reverse lookup from normalized name back to actual name. + * + * @description + * A map of DOM element attribute names to the normalized name. This is + * needed to do reverse lookup from normalized name back to actual name. */ /** * @ngdoc method * @name $compile.directive.Attributes#$set - * @function + * @kind function * * @description * Set DOM element attribute value. @@ -7034,7 +11631,7 @@ function nodesetLinkingFn( /* NodeList */ nodeList, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn -){} +) {} function directiveLinkingFn( /* nodesetLinkingFn */ nodesetLinkingFn, @@ -7042,7 +11639,7 @@ function directiveLinkingFn( /* Node */ node, /* Element */ rootElement, /* function(Function) */ boundTranscludeFn -){} +) {} function tokenDifference(str1, str2) { var values = '', @@ -7050,30 +11647,70 @@ function tokenDifference(str1, str2) { tokens2 = str2.split(/\s+/); outer: - for(var i = 0; i < tokens1.length; i++) { + for (var i = 0; i < tokens1.length; i++) { var token = tokens1[i]; - for(var j = 0; j < tokens2.length; j++) { - if(token == tokens2[j]) continue outer; + for (var j = 0; j < tokens2.length; j++) { + if (token === tokens2[j]) continue outer; } values += (values.length > 0 ? ' ' : '') + token; } return values; } +function removeComments(jqNodes) { + jqNodes = jqLite(jqNodes); + var i = jqNodes.length; + + if (i <= 1) { + return jqNodes; + } + + while (i--) { + var node = jqNodes[i]; + if (node.nodeType === NODE_TYPE_COMMENT || + (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) { + splice.call(jqNodes, i, 1); + } + } + return jqNodes; +} + +var $controllerMinErr = minErr('$controller'); + + +var CNTRL_REG = /^(\S+)(\s+as\s+([\w$]+))?$/; +function identifierForController(controller, ident) { + if (ident && isString(ident)) return ident; + if (isString(controller)) { + var match = CNTRL_REG.exec(controller); + if (match) return match[3]; + } +} + + /** * @ngdoc provider * @name $controllerProvider + * @this + * * @description - * The {@link ng.$controller $controller service} is used by Angular to create new + * The {@link ng.$controller $controller service} is used by AngularJS to create new * controllers. * * This provider allows controller registration via the * {@link ng.$controllerProvider#register register} method. */ function $ControllerProvider() { - var controllers = {}, - CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/; + var controllers = {}; + /** + * @ngdoc method + * @name $controllerProvider#has + * @param {string} name Controller name to check. + */ + this.has = function(name) { + return controllers.hasOwnProperty(name); + }; /** * @ngdoc method @@ -7092,8 +11729,7 @@ function $ControllerProvider() { } }; - - this.$get = ['$injector', '$window', function($injector, $window) { + this.$get = ['$injector', function($injector) { /** * @ngdoc service @@ -7106,7 +11742,10 @@ function $ControllerProvider() { * * * check if a controller with given name is registered via `$controllerProvider` * * check if evaluating the string on the current scope returns a constructor - * * check `window[constructor]` on the global `window` object + * + * The string can use the `controller as property` syntax, where the controller instance is published + * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this + * to work correctly. * * @param {Object} locals Injection locals for Controller. * @return {Object} Instance of given controller. @@ -7117,34 +11756,94 @@ function $ControllerProvider() { * It's just a simple call to {@link auto.$injector $injector}, but extracted into * a service, so that one can override this service with [BC version](https://gist.github.com/1649788). */ - return function(expression, locals) { + return function $controller(expression, locals, later, ident) { + // PRIVATE API: + // param `later` --- indicates that the controller's constructor is invoked at a later time. + // If true, $controller will allocate the object with the correct + // prototype chain, but will not invoke the controller until a returned + // callback is invoked. + // param `ident` --- An optional label which overrides the label parsed from the controller + // expression, if any. var instance, match, constructor, identifier; + later = later === true; + if (ident && isString(ident)) { + identifier = ident; + } - if(isString(expression)) { - match = expression.match(CNTRL_REG), - constructor = match[1], - identifier = match[3]; + if (isString(expression)) { + match = expression.match(CNTRL_REG); + if (!match) { + throw $controllerMinErr('ctrlfmt', + 'Badly formed controller string \'{0}\'. ' + + 'Must match `__name__ as __id__` or `__name__`.', expression); + } + constructor = match[1]; + identifier = identifier || match[3]; expression = controllers.hasOwnProperty(constructor) ? controllers[constructor] - : getter(locals.$scope, constructor, true) || getter($window, constructor, true); + : getter(locals.$scope, constructor, true); + + if (!expression) { + throw $controllerMinErr('ctrlreg', + 'The controller with the name \'{0}\' is not registered.', constructor); + } assertArgFn(expression, constructor, true); } - instance = $injector.instantiate(expression, locals); - - if (identifier) { - if (!(locals && typeof locals.$scope == 'object')) { - throw minErr('$controller')('noscp', - "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.", - constructor || expression.name, identifier); + if (later) { + // Instantiate controller later: + // This machinery is used to create an instance of the object before calling the + // controller's constructor itself. + // + // This allows properties to be added to the controller before the constructor is + // invoked. Primarily, this is used for isolate scope bindings in $compile. + // + // This feature is not intended for use by applications, and is thus not documented + // publicly. + // Object creation: http://jsperf.com/create-constructor/2 + var controllerPrototype = (isArray(expression) ? + expression[expression.length - 1] : expression).prototype; + instance = Object.create(controllerPrototype || null); + + if (identifier) { + addIdentifier(locals, identifier, instance, constructor || expression.name); } - locals.$scope[identifier] = instance; + return extend(function $controllerInit() { + var result = $injector.invoke(expression, instance, locals, constructor); + if (result !== instance && (isObject(result) || isFunction(result))) { + instance = result; + if (identifier) { + // If result changed, re-assign controllerAs value to scope. + addIdentifier(locals, identifier, instance, constructor || expression.name); + } + } + return instance; + }, { + instance: instance, + identifier: identifier + }); + } + + instance = $injector.instantiate(expression, locals, constructor); + + if (identifier) { + addIdentifier(locals, identifier, instance, constructor || expression.name); } return instance; }; + + function addIdentifier(locals, identifier, instance, name) { + if (!(locals && isObject(locals.$scope))) { + throw minErr('$controller')('noscp', + 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.', + name, identifier); + } + + locals.$scope[identifier] = instance; + } }]; } @@ -7152,39 +11851,69 @@ function $ControllerProvider() { * @ngdoc service * @name $document * @requires $window + * @this * * @description * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object. * * @example - + -
+

$document title:

window.document title:

- function MainCtrl($scope, $document) { - $scope.title = $document[0].title; - $scope.windowTitle = angular.element(window.document)[0].title; - } + angular.module('documentExample', []) + .controller('ExampleController', ['$scope', '$document', function($scope, $document) { + $scope.title = $document[0].title; + $scope.windowTitle = angular.element(window.document)[0].title; + }]); */ -function $DocumentProvider(){ - this.$get = ['$window', function(window){ +function $DocumentProvider() { + this.$get = ['$window', function(window) { return jqLite(window.document); }]; } + +/** + * @private + * @this + * Listens for document visibility change and makes the current status accessible. + */ +function $$IsDocumentHiddenProvider() { + this.$get = ['$document', '$rootScope', function($document, $rootScope) { + var doc = $document[0]; + var hidden = doc && doc.hidden; + + $document.on('visibilitychange', changeListener); + + $rootScope.$on('$destroy', function() { + $document.off('visibilitychange', changeListener); + }); + + function changeListener() { + hidden = doc.hidden; + } + + return function() { + return hidden; + }; + }]; +} + /** * @ngdoc service * @name $exceptionHandler * @requires ng.$log + * @this * * @description - * Any uncaught exception in angular expressions is delegated to this service. + * Any uncaught exception in AngularJS expressions is delegated to this service. * The default implementation simply delegates to `$log.error` which logs it into * the browser console. * @@ -7193,20 +11922,31 @@ function $DocumentProvider(){ * * ## Example: * + * The example below will overwrite the default `$exceptionHandler` in order to (a) log uncaught + * errors to the backend for later inspection by the developers and (b) to use `$log.warn()` instead + * of `$log.error()`. + * * ```js - * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () { - * return function (exception, cause) { - * exception.message += ' (caused by "' + cause + '")'; - * throw exception; - * }; - * }); + * angular. + * module('exceptionOverwrite', []). + * factory('$exceptionHandler', ['$log', 'logErrorsToBackend', function($log, logErrorsToBackend) { + * return function myExceptionHandler(exception, cause) { + * logErrorsToBackend(exception, cause); + * $log.warn(exception, cause); + * }; + * }]); * ``` * - * This example will override the normal action of `$exceptionHandler`, to make angular - * exceptions fail hard when they happen, instead of just logging to the console. + *
+ * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind` + * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler} + * (unless executed during a digest). + * + * If you wish, you can manually delegate exceptions, e.g. + * `try { ... } catch(e) { $exceptionHandler(e); }` * * @param {Error} exception Exception associated with the error. - * @param {string=} cause optional information about the context in which + * @param {string=} cause Optional information about the context in which * the error was thrown. * */ @@ -7218,30 +11958,218 @@ function $ExceptionHandlerProvider() { }]; } -/** - * Parse headers into key value object - * - * @param {string} headers Raw headers as a string - * @returns {Object} Parsed headers as key value object - */ -function parseHeaders(headers) { - var parsed = {}, key, val, i; - - if (!headers) return parsed; - - forEach(headers.split('\n'), function(line) { - i = line.indexOf(':'); - key = lowercase(trim(line.substr(0, i))); - val = trim(line.substr(i + 1)); - - if (key) { - if (parsed[key]) { - parsed[key] += ', ' + val; +var $$ForceReflowProvider = /** @this */ function() { + this.$get = ['$document', function($document) { + return function(domNode) { + //the line below will force the browser to perform a repaint so + //that all the animated elements within the animation frame will + //be properly updated and drawn on screen. This is required to + //ensure that the preparation animation is properly flushed so that + //the active state picks up from there. DO NOT REMOVE THIS LINE. + //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH + //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND + //WILL TAKE YEARS AWAY FROM YOUR LIFE. + if (domNode) { + if (!domNode.nodeType && domNode instanceof jqLite) { + domNode = domNode[0]; + } } else { - parsed[key] = val; + domNode = $document[0].body; + } + return domNode.offsetWidth + 1; + }; + }]; +}; + +var APPLICATION_JSON = 'application/json'; +var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'}; +var JSON_START = /^\[|^\{(?!\{)/; +var JSON_ENDS = { + '[': /]$/, + '{': /}$/ +}; +var JSON_PROTECTION_PREFIX = /^\)]\}',?\n/; +var $httpMinErr = minErr('$http'); + +function serializeValue(v) { + if (isObject(v)) { + return isDate(v) ? v.toISOString() : toJson(v); + } + return v; +} + + +/** @this */ +function $HttpParamSerializerProvider() { + /** + * @ngdoc service + * @name $httpParamSerializer + * @description + * + * Default {@link $http `$http`} params serializer that converts objects to strings + * according to the following rules: + * + * * `{'foo': 'bar'}` results in `foo=bar` + * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object) + * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element) + * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D` (stringified and encoded representation of an object) + * + * Note that serializer will sort the request parameters alphabetically. + */ + + this.$get = function() { + return function ngParamSerializer(params) { + if (!params) return ''; + var parts = []; + forEachSorted(params, function(value, key) { + if (value === null || isUndefined(value) || isFunction(value)) return; + if (isArray(value)) { + forEach(value, function(v) { + parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v))); + }); + } else { + parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value))); + } + }); + + return parts.join('&'); + }; + }; +} + +/** @this */ +function $HttpParamSerializerJQLikeProvider() { + /** + * @ngdoc service + * @name $httpParamSerializerJQLike + * + * @description + * + * Alternative {@link $http `$http`} params serializer that follows + * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic. + * The serializer will also sort the params alphabetically. + * + * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property: + * + * ```js + * $http({ + * url: myUrl, + * method: 'GET', + * params: myParams, + * paramSerializer: '$httpParamSerializerJQLike' + * }); + * ``` + * + * It is also possible to set it as the default `paramSerializer` in the + * {@link $httpProvider#defaults `$httpProvider`}. + * + * Additionally, you can inject the serializer and use it explicitly, for example to serialize + * form data for submission: + * + * ```js + * .controller(function($http, $httpParamSerializerJQLike) { + * //... + * + * $http({ + * url: myUrl, + * method: 'POST', + * data: $httpParamSerializerJQLike(myData), + * headers: { + * 'Content-Type': 'application/x-www-form-urlencoded' + * } + * }); + * + * }); + * ``` + * + */ + this.$get = function() { + return function jQueryLikeParamSerializer(params) { + if (!params) return ''; + var parts = []; + serialize(params, '', true); + return parts.join('&'); + + function serialize(toSerialize, prefix, topLevel) { + if (isArray(toSerialize)) { + forEach(toSerialize, function(value, index) { + serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']'); + }); + } else if (isObject(toSerialize) && !isDate(toSerialize)) { + forEachSorted(toSerialize, function(value, key) { + serialize(value, prefix + + (topLevel ? '' : '[') + + key + + (topLevel ? '' : ']')); + }); + } else { + if (isFunction(toSerialize)) { + toSerialize = toSerialize(); + } + parts.push(encodeUriQuery(prefix) + '=' + + (toSerialize == null ? '' : encodeUriQuery(serializeValue(toSerialize)))); + } + } + }; + }; +} + +function defaultHttpResponseTransform(data, headers) { + if (isString(data)) { + // Strip json vulnerability protection prefix and trim whitespace + var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim(); + + if (tempData) { + var contentType = headers('Content-Type'); + var hasJsonContentType = contentType && (contentType.indexOf(APPLICATION_JSON) === 0); + + if (hasJsonContentType || isJsonLike(tempData)) { + try { + data = fromJson(tempData); + } catch (e) { + if (!hasJsonContentType) { + return data; + } + throw $httpMinErr('baddata', 'Data must be a valid JSON object. Received: "{0}". ' + + 'Parse error: "{1}"', data, e); + } } } - }); + } + + return data; +} + +function isJsonLike(str) { + var jsonStart = str.match(JSON_START); + return jsonStart && JSON_ENDS[jsonStart[0]].test(str); +} + +/** + * Parse headers into key value object + * + * @param {string} headers Raw headers as a string + * @returns {Object} Parsed headers as key value object + */ +function parseHeaders(headers) { + var parsed = createMap(), i; + + function fillInParsed(key, val) { + if (key) { + parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; + } + } + + if (isString(headers)) { + forEach(headers.split('\n'), function(line) { + i = line.indexOf(':'); + fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1))); + }); + } else if (isObject(headers)) { + forEach(headers, function(headerVal, headerKey) { + fillInParsed(lowercase(headerKey), trim(headerVal)); + }); + } return parsed; } @@ -7256,17 +12184,21 @@ function parseHeaders(headers) { * @param {(string|Object)} headers Headers to provide access to. * @returns {function(string=)} Returns a getter function which if called with: * - * - if called with single an argument returns a single header value or null + * - if called with an argument returns a single header value or null * - if called with no arguments returns an object containing all headers. */ function headersGetter(headers) { - var headersObj = isObject(headers) ? headers : undefined; + var headersObj; return function(name) { if (!headersObj) headersObj = parseHeaders(headers); if (name) { - return headersObj[lowercase(name)] || null; + var value = headersObj[lowercase(name)]; + if (value === undefined) { + value = null; + } + return value; } return headersObj; @@ -7280,16 +12212,18 @@ function headersGetter(headers) { * This function is used for both request and response transforming * * @param {*} data Data to transform. - * @param {function(string=)} headers Http headers getter fn. + * @param {function(string=)} headers HTTP headers getter fn. + * @param {number} status HTTP status code of the response. * @param {(Function|Array.)} fns Function or an array of functions. * @returns {*} Transformed data. */ -function transformData(data, headers, fns) { - if (isFunction(fns)) - return fns(data, headers); +function transformData(data, headers, status, fns) { + if (isFunction(fns)) { + return fns(data, headers, status); + } forEach(fns, function(fn) { - data = fn(data, headers); + data = fn(data, headers, status); }); return data; @@ -7301,27 +12235,75 @@ function isSuccess(status) { } +/** + * @ngdoc provider + * @name $httpProvider + * @this + * + * @description + * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service. + */ function $HttpProvider() { - var JSON_START = /^\s*(\[|\{[^\{])/, - JSON_END = /[\}\]]\s*$/, - PROTECTION_PREFIX = /^\)\]\}',?\n/, - CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'}; - + /** + * @ngdoc property + * @name $httpProvider#defaults + * @description + * + * Object containing default values for all {@link ng.$http $http} requests. + * + * - **`defaults.cache`** - {boolean|Object} - A boolean value or object created with + * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of HTTP responses + * by default. See {@link $http#caching $http Caching} for more information. + * + * - **`defaults.headers`** - {Object} - Default headers for all $http requests. + * Refer to {@link ng.$http#setting-http-headers $http} for documentation on + * setting default headers. + * - **`defaults.headers.common`** + * - **`defaults.headers.post`** + * - **`defaults.headers.put`** + * - **`defaults.headers.patch`** + * + * - **`defaults.jsonpCallbackParam`** - `{string}` - the name of the query parameter that passes the name of the + * callback in a JSONP request. The value of this parameter will be replaced with the expression generated by the + * {@link $jsonpCallbacks} service. Defaults to `'callback'`. + * + * - **`defaults.paramSerializer`** - `{string|function(Object):string}` - A function + * used to the prepare string representation of request parameters (specified as an object). + * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}. + * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}. + * + * - **`defaults.transformRequest`** - + * `{Array|function(data, headersGetter)}` - + * An array of functions (or a single function) which are applied to the request data. + * By default, this is an array with one request transformation function: + * + * - If the `data` property of the request configuration object contains an object, serialize it + * into JSON format. + * + * - **`defaults.transformResponse`** - + * `{Array|function(data, headersGetter, status)}` - + * An array of functions (or a single function) which are applied to the response data. By default, + * this is an array which applies one response transformation function that does two things: + * + * - If XSRF prefix is detected, strip it + * (see {@link ng.$http#security-considerations Security Considerations in the $http docs}). + * - If the `Content-Type` is `application/json` or the response looks like JSON, + * deserialize it using a JSON parser. + * + * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token. + * Defaults value is `'XSRF-TOKEN'`. + * + * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the + * XSRF token. Defaults value is `'X-XSRF-TOKEN'`. + * + */ var defaults = this.defaults = { // transform incoming response data - transformResponse: [function(data) { - if (isString(data)) { - // strip json vulnerability protection prefix - data = data.replace(PROTECTION_PREFIX, ''); - if (JSON_START.test(data) && JSON_END.test(data)) - data = fromJson(data); - } - return data; - }], + transformResponse: [defaultHttpResponseTransform], // transform outgoing request data transformRequest: [function(d) { - return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d; + return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d; }], // default headers @@ -7329,32 +12311,135 @@ function $HttpProvider() { common: { 'Accept': 'application/json, text/plain, */*' }, - post: copy(CONTENT_TYPE_APPLICATION_JSON), - put: copy(CONTENT_TYPE_APPLICATION_JSON), - patch: copy(CONTENT_TYPE_APPLICATION_JSON) + post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), + put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON), + patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON) }, xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN' + xsrfHeaderName: 'X-XSRF-TOKEN', + + paramSerializer: '$httpParamSerializer', + + jsonpCallbackParam: 'callback' + }; + + var useApplyAsync = false; + /** + * @ngdoc method + * @name $httpProvider#useApplyAsync + * @description + * + * Configure $http service to combine processing of multiple http responses received at around + * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in + * significant performance improvement for bigger applications that make many HTTP requests + * concurrently (common during application bootstrap). + * + * Defaults to false. If no value is specified, returns the current configured value. + * + * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred + * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window + * to load and share the same digest cycle. + * + * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining. + * otherwise, returns the current configured value. + */ + this.useApplyAsync = function(value) { + if (isDefined(value)) { + useApplyAsync = !!value; + return this; + } + return useApplyAsync; }; /** - * Are ordered by request, i.e. they are applied in the same order as the + * @ngdoc property + * @name $httpProvider#interceptors + * @description + * + * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http} + * pre-processing of request or postprocessing of responses. + * + * These service factories are ordered by request, i.e. they are applied in the same order as the * array, on request, but reverse order, on response. + * + * {@link ng.$http#interceptors Interceptors detailed info} */ var interceptorFactories = this.interceptors = []; /** - * For historical reasons, response interceptors are ordered by the order in which - * they are applied to the response. (This is the opposite of interceptorFactories) + * @ngdoc property + * @name $httpProvider#xsrfTrustedOrigins + * @description + * + * Array containing URLs whose origins are trusted to receive the XSRF token. See the + * {@link ng.$http#security-considerations Security Considerations} sections for more details on + * XSRF. + * + * **Note:** An "origin" consists of the [URI scheme](https://en.wikipedia.org/wiki/URI_scheme), + * the [hostname](https://en.wikipedia.org/wiki/Hostname) and the + * [port number](https://en.wikipedia.org/wiki/Port_(computer_networking). For `http:` and + * `https:`, the port number can be omitted if using th default ports (80 and 443 respectively). + * Examples: `http://example.com`, `https://api.example.com:9876` + * + *
+ * It is not possible to trust specific URLs/paths. The `path`, `query` and `fragment` parts + * of a URL will be ignored. For example, `https://foo.com/path/bar?query=baz#fragment` will be + * treated as `https://foo.com`, meaning that **all** requests to URLs starting with + * `https://foo.com/` will include the XSRF token. + *
+ * + * @example + * + * ```js + * // App served from `https://example.com/`. + * angular. + * module('xsrfTrustedOriginsExample', []). + * config(['$httpProvider', function($httpProvider) { + * $httpProvider.xsrfTrustedOrigins.push('https://api.example.com'); + * }]). + * run(['$http', function($http) { + * // The XSRF token will be sent. + * $http.get('https://api.example.com/preferences').then(...); + * + * // The XSRF token will NOT be sent. + * $http.get('https://stats.example.com/activity').then(...); + * }]); + * ``` + */ + var xsrfTrustedOrigins = this.xsrfTrustedOrigins = []; + + /** + * @ngdoc property + * @name $httpProvider#xsrfWhitelistedOrigins + * @description + * + * @deprecated + * sinceVersion="1.8.1" + * + * This property is deprecated. Use {@link $httpProvider#xsrfTrustedOrigins xsrfTrustedOrigins} + * instead. */ - var responseInterceptorFactories = this.responseInterceptors = []; + Object.defineProperty(this, 'xsrfWhitelistedOrigins', { + get: function() { + return this.xsrfTrustedOrigins; + }, + set: function(origins) { + this.xsrfTrustedOrigins = origins; + } + }); - this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', - function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { + this.$get = ['$browser', '$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector', '$sce', + function($browser, $httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector, $sce) { var defaultCache = $cacheFactory('$http'); + /** + * Make sure that default param serializer is exposed as a function + */ + defaults.paramSerializer = isString(defaults.paramSerializer) ? + $injector.get(defaults.paramSerializer) : defaults.paramSerializer; + /** * Interceptors stored in reverse order. Inner interceptors before outer interceptors. * The reversal is needed so that we can build up the interception chain around the @@ -7367,26 +12452,10 @@ function $HttpProvider() { ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); }); - forEach(responseInterceptorFactories, function(interceptorFactory, index) { - var responseFn = isString(interceptorFactory) - ? $injector.get(interceptorFactory) - : $injector.invoke(interceptorFactory); - - /** - * Response interceptors go before "around" interceptors (no real reason, just - * had to pick one.) But they are already reversed, so we can't use unshift, hence - * the splice. - */ - reversedInterceptors.splice(index, 0, { - response: function(response) { - return responseFn($q.when(response)); - }, - responseError: function(response) { - return responseFn($q.reject(response)); - } - }); - }); - + /** + * A function to check request URLs against a list of allowed origins. + */ + var urlIsAllowedOrigin = urlIsAllowedOriginFactory(xsrfTrustedOrigins); /** * @ngdoc service @@ -7399,7 +12468,7 @@ function $HttpProvider() { * @requires $injector * * @description - * The `$http` service is a core Angular service that facilitates communication with the remote + * The `$http` service is a core AngularJS service that facilitates communication with the remote * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest) * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP). * @@ -7414,52 +12483,36 @@ function $HttpProvider() { * it is important to familiarize yourself with these APIs and the guarantees they provide. * * - * # General usage - * The `$http` service is a function which takes a single argument — a configuration object — - * that is used to generate an HTTP request and returns a {@link ng.$q promise} - * with two $http specific methods: `success` and `error`. + * ## General usage + * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} — + * that is used to generate an HTTP request and returns a {@link ng.$q promise} that is + * resolved (request success) or rejected (request failure) with a + * {@link ng.$http#$http-returns response} object. * * ```js - * $http({method: 'GET', url: '/someUrl'}). - * success(function(data, status, headers, config) { + * // Simple GET request example: + * $http({ + * method: 'GET', + * url: '/someUrl' + * }).then(function successCallback(response) { * // this callback will be called asynchronously * // when the response is available - * }). - * error(function(data, status, headers, config) { + * }, function errorCallback(response) { * // called asynchronously if an error occurs * // or server returns response with an error status. * }); * ``` * - * Since the returned value of calling the $http function is a `promise`, you can also use - * the `then` method to register callbacks, and these callbacks will receive a single argument – - * an object representing the response. See the API signature and type info below for more - * details. - * - * A response status code between 200 and 299 is considered a success status and - * will result in the success callback being called. Note that if the response is a redirect, - * XMLHttpRequest will transparently follow it, meaning that the error callback will not be - * called for such responses. - * - * # Writing Unit Tests that use $http - * When unit testing (using {@link ngMock ngMock}), it is necessary to call - * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending - * request using trained responses. - * - * ``` - * $httpBackend.expectGET(...); - * $http.get(...); - * $httpBackend.flush(); - * ``` * - * # Shortcut methods + * ## Shortcut methods * * Shortcut methods are also available. All shortcut methods require passing in the URL, and - * request data must be passed in for POST/PUT requests. + * request data must be passed in for POST/PUT requests. An optional config can be passed as the + * last argument. * * ```js - * $http.get('/someUrl').success(successCallback); - * $http.post('/someUrl', data).success(successCallback); + * $http.get('/someUrl', config).then(successCallback, errorCallback); + * $http.post('/someUrl', data, config).then(successCallback, errorCallback); * ``` * * Complete list of shortcut methods: @@ -7470,16 +12523,28 @@ function $HttpProvider() { * - {@link ng.$http#put $http.put} * - {@link ng.$http#delete $http.delete} * - {@link ng.$http#jsonp $http.jsonp} + * - {@link ng.$http#patch $http.patch} + * + * + * ## Writing Unit Tests that use $http + * When unit testing (using {@link ngMock ngMock}), it is necessary to call + * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending + * request using trained responses. * + * ``` + * $httpBackend.expectGET(...); + * $http.get(...); + * $httpBackend.flush(); + * ``` * - * # Setting HTTP Headers + * ## Setting HTTP Headers * * The $http service will automatically add certain HTTP headers to all requests. These defaults * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration * object, which currently contains this default configuration: * * - `$httpProvider.defaults.headers.common` (headers that are common for all requests): - * - `Accept: application/json, text/plain, * / *` + * - Accept: application/json, text/plain, \*/\* * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests) * - `Content-Type: application/json` * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests) @@ -7488,74 +12553,143 @@ function $HttpProvider() { * To add or overwrite these defaults, simply add or remove a property from these configuration * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object * with the lowercased HTTP method name as the key, e.g. - * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }. + * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`. * * The defaults can also be set at runtime via the `$http.defaults` object in the same * fashion. For example: * * ``` * module.run(function($http) { - * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w' + * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'; * }); * ``` * * In addition, you can supply a `headers` property in the config object passed when * calling `$http(config)`, which overrides the defaults without changing them globally. * + * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis, + * Use the `headers` property, setting the desired header to `undefined`. For example: + * + * ```js + * var req = { + * method: 'POST', + * url: 'http://example.com', + * headers: { + * 'Content-Type': undefined + * }, + * data: { test: 'test' } + * } + * + * $http(req).then(function(){...}, function(){...}); + * ``` + * + * ## Transforming Requests and Responses + * + * Both requests and responses can be transformed using transformation functions: `transformRequest` + * and `transformResponse`. These properties can be a single function that returns + * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions, + * which allows you to `push` or `unshift` a new transformation function into the transformation chain. + * + *
+ * **Note:** AngularJS does not make a copy of the `data` parameter before it is passed into the `transformRequest` pipeline. + * That means changes to the properties of `data` are not local to the transform function (since Javascript passes objects by reference). + * For example, when calling `$http.get(url, $scope.myObject)`, modifications to the object's properties in a transformRequest + * function will be reflected on the scope and in any templates where the object is data-bound. + * To prevent this, transform functions should have no side-effects. + * If you need to modify properties, it is recommended to make a copy of the data, or create new object to return. + *
+ * + * ### Default Transformations + * + * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and + * `defaults.transformResponse` properties. If a request does not provide its own transformations + * then these will be applied. * - * # Transforming Requests and Responses + * You can augment or replace the default transformations by modifying these properties by adding to or + * replacing the array. * - * Both requests and responses can be transformed using transform functions. By default, Angular - * applies these transformations: + * AngularJS provides the following default transformations: * - * Request transformations: + * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`) is + * an array with one function that does the following: * * - If the `data` property of the request configuration object contains an object, serialize it * into JSON format. * - * Response transformations: + * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`) is + * an array with one function that does the following: * * - If XSRF prefix is detected, strip it (see Security Considerations section below). - * - If JSON response is detected, deserialize it using a JSON parser. - * - * To globally augment or override the default transforms, modify the - * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse` - * properties. These properties are by default an array of transform functions, which allows you - * to `push` or `unshift` a new transformation function into the transformation chain. You can - * also decide to completely override any default transformations by assigning your - * transformation functions to these properties directly without the array wrapper. These defaults - * are again available on the $http factory at run-time, which may be useful if you have run-time - * services you wish to be involved in your transformations. - * - * Similarly, to locally override the request/response transforms, augment the - * `transformRequest` and/or `transformResponse` properties of the configuration object passed + * - If the `Content-Type` is `application/json` or the response looks like JSON, + * deserialize it using a JSON parser. + * + * + * ### Overriding the Default Transformations Per Request + * + * If you wish to override the request/response transformations only for a single request then provide + * `transformRequest` and/or `transformResponse` properties on the configuration object passed * into `$http`. * + * Note that if you provide these properties on the config object the default transformations will be + * overwritten. If you wish to augment the default transformations then you must include them in your + * local transformation array. + * + * The following code demonstrates adding a new response transformation to be run after the default response + * transformations have been run. + * + * ```js + * function appendTransform(defaults, transform) { + * + * // We can't guarantee that the default transformation is an array + * defaults = angular.isArray(defaults) ? defaults : [defaults]; + * + * // Append the new transformation to the defaults + * return defaults.concat(transform); + * } * - * # Caching + * $http({ + * url: '...', + * method: 'GET', + * transformResponse: appendTransform($http.defaults.transformResponse, function(value) { + * return doTransform(value); + * }) + * }); + * ``` + * + * + * ## Caching * - * To enable caching, set the request configuration `cache` property to `true` (to use default - * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}). - * When the cache is enabled, `$http` stores the response from the server in the specified - * cache. The next time the same request is made, the response is served from the cache without - * sending a request to the server. + * {@link ng.$http `$http`} responses are not cached by default. To enable caching, you must + * set the config.cache value or the default cache value to TRUE or to a cache object (created + * with {@link ng.$cacheFactory `$cacheFactory`}). If defined, the value of config.cache takes + * precedence over the default cache value. * - * Note that even if the response is served from cache, delivery of the data is asynchronous in - * the same way that real requests are. + * In order to: + * * cache all responses - set the default cache value to TRUE or to a cache object + * * cache a specific response - set config.cache value to TRUE or to a cache object * - * If there are multiple GET requests for the same URL that should be cached using the same - * cache, but the cache is not populated yet, only one request to the server will be made and - * the remaining requests will be fulfilled using the response from the first request. + * If caching is enabled, but neither the default cache nor config.cache are set to a cache object, + * then the default `$cacheFactory("$http")` object is used. * - * You can change the default cache to a new object (built with - * {@link ng.$cacheFactory `$cacheFactory`}) by updating the - * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set - * their `cache` property to `true` will now use this cache object. + * The default cache value can be set by updating the + * {@link ng.$http#defaults `$http.defaults.cache`} property or the + * {@link $httpProvider#defaults `$httpProvider.defaults.cache`} property. * - * If you set the default cache to `false` then only requests that specify their own custom - * cache object will be cached. + * When caching is enabled, {@link ng.$http `$http`} stores the response from the server using + * the relevant cache object. The next time the same request is made, the response is returned + * from the cache without sending a request to the server. * - * # Interceptors + * Take note that: + * + * * Only GET and JSONP requests are cached. + * * The cache key is the request URL including search parameters; headers are not considered. + * * Cached responses are returned asynchronously, in the same way as responses from the server. + * * If multiple identical requests are made using the same cache, which is not yet populated, + * one request will be made to the server and remaining requests will return the same response. + * * A cache-control header on the response does not affect if or how responses are cached. + * + * + * ## Interceptors * * Before you start creating interceptors, be sure to understand the * {@link ng.$q $q and deferred/promise APIs}. @@ -7573,14 +12707,14 @@ function $HttpProvider() { * * There are two kinds of interceptors (and two kinds of rejection interceptors): * - * * `request`: interceptors get called with http `config` object. The function is free to - * modify the `config` or create a new one. The function needs to return the `config` - * directly or as a promise. + * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to + * modify the `config` object or create a new one. The function needs to return the `config` + * object directly, or a promise containing the `config` or a new `config` object. * * `requestError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * * `response`: interceptors get called with http `response` object. The function is free to - * modify the `response` or create a new one. The function needs to return the `response` - * directly or as a promise. + * modify the `response` object or create a new one. The function needs to return the `response` + * object directly, or as a promise containing the `response` or a new `response` object. * * `responseError`: interceptor gets called when a previous interceptor threw an error or * resolved with a rejection. * @@ -7592,7 +12726,7 @@ function $HttpProvider() { * // optional method * 'request': function(config) { * // do something on success - * return config || $q.when(config); + * return config; * }, * * // optional method @@ -7609,7 +12743,7 @@ function $HttpProvider() { * // optional method * 'response': function(response) { * // do something on success - * return response || $q.when(response); + * return response; * }, * * // optional method @@ -7640,69 +12774,24 @@ function $HttpProvider() { * }); * ``` * - * # Response interceptors (DEPRECATED) - * - * Before you start creating interceptors, be sure to understand the - * {@link ng.$q $q and deferred/promise APIs}. - * - * For purposes of global error handling, authentication or any kind of synchronous or - * asynchronous preprocessing of received responses, it is desirable to be able to intercept - * responses for http requests before they are handed over to the application code that - * initiated these requests. The response interceptors leverage the {@link ng.$q - * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing. - * - * The interceptors are service factories that are registered with the $httpProvider by - * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and - * injected with dependencies (if specified) and returns the interceptor — a function that - * takes a {@link ng.$q promise} and returns the original or a new promise. - * - * ```js - * // register the interceptor as a service - * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) { - * return function(promise) { - * return promise.then(function(response) { - * // do something on success - * return response; - * }, function(response) { - * // do something on error - * if (canRecover(response)) { - * return responseOrNewPromise - * } - * return $q.reject(response); - * }); - * } - * }); - * - * $httpProvider.responseInterceptors.push('myHttpInterceptor'); - * - * - * // register the interceptor via an anonymous factory - * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) { - * return function(promise) { - * // same as above - * } - * }); - * ``` - * - * - * # Security Considerations + * ## Security Considerations * * When designing web applications, consider security threats from: * * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) * - * Both server and the client must cooperate in order to eliminate these threats. Angular comes + * Both server and the client must cooperate in order to eliminate these threats. AngularJS comes * pre-configured with strategies that address these issues, but for this to work backend server * cooperation is required. * - * ## JSON Vulnerability Protection + * ### JSON Vulnerability Protection * * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx) * allows third party website to turn your JSON resource URL into * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To * counter this your server can prefix all JSON requests with following string `")]}',\n"`. - * Angular will automatically strip the prefix before processing it as JSON. + * AngularJS will automatically strip the prefix before processing it as JSON. * * For example if your server needs to return: * ```js @@ -7715,104 +12804,158 @@ function $HttpProvider() { * ['one','two'] * ``` * - * Angular will strip the prefix, before processing the JSON. + * AngularJS will strip the prefix, before processing the JSON. * * - * ## Cross Site Request Forgery (XSRF) Protection + * ### Cross Site Request Forgery (XSRF) Protection * - * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which - * an unauthorized site can gain your user's private data. Angular provides a mechanism - * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie - * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only - * JavaScript that runs on your domain could read the cookie, your server can be assured that - * the XHR came from JavaScript running on your domain. The header will not be set for - * cross-domain requests. + * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by + * which the attacker can trick an authenticated user into unknowingly executing actions on your + * website. AngularJS provides a mechanism to counter XSRF. When performing XHR requests, the + * $http service reads a token from a cookie (by default, `XSRF-TOKEN`) and sets it as an HTTP + * header (by default `X-XSRF-TOKEN`). Since only JavaScript that runs on your domain could read + * the cookie, your server can be assured that the XHR came from JavaScript running on your + * domain. * * To take advantage of this, your server needs to set a token in a JavaScript readable session * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the - * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure - * that only JavaScript running on your domain could have sent the request. The token must be - * unique for each user and must be verifiable by the server (to prevent the JavaScript from + * server can verify that the cookie matches the `X-XSRF-TOKEN` HTTP header, and therefore be + * sure that only JavaScript running on your domain could have sent the request. The token must + * be unique for each user and must be verifiable by the server (to prevent the JavaScript from * making up its own tokens). We recommend that the token is a digest of your site's - * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) + * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) * for added security. * - * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName - * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time, - * or the per-request config object. + * The header will — by default — **not** be set for cross-domain requests. This + * prevents unauthorized servers (e.g. malicious or compromised 3rd-party APIs) from gaining + * access to your users' XSRF tokens and exposing them to Cross Site Request Forgery. If you + * want to, you can trust additional origins to also receive the XSRF token, by adding them + * to {@link ng.$httpProvider#xsrfTrustedOrigins xsrfTrustedOrigins}. This might be + * useful, for example, if your application, served from `example.com`, needs to access your API + * at `api.example.com`. + * See {@link ng.$httpProvider#xsrfTrustedOrigins $httpProvider.xsrfTrustedOrigins} for + * more details. + * + *
+ * **Warning**
+ * Only trusted origins that you have control over and make sure you understand the + * implications of doing so. + *
+ * + * The name of the cookie and the header can be specified using the `xsrfCookieName` and + * `xsrfHeaderName` properties of either `$httpProvider.defaults` at config-time, + * `$http.defaults` at run-time, or the per-request config object. + * + * In order to prevent collisions in environments where multiple AngularJS apps share the + * same domain or subdomain, we recommend that each application uses a unique cookie name. * * * @param {object} config Object describing the request to be made and how it should be * processed. The object has following properties: * * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc) - * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested. - * - **params** – `{Object.}` – Map of strings or objects which will be turned - * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be - * JSONified. + * - **url** – `{string|TrustedObject}` – Absolute or relative URL of the resource that is being requested; + * or an object created by a call to `$sce.trustAsResourceUrl(url)`. + * - **params** – `{Object.}` – Map of strings or objects which will be serialized + * with the `paramSerializer` and appended as GET parameters. * - **data** – `{string|Object}` – Data to be sent as the request message data. * - **headers** – `{Object}` – Map of strings or functions which return strings representing * HTTP headers to send to the server. If the return value of a function is null, the - * header will not be sent. + * header will not be sent. Functions accept a config object as an argument. + * - **eventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest object. + * To bind events to the XMLHttpRequest upload object, use `uploadEventHandlers`. + * The handler will be called in the context of a `$apply` block. + * - **uploadEventHandlers** - `{Object}` - Event listeners to be bound to the XMLHttpRequest upload + * object. To bind events to the XMLHttpRequest object, use `eventHandlers`. + * The handler will be called in the context of a `$apply` block. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. * - **transformRequest** – * `{function(data, headersGetter)|Array.}` – * transform function or an array of such functions. The transform function takes the http * request body and headers and returns its transformed (typically serialized) version. + * See {@link ng.$http#overriding-the-default-transformations-per-request + * Overriding the Default Transformations} * - **transformResponse** – - * `{function(data, headersGetter)|Array.}` – + * `{function(data, headersGetter, status)|Array.}` – * transform function or an array of such functions. The transform function takes the http - * response body and headers and returns its transformed (typically deserialized) version. - * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the - * GET request, otherwise if a cache instance built with - * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for - * caching. + * response body, headers and status and returns its transformed (typically deserialized) version. + * See {@link ng.$http#overriding-the-default-transformations-per-request + * Overriding the Default Transformations} + * - **paramSerializer** - `{string|function(Object):string}` - A function used to + * prepare the string representation of request parameters (specified as an object). + * If specified as string, it is interpreted as function registered with the + * {@link $injector $injector}, which means you can create your own serializer + * by registering it as a {@link auto.$provide#service service}. + * The default serializer is the {@link $httpParamSerializer $httpParamSerializer}; + * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike} + * - **cache** – `{boolean|Object}` – A boolean value or object created with + * {@link ng.$cacheFactory `$cacheFactory`} to enable or disable caching of the HTTP response. + * See {@link $http#caching $http Caching} for more information. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} * that should abort the request when resolved. - * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the - * XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 + * + * A numerical timeout or a promise returned from {@link ng.$timeout $timeout}, will set + * the `xhrStatus` in the {@link $http#$http-returns response} to "timeout", and any other + * resolved promise will set it to "abort", following standard XMLHttpRequest behavior. + * + * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the + * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials) * for more information. * - **responseType** - `{string}` - see - * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType). - * - * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the - * standard `then` method and two http specific methods: `success` and `error`. The `then` - * method takes two arguments a success and an error callback which will be called with a - * response object. The `success` and `error` methods take a single argument - a function that - * will be called when the request succeeds or fails respectively. The arguments passed into - * these functions are destructured representation of the response object passed into the - * `then` method. The response object has these properties: - * - * - **data** – `{string|Object}` – The response body transformed with the transform - * functions. + * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype). + * + * @returns {HttpPromise} A {@link ng.$q `Promise}` that will be resolved (request success) + * or rejected (request failure) with a response object. + * + * The response object has these properties: + * + * - **data** – `{string|Object}` – The response body transformed with + * the transform functions. * - **status** – `{number}` – HTTP status code of the response. * - **headers** – `{function([headerName])}` – Header getter function. - * - **config** – `{Object}` – The configuration object that was used to generate the request. + * - **config** – `{Object}` – The configuration object that was used + * to generate the request. * - **statusText** – `{string}` – HTTP status text of the response. + * - **xhrStatus** – `{string}` – Status of the XMLHttpRequest + * (`complete`, `error`, `timeout` or `abort`). + * + * + * A response status code between 200 and 299 is considered a success status + * and will result in the success callback being called. Any response status + * code outside of that range is considered an error status and will result + * in the error callback being called. + * Also, status codes less than -1 are normalized to zero. -1 usually means + * the request was aborted, e.g. using a `config.timeout`. More information + * about the status might be available in the `xhrStatus` property. + * + * Note that if the response is a redirect, XMLHttpRequest will transparently + * follow it, meaning that the outcome (success or error) will be determined + * by the final response status code. + * * * @property {Array.} pendingRequests Array of config objects for currently pending * requests. This is primarily meant to be used for debugging purposes. * * * @example - + -
- - +
http status code: {{status}}
@@ -7820,30 +12963,38 @@ function $HttpProvider() {
- function FetchCtrl($scope, $http, $templateCache) { - $scope.method = 'GET'; - $scope.url = 'http-hello.html'; - - $scope.fetch = function() { - $scope.code = null; - $scope.response = null; - - $http({method: $scope.method, url: $scope.url, cache: $templateCache}). - success(function(data, status) { - $scope.status = status; - $scope.data = data; - }). - error(function(data, status) { - $scope.data = data || "Request failed"; - $scope.status = status; - }); - }; + angular.module('httpExample', []) + .config(['$sceDelegateProvider', function($sceDelegateProvider) { + // We must add the JSONP endpoint that we are using to the trusted list to show that we trust it + $sceDelegateProvider.trustedResourceUrlList([ + 'self', + 'https://angularjs.org/**' + ]); + }]) + .controller('FetchController', ['$scope', '$http', '$templateCache', + function($scope, $http, $templateCache) { + $scope.method = 'GET'; + $scope.url = 'http-hello.html'; + + $scope.fetch = function() { + $scope.code = null; + $scope.response = null; + + $http({method: $scope.method, url: $scope.url, cache: $templateCache}). + then(function(response) { + $scope.status = response.status; + $scope.data = response.data; + }, function(response) { + $scope.data = response.data || 'Request failed'; + $scope.status = response.status; + }); + }; - $scope.updateModel = function(method, url) { - $scope.method = method; - $scope.url = url; - }; - } + $scope.updateModel = function(method, url) { + $scope.method = method; + $scope.url = url; + }; + }]); Hello, $http! @@ -7853,7 +13004,6 @@ function $HttpProvider() { var data = element(by.binding('data')); var fetchBtn = element(by.id('fetchbtn')); var sampleGetBtn = element(by.id('samplegetbtn')); - var sampleJsonpBtn = element(by.id('samplejsonpbtn')); var invalidJsonpBtn = element(by.id('invalidjsonpbtn')); it('should make an xhr GET request', function() { @@ -7863,12 +13013,14 @@ function $HttpProvider() { expect(data.getText()).toMatch(/Hello, \$http!/); }); - it('should make a JSONP request to angularjs.org', function() { - sampleJsonpBtn.click(); - fetchBtn.click(); - expect(status.getText()).toMatch('200'); - expect(data.getText()).toMatch(/Super Hero!/); - }); +// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185 +// it('should make a JSONP request to angularjs.org', function() { +// var sampleJsonpBtn = element(by.id('samplejsonpbtn')); +// sampleJsonpBtn.click(); +// fetchBtn.click(); +// expect(status.getText()).toMatch('200'); +// expect(data.getText()).toMatch(/Super Hero!/); +// }); it('should make JSONP request to invalid URL and invoke the error handler', function() { @@ -7881,90 +13033,84 @@ function $HttpProvider() {
*/ function $http(requestConfig) { - var config = { - method: 'get', - transformRequest: defaults.transformRequest, - transformResponse: defaults.transformResponse - }; - var headers = mergeHeaders(requestConfig); - - extend(config, requestConfig); - config.headers = headers; - config.method = uppercase(config.method); - var xsrfValue = urlIsSameOrigin(config.url) - ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] - : undefined; - if (xsrfValue) { - headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; + if (!isObject(requestConfig)) { + throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig); } + if (!isString($sce.valueOf(requestConfig.url))) { + throw minErr('$http')('badreq', 'Http request configuration url must be a string or a $sce trusted object. Received: {0}', requestConfig.url); + } - var serverRequest = function(config) { - headers = config.headers; - var reqData = transformData(config.data, headersGetter(headers), config.transformRequest); - - // strip content-type if data is undefined - if (isUndefined(config.data)) { - forEach(headers, function(value, header) { - if (lowercase(header) === 'content-type') { - delete headers[header]; - } - }); - } + var config = extend({ + method: 'get', + transformRequest: defaults.transformRequest, + transformResponse: defaults.transformResponse, + paramSerializer: defaults.paramSerializer, + jsonpCallbackParam: defaults.jsonpCallbackParam + }, requestConfig); - if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { - config.withCredentials = defaults.withCredentials; - } + config.headers = mergeHeaders(requestConfig); + config.method = uppercase(config.method); + config.paramSerializer = isString(config.paramSerializer) ? + $injector.get(config.paramSerializer) : config.paramSerializer; - // send request - return sendReq(config, reqData, headers).then(transformResponse, transformResponse); - }; + $browser.$$incOutstandingRequestCount('$http'); - var chain = [serverRequest, undefined]; - var promise = $q.when(config); + var requestInterceptors = []; + var responseInterceptors = []; + var promise = $q.resolve(config); // apply interceptors forEach(reversedInterceptors, function(interceptor) { if (interceptor.request || interceptor.requestError) { - chain.unshift(interceptor.request, interceptor.requestError); + requestInterceptors.unshift(interceptor.request, interceptor.requestError); } if (interceptor.response || interceptor.responseError) { - chain.push(interceptor.response, interceptor.responseError); + responseInterceptors.push(interceptor.response, interceptor.responseError); } }); - while(chain.length) { - var thenFn = chain.shift(); - var rejectFn = chain.shift(); + promise = chainInterceptors(promise, requestInterceptors); + promise = promise.then(serverRequest); + promise = chainInterceptors(promise, responseInterceptors); + promise = promise.finally(completeOutstandingRequest); - promise = promise.then(thenFn, rejectFn); - } + return promise; - promise.success = function(fn) { - promise.then(function(response) { - fn(response.data, response.status, response.headers, config); - }); - return promise; - }; - promise.error = function(fn) { - promise.then(null, function(response) { - fn(response.data, response.status, response.headers, config); - }); + function chainInterceptors(promise, interceptors) { + for (var i = 0, ii = interceptors.length; i < ii;) { + var thenFn = interceptors[i++]; + var rejectFn = interceptors[i++]; + + promise = promise.then(thenFn, rejectFn); + } + + interceptors.length = 0; + return promise; - }; + } - return promise; + function completeOutstandingRequest() { + $browser.$$completeOutstandingRequest(noop, '$http'); + } - function transformResponse(response) { - // make a copy since the response must be cacheable - var resp = extend({}, response, { - data: transformData(response.data, response.headers, config.transformResponse) + function executeHeaderFns(headers, config) { + var headerContent, processedHeaders = {}; + + forEach(headers, function(headerFn, header) { + if (isFunction(headerFn)) { + headerContent = headerFn(config); + if (headerContent != null) { + processedHeaders[header] = headerContent; + } + } else { + processedHeaders[header] = headerFn; + } }); - return (isSuccess(response.status)) - ? resp - : $q.reject(resp); + + return processedHeaders; } function mergeHeaders(config) { @@ -7974,11 +13120,7 @@ function $HttpProvider() { defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); - // execute if header value is function - execHeaders(defHeaders); - execHeaders(reqHeaders); - - // using for-in instead of forEach to avoid unecessary iteration after header has been found + // using for-in instead of forEach to avoid unnecessary iteration after header has been found defaultHeadersIteration: for (defHeaderName in defHeaders) { lowercaseDefHeaderName = lowercase(defHeaderName); @@ -7992,22 +13134,39 @@ function $HttpProvider() { reqHeaders[defHeaderName] = defHeaders[defHeaderName]; } - return reqHeaders; + // execute if header value is a function for merged headers + return executeHeaderFns(reqHeaders, shallowCopy(config)); + } - function execHeaders(headers) { - var headerContent; + function serverRequest(config) { + var headers = config.headers; + var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest); - forEach(headers, function(headerFn, header) { - if (isFunction(headerFn)) { - headerContent = headerFn(); - if (headerContent != null) { - headers[header] = headerContent; - } else { - delete headers[header]; - } + // strip content-type if data is undefined + if (isUndefined(reqData)) { + forEach(headers, function(value, header) { + if (lowercase(header) === 'content-type') { + delete headers[header]; } }); } + + if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) { + config.withCredentials = defaults.withCredentials; + } + + // send request + return sendReq(config, reqData).then(transformResponse, transformResponse); + } + + function transformResponse(response) { + // make a copy since the response must be cacheable + var resp = extend({}, response); + resp.data = transformData(response.data, response.headers, response.status, + config.transformResponse); + return (isSuccess(response.status)) + ? resp + : $q.reject(resp); } } @@ -8020,9 +13179,11 @@ function $HttpProvider() { * @description * Shortcut method to perform `GET` request. * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object + * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; + * or an object created by a call to `$sce.trustAsResourceUrl(url)`. + * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. + * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. + * See {@link ng.$http#$http-returns `$http()` return value}. */ /** @@ -8032,9 +13193,11 @@ function $HttpProvider() { * @description * Shortcut method to perform `DELETE` request. * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object + * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; + * or an object created by a call to `$sce.trustAsResourceUrl(url)`. + * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. + * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. + * See {@link ng.$http#$http-returns `$http()` return value}. */ /** @@ -8044,9 +13207,11 @@ function $HttpProvider() { * @description * Shortcut method to perform `HEAD` request. * - * @param {string} url Relative or absolute URL specifying the destination of the request - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object + * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; + * or an object created by a call to `$sce.trustAsResourceUrl(url)`. + * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. + * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. + * See {@link ng.$http#$http-returns `$http()` return value}. */ /** @@ -8056,10 +13221,40 @@ function $HttpProvider() { * @description * Shortcut method to perform `JSONP` request. * - * @param {string} url Relative or absolute URL specifying the destination of the request. - * Should contain `JSON_CALLBACK` string. - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object + * Note that, since JSONP requests are sensitive because the response is given full access to the browser, + * the url must be declared, via {@link $sce} as a trusted resource URL. + * You can trust a URL by adding it to the trusted resource URL list via + * {@link $sceDelegateProvider#trustedResourceUrlList `$sceDelegateProvider.trustedResourceUrlList`} or + * by explicitly trusting the URL via {@link $sce#trustAsResourceUrl `$sce.trustAsResourceUrl(url)`}. + * + * You should avoid generating the URL for the JSONP request from user provided data. + * Provide additional query parameters via `params` property of the `config` parameter, rather than + * modifying the URL itself. + * + * JSONP requests must specify a callback to be used in the response from the server. This callback + * is passed as a query parameter in the request. You must specify the name of this parameter by + * setting the `jsonpCallbackParam` property on the request config object. + * + * ``` + * $http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'}) + * ``` + * + * You can also specify a default callback parameter name in `$http.defaults.jsonpCallbackParam`. + * Initially this is set to `'callback'`. + * + *
+ * You can no longer use the `JSON_CALLBACK` string as a placeholder for specifying where the callback + * parameter value should go. + *
+ * + * If you would like to customise where and how the callbacks are stored then try overriding + * or decorating the {@link $jsonpCallbacks} service. + * + * @param {string|TrustedObject} url Absolute or relative URL of the resource that is being requested; + * or an object created by a call to `$sce.trustAsResourceUrl(url)`. + * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. + * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. + * See {@link ng.$http#$http-returns `$http()` return value}. */ createShortMethods('get', 'delete', 'head', 'jsonp'); @@ -8072,8 +13267,9 @@ function $HttpProvider() { * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object + * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. + * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. + * See {@link ng.$http#$http-returns `$http()` return value}. */ /** @@ -8085,10 +13281,25 @@ function $HttpProvider() { * * @param {string} url Relative or absolute URL specifying the destination of the request * @param {*} data Request content - * @param {Object=} config Optional configuration object - * @returns {HttpPromise} Future object + * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. + * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. + * See {@link ng.$http#$http-returns `$http()` return value}. */ - createShortMethodsWithData('post', 'put'); + + /** + * @ngdoc method + * @name $http#patch + * + * @description + * Shortcut method to perform `PATCH` request. + * + * @param {string} url Relative or absolute URL specifying the destination of the request + * @param {*} data Request content + * @param {Object=} config Optional configuration object. See {@link ng.$http#$http-arguments `$http()` arguments}. + * @returns {HttpPromise} A Promise that will be resolved or rejected with a response object. + * See {@link ng.$http#$http-returns `$http()` return value}. + */ + createShortMethodsWithData('post', 'put', 'patch'); /** * @ngdoc property @@ -8109,7 +13320,7 @@ function $HttpProvider() { function createShortMethods(names) { forEach(arguments, function(name) { $http[name] = function(url, config) { - return $http(extend(config || {}, { + return $http(extend({}, config || {}, { method: name, url: url })); @@ -8121,7 +13332,7 @@ function $HttpProvider() { function createShortMethodsWithData(name) { forEach(arguments, function(name) { $http[name] = function(url, data, config) { - return $http(extend(config || {}, { + return $http(extend({}, config || {}, { method: name, url: url, data: data @@ -8137,36 +13348,54 @@ function $HttpProvider() { * !!! ACCESSES CLOSURE VARS: * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests */ - function sendReq(config, reqData, reqHeaders) { + function sendReq(config, reqData) { var deferred = $q.defer(), promise = deferred.promise, cache, cachedResp, - url = buildUrl(config.url, config.params); + reqHeaders = config.headers, + isJsonp = lowercase(config.method) === 'jsonp', + url = config.url; + + if (isJsonp) { + // JSONP is a pretty sensitive operation where we're allowing a script to have full access to + // our DOM and JS space. So we require that the URL satisfies SCE.RESOURCE_URL. + url = $sce.getTrustedResourceUrl(url); + } else if (!isString(url)) { + // If it is not a string then the URL must be a $sce trusted object + url = $sce.valueOf(url); + } + + url = buildUrl(url, config.paramSerializer(config.params)); + + if (isJsonp) { + // Check the url and add the JSONP callback placeholder + url = sanitizeJsonpCallbackParam(url, config.jsonpCallbackParam); + } $http.pendingRequests.push(config); promise.then(removePendingReq, removePendingReq); - - if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') { + if ((config.cache || defaults.cache) && config.cache !== false && + (config.method === 'GET' || config.method === 'JSONP')) { cache = isObject(config.cache) ? config.cache - : isObject(defaults.cache) ? defaults.cache + : isObject(/** @type {?} */ (defaults).cache) + ? /** @type {?} */ (defaults).cache : defaultCache; } if (cache) { cachedResp = cache.get(url); if (isDefined(cachedResp)) { - if (cachedResp.then) { + if (isPromiseLike(cachedResp)) { // cached request has already been sent, but there is no response yet - cachedResp.then(removePendingReq, removePendingReq); - return cachedResp; + cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult); } else { // serving from cache if (isArray(cachedResp)) { - resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]), cachedResp[3]); + resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3], cachedResp[4]); } else { - resolvePromise(cachedResp, 200, {}, 'OK'); + resolvePromise(cachedResp, 200, {}, 'OK', 'complete'); } } } else { @@ -8175,14 +13404,47 @@ function $HttpProvider() { } } - // if we won't have the response in cache, send the request to the backend + + // if we won't have the response in cache, set the xsrf headers and + // send the request to the backend if (isUndefined(cachedResp)) { + var xsrfValue = urlIsAllowedOrigin(config.url) + ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName] + : undefined; + if (xsrfValue) { + reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue; + } + $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout, - config.withCredentials, config.responseType); + config.withCredentials, config.responseType, + createApplyHandlers(config.eventHandlers), + createApplyHandlers(config.uploadEventHandlers)); } return promise; + function createApplyHandlers(eventHandlers) { + if (eventHandlers) { + var applyHandlers = {}; + forEach(eventHandlers, function(eventHandler, key) { + applyHandlers[key] = function(event) { + if (useApplyAsync) { + $rootScope.$applyAsync(callEventHandler); + } else if ($rootScope.$$phase) { + callEventHandler(); + } else { + $rootScope.$apply(callEventHandler); + } + + function callEventHandler() { + eventHandler(event); + } + }; + }); + return applyHandlers; + } + } + /** * Callback registered to $httpBackend(): @@ -8190,89 +13452,127 @@ function $HttpProvider() { * - resolves the raw $http promise * - calls $apply */ - function done(status, response, headersString, statusText) { + function done(status, response, headersString, statusText, xhrStatus) { if (cache) { if (isSuccess(status)) { - cache.put(url, [status, response, parseHeaders(headersString), statusText]); + cache.put(url, [status, response, parseHeaders(headersString), statusText, xhrStatus]); } else { // remove promise from the cache cache.remove(url); } } - resolvePromise(response, status, headersString, statusText); - if (!$rootScope.$$phase) $rootScope.$apply(); + function resolveHttpPromise() { + resolvePromise(response, status, headersString, statusText, xhrStatus); + } + + if (useApplyAsync) { + $rootScope.$applyAsync(resolveHttpPromise); + } else { + resolveHttpPromise(); + if (!$rootScope.$$phase) $rootScope.$apply(); + } } /** * Resolves the raw $http promise. */ - function resolvePromise(response, status, headers, statusText) { - // normalize internal statuses to 0 - status = Math.max(status, 0); + function resolvePromise(response, status, headers, statusText, xhrStatus) { + //status: HTTP response status code, 0, -1 (aborted by timeout / promise) + status = status >= -1 ? status : 0; (isSuccess(status) ? deferred.resolve : deferred.reject)({ data: response, status: status, headers: headersGetter(headers), config: config, - statusText : statusText + statusText: statusText, + xhrStatus: xhrStatus }); } + function resolvePromiseWithResult(result) { + resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText, result.xhrStatus); + } function removePendingReq() { - var idx = indexOf($http.pendingRequests, config); + var idx = $http.pendingRequests.indexOf(config); if (idx !== -1) $http.pendingRequests.splice(idx, 1); } } - function buildUrl(url, params) { - if (!params) return url; - var parts = []; - forEachSorted(params, function(value, key) { - if (value === null || isUndefined(value)) return; - if (!isArray(value)) value = [value]; + function buildUrl(url, serializedParams) { + if (serializedParams.length > 0) { + url += ((url.indexOf('?') === -1) ? '?' : '&') + serializedParams; + } + return url; + } - forEach(value, function(v) { - if (isObject(v)) { - v = toJson(v); - } - parts.push(encodeUriQuery(key) + '=' + - encodeUriQuery(v)); - }); - }); - if(parts.length > 0) { - url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); - } - return url; + function sanitizeJsonpCallbackParam(url, cbKey) { + var parts = url.split('?'); + if (parts.length > 2) { + // Throw if the url contains more than one `?` query indicator + throw $httpMinErr('badjsonp', 'Illegal use more than one "?", in url, "{1}"', url); + } + var params = parseKeyValue(parts[1]); + forEach(params, function(value, key) { + if (value === 'JSON_CALLBACK') { + // Throw if the url already contains a reference to JSON_CALLBACK + throw $httpMinErr('badjsonp', 'Illegal use of JSON_CALLBACK in url, "{0}"', url); } + if (key === cbKey) { + // Throw if the callback param was already provided + throw $httpMinErr('badjsonp', 'Illegal use of callback param, "{0}", in url, "{1}"', cbKey, url); + } + }); + // Add in the JSON_CALLBACK callback param value + url += ((url.indexOf('?') === -1) ? '?' : '&') + cbKey + '=JSON_CALLBACK'; + return url; + } }]; } -function createXhr(method) { - //if IE and the method is not RFC2616 compliant, or if XMLHttpRequest - //is not available, try getting an ActiveXObject. Otherwise, use XMLHttpRequest - //if it is available - if (msie <= 8 && (!method.match(/^(get|post|head|put|delete|options)$/i) || - !window.XMLHttpRequest)) { - return new window.ActiveXObject("Microsoft.XMLHTTP"); - } else if (window.XMLHttpRequest) { +/** + * @ngdoc service + * @name $xhrFactory + * @this + * + * @description + * Factory function used to create XMLHttpRequest objects. + * + * Replace or decorate this service to create your own custom XMLHttpRequest objects. + * + * ``` + * angular.module('myApp', []) + * .factory('$xhrFactory', function() { + * return function createXhr(method, url) { + * return new window.XMLHttpRequest({mozSystem: true}); + * }; + * }); + * ``` + * + * @param {string} method HTTP method of the request (GET, POST, PUT, ..) + * @param {string} url URL of the request. + */ +function $xhrFactoryProvider() { + this.$get = function() { + return function createXhr() { return new window.XMLHttpRequest(); - } - - throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest."); + }; + }; } /** * @ngdoc service * @name $httpBackend - * @requires $window + * @requires $jsonpCallbacks * @requires $document + * @requires $xhrFactory + * @this * * @description * HTTP backend used by the {@link ng.$http service} that delegates to @@ -8285,38 +13585,28 @@ function createXhr(method) { * $httpBackend} which can be trained with responses. */ function $HttpBackendProvider() { - this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) { - return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]); + this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) { + return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]); }]; } function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) { - var ABORTED = -1; - // TODO(vojta): fix the signature - return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { - var status; - $browser.$$incOutstandingRequestCount(); + return function(method, url, post, callback, headers, timeout, withCredentials, responseType, eventHandlers, uploadEventHandlers) { url = url || $browser.url(); - if (lowercase(method) == 'jsonp') { - var callbackId = '_' + (callbacks.counter++).toString(36); - callbacks[callbackId] = function(data) { - callbacks[callbackId].data = data; - }; - - var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), - function() { - if (callbacks[callbackId].data) { - completeRequest(callback, 200, callbacks[callbackId].data); - } else { - completeRequest(callback, status || -2); - } - callbacks[callbackId] = angular.noop; + if (lowercase(method) === 'jsonp') { + var callbackPath = callbacks.createCallback(url); + var jsonpDone = jsonpReq(url, callbackPath, function(status, text) { + // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING) + var response = (status === 200) && callbacks.getResponse(callbackPath); + completeRequest(callback, status, response, '', text, 'complete'); + callbacks.removeCallback(callbackPath); }); } else { - var xhr = createXhr(method); + var xhr = createXhr(method, url); + var abortedByTimeout = false; xhr.open(method, url, true); forEach(headers, function(value, key) { @@ -8325,37 +13615,59 @@ function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDoc } }); - // In IE6 and 7, this might be called synchronously when xhr.send below is called and the - // response is in the cache. the promise api will ensure that to the app code the api is - // always async - xhr.onreadystatechange = function() { - // onreadystatechange might get called multiple times with readyState === 4 on mobile webkit caused by - // xhrs that are resolved while the app is in the background (see #5426). - // since calling completeRequest sets the `xhr` variable to null, we just check if it's not null before - // continuing - // - // we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and - // Safari respectively. - if (xhr && xhr.readyState == 4) { - var responseHeaders = null, - response = null; - - if(status !== ABORTED) { - responseHeaders = xhr.getAllResponseHeaders(); - - // responseText is the old-school way of retrieving response (supported by IE8 & 9) - // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) - response = ('response' in xhr) ? xhr.response : xhr.responseText; - } + xhr.onload = function requestLoaded() { + var statusText = xhr.statusText || ''; + + // responseText is the old-school way of retrieving response (supported by IE9) + // response/responseType properties were introduced in XHR Level2 spec (supported by IE10) + var response = ('response' in xhr) ? xhr.response : xhr.responseText; - completeRequest(callback, - status || xhr.status, - response, - responseHeaders, - xhr.statusText || ''); + // normalize IE9 bug (http://bugs.jquery.com/ticket/1450) + var status = xhr.status === 1223 ? 204 : xhr.status; + + // fix status code when it is 0 (0 status is undocumented). + // Occurs when accessing file resources or on Android 4.1 stock browser + // while retrieving files from application cache. + if (status === 0) { + status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0; } + + completeRequest(callback, + status, + response, + xhr.getAllResponseHeaders(), + statusText, + 'complete'); }; + var requestError = function() { + // The response is always empty + // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error + completeRequest(callback, -1, null, null, '', 'error'); + }; + + var requestAborted = function() { + completeRequest(callback, -1, null, null, '', abortedByTimeout ? 'timeout' : 'abort'); + }; + + var requestTimeout = function() { + // The response is always empty + // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error + completeRequest(callback, -1, null, null, '', 'timeout'); + }; + + xhr.onerror = requestError; + xhr.ontimeout = requestTimeout; + xhr.onabort = requestAborted; + + forEach(eventHandlers, function(value, key) { + xhr.addEventListener(key, value); + }); + + forEach(uploadEventHandlers, function(value, key) { + xhr.upload.addEventListener(key, value); + }); + if (withCredentials) { xhr.withCredentials = true; } @@ -8377,87 +13689,117 @@ function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDoc } } - xhr.send(post || null); + xhr.send(isUndefined(post) ? null : post); } + // Since we are using xhr.abort() when a request times out, we have to set a flag that + // indicates to requestAborted if the request timed out or was aborted. + // + // http.timeout = numerical timeout timeout + // http.timeout = $timeout timeout + // http.timeout = promise abort + // xhr.abort() abort (The xhr object is normally inaccessible, but + // can be exposed with the xhrFactory) if (timeout > 0) { - var timeoutId = $browserDefer(timeoutRequest, timeout); - } else if (timeout && timeout.then) { - timeout.then(timeoutRequest); + var timeoutId = $browserDefer(function() { + timeoutRequest('timeout'); + }, timeout); + } else if (isPromiseLike(timeout)) { + timeout.then(function() { + timeoutRequest(isDefined(timeout.$$timeoutId) ? 'timeout' : 'abort'); + }); } - - function timeoutRequest() { - status = ABORTED; - jsonpDone && jsonpDone(); - xhr && xhr.abort(); + function timeoutRequest(reason) { + abortedByTimeout = reason === 'timeout'; + if (jsonpDone) { + jsonpDone(); + } + if (xhr) { + xhr.abort(); + } } - function completeRequest(callback, status, response, headersString, statusText) { + function completeRequest(callback, status, response, headersString, statusText, xhrStatus) { // cancel timeout and subsequent timeout promise resolution - timeoutId && $browserDefer.cancel(timeoutId); - jsonpDone = xhr = null; - - // fix status code when it is 0 (0 status is undocumented). - // Occurs when accessing file resources or on Android 4.1 stock browser - // while retrieving files from application cache. - if (status === 0) { - status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0; + if (isDefined(timeoutId)) { + $browserDefer.cancel(timeoutId); } + jsonpDone = xhr = null; - // normalize IE bug (http://bugs.jquery.com/ticket/1450) - status = status === 1223 ? 204 : status; - statusText = statusText || ''; - - callback(status, response, headersString, statusText); - $browser.$$completeOutstandingRequest(noop); + callback(status, response, headersString, statusText, xhrStatus); } }; - function jsonpReq(url, done) { - // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.: + function jsonpReq(url, callbackPath, done) { + url = url.replace('JSON_CALLBACK', callbackPath); + // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.: // - fetches local scripts via XHR and evals them // - adds and immediately removes script elements from the document - var script = rawDocument.createElement('script'), - doneWrapper = function() { - script.onreadystatechange = script.onload = script.onerror = null; - rawDocument.body.removeChild(script); - if (done) done(); - }; - + var script = rawDocument.createElement('script'), callback = null; script.type = 'text/javascript'; script.src = url; - - if (msie && msie <= 8) { - script.onreadystatechange = function() { - if (/loaded|complete/.test(script.readyState)) { - doneWrapper(); + script.async = true; + + callback = function(event) { + script.removeEventListener('load', callback); + script.removeEventListener('error', callback); + rawDocument.body.removeChild(script); + script = null; + var status = -1; + var text = 'unknown'; + + if (event) { + if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) { + event = { type: 'error' }; } - }; - } else { - script.onload = script.onerror = function() { - doneWrapper(); - }; - } + text = event.type; + status = event.type === 'error' ? 404 : 200; + } + + if (done) { + done(status, text); + } + }; + script.addEventListener('load', callback); + script.addEventListener('error', callback); rawDocument.body.appendChild(script); - return doneWrapper; + return callback; } } -var $interpolateMinErr = minErr('$interpolate'); +var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate'); +$interpolateMinErr.throwNoconcat = function(text) { + throw $interpolateMinErr('noconcat', + 'Error while interpolating: {0}\nStrict Contextual Escaping disallows ' + + 'interpolations that concatenate multiple expressions when a trusted value is ' + + 'required. See http://docs.angularjs.org/api/ng.$sce', text); +}; + +$interpolateMinErr.interr = function(text, err) { + return $interpolateMinErr('interr', 'Can\'t interpolate: {0}\n{1}', text, err.toString()); +}; /** * @ngdoc provider * @name $interpolateProvider - * @function + * @this * * @description * * Used for configuring the interpolation markup. Defaults to `{{` and `}}`. * + *
+ * This feature is sometimes used to mix different markup languages, e.g. to wrap an AngularJS + * template within a Python Jinja template (or any other template language). Mixing templating + * languages is **very dangerous**. The embedding template language will not safely escape AngularJS + * expressions, so any user-controlled values in the template will cause Cross Site Scripting (XSS) + * security bugs! + *
+ * * @example - + -
+
//demo.label//
@@ -8496,13 +13838,12 @@ function $InterpolateProvider() { * @param {string=} value new value to set the starting symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ - this.startSymbol = function(value){ + this.startSymbol = function(value) { if (value) { startSymbol = value; return this; - } else { - return startSymbol; } + return startSymbol; }; /** @@ -8514,24 +13855,43 @@ function $InterpolateProvider() { * @param {string=} value new value to set the ending symbol to. * @returns {string|self} Returns the symbol when used as getter and self if used as setter. */ - this.endSymbol = function(value){ + this.endSymbol = function(value) { if (value) { endSymbol = value; return this; - } else { - return endSymbol; } + return endSymbol; }; this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) { var startSymbolLength = startSymbol.length, - endSymbolLength = endSymbol.length; + endSymbolLength = endSymbol.length, + escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'), + escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g'); + + function escape(ch) { + return '\\\\\\' + ch; + } + + function unescapeText(text) { + return text.replace(escapedStartRegexp, startSymbol). + replace(escapedEndRegexp, endSymbol); + } + + // TODO: this is the same as the constantWatchDelegate in parse.js + function constantWatchDelegate(scope, listener, objectEquality, constantInterp) { + var unwatch = scope.$watch(function constantInterpolateWatch(scope) { + unwatch(); + return constantInterp(scope); + }, listener, objectEquality); + return unwatch; + } /** * @ngdoc service * @name $interpolate - * @function + * @kind function * * @requires $parse * @requires $sce @@ -8547,9 +13907,89 @@ function $InterpolateProvider() { * ```js * var $interpolate = ...; // injected * var exp = $interpolate('Hello {{name | uppercase}}!'); - * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!'); + * expect(exp({name:'AngularJS'})).toEqual('Hello ANGULARJS!'); + * ``` + * + * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is + * `true`, the interpolation function will return `undefined` unless all embedded expressions + * evaluate to a value other than `undefined`. + * + * ```js + * var $interpolate = ...; // injected + * var context = {greeting: 'Hello', name: undefined }; + * + * // default "forgiving" mode + * var exp = $interpolate('{{greeting}} {{name}}!'); + * expect(exp(context)).toEqual('Hello !'); + * + * // "allOrNothing" mode + * exp = $interpolate('{{greeting}} {{name}}!', false, null, true); + * expect(exp(context)).toBeUndefined(); + * context.name = 'AngularJS'; + * expect(exp(context)).toEqual('Hello AngularJS!'); + * ``` + * + * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior. + * + * #### Escaped Interpolation + * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers + * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash). + * It will be rendered as a regular start/end marker, and will not be interpreted as an expression + * or binding. + * + * This enables web-servers to prevent script injection attacks and defacing attacks, to some + * degree, while also enabling code examples to work without relying on the + * {@link ng.directive:ngNonBindable ngNonBindable} directive. + * + * **For security purposes, it is strongly encouraged that web servers escape user-supplied data, + * replacing angle brackets (<, >) with &lt; and &gt; respectively, and replacing all + * interpolation start/end markers with their escaped counterparts.** + * + * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered + * output when the $interpolate service processes the text. So, for HTML elements interpolated + * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter + * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such, + * this is typically useful only when user-data is used in rendering a template from the server, or + * when otherwise untrusted data is used by a directive. + * + * + * + *
+ *

{{apptitle}}: \{\{ username = "defaced value"; \}\} + *

+ *

{{username}} attempts to inject code which will deface the + * application, but fails to accomplish their task, because the server has correctly + * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash) + * characters.

+ *

Instead, the result of the attempted script injection is visible, and can be removed + * from the database by an administrator.

+ *
+ *
+ *
+ * + * @knownIssue + * It is currently not possible for an interpolated expression to contain the interpolation end + * symbol. For example, `{{ '}}' }}` will be incorrectly interpreted as `{{ ' }}` + `' }}`, i.e. + * an interpolated expression consisting of a single-quote (`'`) and the `' }}` string. + * + * @knownIssue + * All directives and components must use the standard `{{` `}}` interpolation symbols + * in their templates. If you change the application interpolation symbols the {@link $compile} + * service will attempt to denormalize the standard symbols to the custom symbols. + * The denormalization process is not clever enough to know not to replace instances of the standard + * symbols where they would not normally be treated as interpolation symbols. For example in the following + * code snippet the closing braces of the literal object will get incorrectly denormalized: + * + * ``` + *
* ``` * + * See https://github.com/angular/angular.js/pull/14610#issuecomment-219401099 for more information. * * @param {string} text The text with markup to interpolate. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have @@ -8559,89 +13999,146 @@ function $InterpolateProvider() { * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult, * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that * provides Strict Contextual Escaping for details. + * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined + * unless all embedded expressions evaluate to a value other than `undefined`. * @returns {function(context)} an interpolation function which is used to compute the * interpolated string. The function has these parameters: * - * * `context`: an object against which any expressions embedded in the strings are evaluated - * against. - * + * - `context`: evaluation context for all expressions embedded in the interpolated text */ - function $interpolate(text, mustHaveExpression, trustedContext) { + function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) { + var contextAllowsConcatenation = trustedContext === $sce.URL || trustedContext === $sce.MEDIA_URL; + + // Provide a quick exit and simplified result function for text with no interpolation + if (!text.length || text.indexOf(startSymbol) === -1) { + if (mustHaveExpression) return; + + var unescapedText = unescapeText(text); + if (contextAllowsConcatenation) { + unescapedText = $sce.getTrusted(trustedContext, unescapedText); + } + var constantInterp = valueFn(unescapedText); + constantInterp.exp = text; + constantInterp.expressions = []; + constantInterp.$$watchDelegate = constantWatchDelegate; + + return constantInterp; + } + + allOrNothing = !!allOrNothing; var startIndex, endIndex, index = 0, - parts = [], - length = text.length, - hasInterpolation = false, - fn, + expressions = [], + parseFns, + textLength = text.length, exp, - concat = []; - - while(index < length) { - if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) && - ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) { - (index != startIndex) && parts.push(text.substring(index, startIndex)); - parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex))); - fn.exp = exp; + concat = [], + expressionPositions = [], + singleExpression; + + + while (index < textLength) { + if (((startIndex = text.indexOf(startSymbol, index)) !== -1) && + ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) !== -1)) { + if (index !== startIndex) { + concat.push(unescapeText(text.substring(index, startIndex))); + } + exp = text.substring(startIndex + startSymbolLength, endIndex); + expressions.push(exp); index = endIndex + endSymbolLength; - hasInterpolation = true; + expressionPositions.push(concat.length); + concat.push(''); // Placeholder that will get replaced with the evaluated expression. } else { - // we did not find anything, so we have to add the remainder to the parts array - (index != length) && parts.push(text.substring(index)); - index = length; + // we did not find an interpolation, so we have to add the remainder to the separators array + if (index !== textLength) { + concat.push(unescapeText(text.substring(index))); + } + break; } } - if (!(length = parts.length)) { - // we added, nothing, must have been an empty string. - parts.push(''); - length = 1; - } + singleExpression = concat.length === 1 && expressionPositions.length === 1; + // Intercept expression if we need to stringify concatenated inputs, which may be SCE trusted + // objects rather than simple strings + // (we don't modify the expression if the input consists of only a single trusted input) + var interceptor = contextAllowsConcatenation && singleExpression ? undefined : parseStringifyInterceptor; + parseFns = expressions.map(function(exp) { return $parse(exp, interceptor); }); // Concatenating expressions makes it hard to reason about whether some combination of // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a - // single expression be used for iframe[src], object[src], etc., we ensure that the value - // that's used is assigned or constructed by some JS code somewhere that is more testable or - // make it obvious that you bound the value to some user controlled value. This helps reduce - // the load when auditing for XSS issues. - if (trustedContext && parts.length > 1) { - throw $interpolateMinErr('noconcat', - "Error while interpolating: {0}\nStrict Contextual Escaping disallows " + - "interpolations that concatenate multiple expressions when a trusted value is " + - "required. See http://docs.angularjs.org/api/ng.$sce", text); - } - - if (!mustHaveExpression || hasInterpolation) { - concat.length = length; - fn = function(context) { - try { - for(var i = 0, ii = length, part; i 1) { + // This context does not allow more than one part, e.g. expr + string or exp + exp. + $interpolateMinErr.throwNoconcat(text); } + // In an unprivileged context or only one part: just concatenate and return. + return concat.join(''); }; - fn.exp = text; - fn.parts = parts; - return fn; + + return extend(function interpolationFn(context) { + var i = 0; + var ii = expressions.length; + var values = new Array(ii); + + try { + for (; i < ii; i++) { + values[i] = parseFns[i](context); + } + + return compute(values); + } catch (err) { + $exceptionHandler($interpolateMinErr.interr(text, err)); + } + + }, { + // all of these properties are undocumented for now + exp: text, //just for compatibility with regular watchers created via $watch + expressions: expressions, + $$watchDelegate: function(scope, listener) { + var lastValue; + return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) { + var currValue = compute(values); + listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope); + lastValue = currValue; + }); + } + }); + } + + function parseStringifyInterceptor(value) { + try { + // In concatenable contexts, getTrusted comes at the end, to avoid sanitizing individual + // parts of a full URL. We don't care about losing the trustedness here. + // In non-concatenable contexts, where there is only one expression, this interceptor is + // not applied to the expression. + value = (trustedContext && !contextAllowsConcatenation) ? + $sce.getTrusted(trustedContext, value) : + $sce.valueOf(value); + return allOrNothing && !isDefined(value) ? value : stringify(value); + } catch (err) { + $exceptionHandler($interpolateMinErr.interr(text, err)); + } } } @@ -8652,7 +14149,7 @@ function $InterpolateProvider() { * @description * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`. * - * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change + * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change * the symbol. * * @returns {string} start symbol. @@ -8668,7 +14165,7 @@ function $InterpolateProvider() { * @description * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`. * - * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change + * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change * the symbol. * * @returns {string} end symbol. @@ -8681,263 +14178,328 @@ function $InterpolateProvider() { }]; } +var $intervalMinErr = minErr('$interval'); + +/** @this */ function $IntervalProvider() { - this.$get = ['$rootScope', '$window', '$q', - function($rootScope, $window, $q) { + this.$get = ['$$intervalFactory', '$window', + function($$intervalFactory, $window) { var intervals = {}; + var setIntervalFn = function(tick, delay, deferred) { + var id = $window.setInterval(tick, delay); + intervals[id] = deferred; + return id; + }; + var clearIntervalFn = function(id) { + $window.clearInterval(id); + delete intervals[id]; + }; + /** + * @ngdoc service + * @name $interval + * + * @description + * AngularJS's wrapper for `window.setInterval`. The `fn` function is executed every `delay` + * milliseconds. + * + * The return value of registering an interval function is a promise. This promise will be + * notified upon each tick of the interval, and will be resolved after `count` iterations, or + * run indefinitely if `count` is not defined. The value of the notification will be the + * number of iterations that have run. + * To cancel an interval, call `$interval.cancel(promise)`. + * + * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to + * move forward by `millis` milliseconds and trigger any functions scheduled to run in that + * time. + * + *
+ * **Note**: Intervals created by this service must be explicitly destroyed when you are finished + * with them. In particular they are not automatically destroyed when a controller's scope or a + * directive's element are destroyed. + * You should take this into consideration and make sure to always cancel the interval at the + * appropriate moment. See the example below for more details on how and when to do this. + *
+ * + * @param {function()} fn A function that should be called repeatedly. If no additional arguments + * are passed (see below), the function is called with the current iteration count. + * @param {number} delay Number of milliseconds between each function call. + * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat + * indefinitely. + * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise + * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. + * @param {...*=} Pass additional parameters to the executed function. + * @returns {promise} A promise which will be notified on each iteration. It will resolve once all iterations of the interval complete. + * + * @example + * + * + * + * + *
+ *
+ *
+ * Current time is: + *
+ * Blood 1 : {{blood_1}} + * Blood 2 : {{blood_2}} + * + * + * + *
+ *
+ * + *
+ *
+ */ + var interval = $$intervalFactory(setIntervalFn, clearIntervalFn); - /** - * @ngdoc service - * @name $interval - * - * @description - * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay` - * milliseconds. - * - * The return value of registering an interval function is a promise. This promise will be - * notified upon each tick of the interval, and will be resolved after `count` iterations, or - * run indefinitely if `count` is not defined. The value of the notification will be the - * number of iterations that have run. - * To cancel an interval, call `$interval.cancel(promise)`. - * - * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to - * move forward by `millis` milliseconds and trigger any functions scheduled to run in that - * time. - * - *
- * **Note**: Intervals created by this service must be explicitly destroyed when you are finished - * with them. In particular they are not automatically destroyed when a controller's scope or a - * directive's element are destroyed. - * You should take this into consideration and make sure to always cancel the interval at the - * appropriate moment. See the example below for more details on how and when to do this. - *
- * - * @param {function()} fn A function that should be called repeatedly. - * @param {number} delay Number of milliseconds between each function call. - * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat - * indefinitely. - * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise - * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. - * @returns {promise} A promise which will be notified on each iteration. - * - * @example - * - * - * - * - *
- *
- * Date format:
- * Current time is: - *
- * Blood 1 : {{blood_1}} - * Blood 2 : {{blood_2}} - * - * - * - *
- *
- * - *
- *
- */ - function interval(fn, delay, count, invokeApply) { - var setInterval = $window.setInterval, - clearInterval = $window.clearInterval, - deferred = $q.defer(), - promise = deferred.promise, - iteration = 0, - skipApply = (isDefined(invokeApply) && !invokeApply); + /** + * @ngdoc method + * @name $interval#cancel + * + * @description + * Cancels a task associated with the `promise`. + * + * @param {Promise=} promise returned by the `$interval` function. + * @returns {boolean} Returns `true` if the task was successfully canceled. + */ + interval.cancel = function(promise) { + if (!promise) return false; - count = isDefined(count) ? count : 0; + if (!promise.hasOwnProperty('$$intervalId')) { + throw $intervalMinErr('badprom', + '`$interval.cancel()` called with a promise that was not generated by `$interval()`.'); + } - promise.then(null, null, fn); + if (!intervals.hasOwnProperty(promise.$$intervalId)) return false; - promise.$$intervalId = setInterval(function tick() { - deferred.notify(iteration++); + var id = promise.$$intervalId; + var deferred = intervals[id]; - if (count > 0 && iteration >= count) { - deferred.resolve(iteration); - clearInterval(promise.$$intervalId); - delete intervals[promise.$$intervalId]; - } + // Interval cancels should not report an unhandled promise. + markQExceptionHandled(deferred.promise); + deferred.reject('canceled'); + clearIntervalFn(id); - if (!skipApply) $rootScope.$apply(); + return true; + }; + + return interval; + }]; +} + +/** @this */ +function $$IntervalFactoryProvider() { + this.$get = ['$browser', '$q', '$$q', '$rootScope', + function($browser, $q, $$q, $rootScope) { + return function intervalFactory(setIntervalFn, clearIntervalFn) { + return function intervalFn(fn, delay, count, invokeApply) { + var hasParams = arguments.length > 4, + args = hasParams ? sliceArgs(arguments, 4) : [], + iteration = 0, + skipApply = isDefined(invokeApply) && !invokeApply, + deferred = (skipApply ? $$q : $q).defer(), + promise = deferred.promise; + + count = isDefined(count) ? count : 0; + + function callback() { + if (!hasParams) { + fn(iteration); + } else { + fn.apply(null, args); + } + } - }, delay); + function tick() { + if (skipApply) { + $browser.defer(callback); + } else { + $rootScope.$evalAsync(callback); + } + deferred.notify(iteration++); - intervals[promise.$$intervalId] = deferred; + if (count > 0 && iteration >= count) { + deferred.resolve(iteration); + clearIntervalFn(promise.$$intervalId); + } - return promise; - } + if (!skipApply) $rootScope.$apply(); + } + promise.$$intervalId = setIntervalFn(tick, delay, deferred, skipApply); - /** - * @ngdoc method - * @name $interval#cancel - * - * @description - * Cancels a task associated with the `promise`. - * - * @param {promise} promise returned by the `$interval` function. - * @returns {boolean} Returns `true` if the task was successfully canceled. - */ - interval.cancel = function(promise) { - if (promise && promise.$$intervalId in intervals) { - intervals[promise.$$intervalId].reject('canceled'); - clearInterval(promise.$$intervalId); - delete intervals[promise.$$intervalId]; - return true; - } - return false; + return promise; + }; }; - - return interval; }]; } /** * @ngdoc service - * @name $locale - * + * @name $jsonpCallbacks + * @requires $window * @description - * $locale service provides localization rules for various Angular components. As of right now the - * only public api is: - * - * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) + * This service handles the lifecycle of callbacks to handle JSONP requests. + * Override this service if you wish to customise where the callbacks are stored and + * how they vary compared to the requested url. */ -function $LocaleProvider(){ +var $jsonpCallbacksProvider = /** @this */ function() { this.$get = function() { + var callbacks = angular.callbacks; + var callbackMap = {}; + + function createCallback(callbackId) { + var callback = function(data) { + callback.data = data; + callback.called = true; + }; + callback.id = callbackId; + return callback; + } + return { - id: 'en-us', - - NUMBER_FORMATS: { - DECIMAL_SEP: '.', - GROUP_SEP: ',', - PATTERNS: [ - { // Decimal Pattern - minInt: 1, - minFrac: 0, - maxFrac: 3, - posPre: '', - posSuf: '', - negPre: '-', - negSuf: '', - gSize: 3, - lgSize: 3 - },{ //Currency Pattern - minInt: 1, - minFrac: 2, - maxFrac: 2, - posPre: '\u00A4', - posSuf: '', - negPre: '(\u00A4', - negSuf: ')', - gSize: 3, - lgSize: 3 - } - ], - CURRENCY_SYM: '$' + /** + * @ngdoc method + * @name $jsonpCallbacks#createCallback + * @param {string} url the url of the JSONP request + * @returns {string} the callback path to send to the server as part of the JSONP request + * @description + * {@link $httpBackend} calls this method to create a callback and get hold of the path to the callback + * to pass to the server, which will be used to call the callback with its payload in the JSONP response. + */ + createCallback: function(url) { + var callbackId = '_' + (callbacks.$$counter++).toString(36); + var callbackPath = 'angular.callbacks.' + callbackId; + var callback = createCallback(callbackId); + callbackMap[callbackPath] = callbacks[callbackId] = callback; + return callbackPath; }, - - DATETIME_FORMATS: { - MONTH: - 'January,February,March,April,May,June,July,August,September,October,November,December' - .split(','), - SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','), - DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','), - SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','), - AMPMS: ['AM','PM'], - medium: 'MMM d, y h:mm:ss a', - short: 'M/d/yy h:mm a', - fullDate: 'EEEE, MMMM d, y', - longDate: 'MMMM d, y', - mediumDate: 'MMM d, y', - shortDate: 'M/d/yy', - mediumTime: 'h:mm:ss a', - shortTime: 'h:mm a' + /** + * @ngdoc method + * @name $jsonpCallbacks#wasCalled + * @param {string} callbackPath the path to the callback that was sent in the JSONP request + * @returns {boolean} whether the callback has been called, as a result of the JSONP response + * @description + * {@link $httpBackend} calls this method to find out whether the JSONP response actually called the + * callback that was passed in the request. + */ + wasCalled: function(callbackPath) { + return callbackMap[callbackPath].called; }, - - pluralCat: function(num) { - if (num === 1) { - return 'one'; - } - return 'other'; + /** + * @ngdoc method + * @name $jsonpCallbacks#getResponse + * @param {string} callbackPath the path to the callback that was sent in the JSONP request + * @returns {*} the data received from the response via the registered callback + * @description + * {@link $httpBackend} calls this method to get hold of the data that was provided to the callback + * in the JSONP response. + */ + getResponse: function(callbackPath) { + return callbackMap[callbackPath].data; + }, + /** + * @ngdoc method + * @name $jsonpCallbacks#removeCallback + * @param {string} callbackPath the path to the callback that was sent in the JSONP request + * @description + * {@link $httpBackend} calls this method to remove the callback after the JSONP request has + * completed or timed-out. + */ + removeCallback: function(callbackPath) { + var callback = callbackMap[callbackPath]; + delete callbacks[callback.id]; + delete callbackMap[callbackPath]; } }; }; -} +}; + +/** + * @ngdoc service + * @name $locale + * + * @description + * $locale service provides localization rules for various AngularJS components. As of right now the + * only public api is: + * + * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`) + */ + +/* global stripHash: true */ -var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, +var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; var $locationMinErr = minErr('$location'); @@ -8953,59 +14515,89 @@ function encodePath(path) { i = segments.length; while (i--) { - segments[i] = encodeUriSegment(segments[i]); + // decode forward slashes to prevent them from being double encoded + segments[i] = encodeUriSegment(segments[i].replace(/%2F/g, '/')); + } + + return segments.join('/'); +} + +function decodePath(path, html5Mode) { + var segments = path.split('/'), + i = segments.length; + + while (i--) { + segments[i] = decodeURIComponent(segments[i]); + if (html5Mode) { + // encode forward slashes to prevent them from being mistaken for path separators + segments[i] = segments[i].replace(/\//g, '%2F'); + } } return segments.join('/'); } -function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) { - var parsedUrl = urlResolve(absoluteUrl, appBase); +function normalizePath(pathValue, searchValue, hashValue) { + var search = toKeyValue(searchValue), + hash = hashValue ? '#' + encodeUriSegment(hashValue) : '', + path = encodePath(pathValue); + + return path + (search ? '?' + search : '') + hash; +} + +function parseAbsoluteUrl(absoluteUrl, locationObj) { + var parsedUrl = urlResolve(absoluteUrl); locationObj.$$protocol = parsedUrl.protocol; locationObj.$$host = parsedUrl.hostname; - locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; + locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null; } +var DOUBLE_SLASH_REGEX = /^\s*[\\/]{2,}/; +function parseAppUrl(url, locationObj, html5Mode) { -function parseAppUrl(relativeUrl, locationObj, appBase) { - var prefixed = (relativeUrl.charAt(0) !== '/'); + if (DOUBLE_SLASH_REGEX.test(url)) { + throw $locationMinErr('badpath', 'Invalid url "{0}".', url); + } + + var prefixed = (url.charAt(0) !== '/'); if (prefixed) { - relativeUrl = '/' + relativeUrl; + url = '/' + url; } - var match = urlResolve(relativeUrl, appBase); - locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ? - match.pathname.substring(1) : match.pathname); + var match = urlResolve(url); + var path = prefixed && match.pathname.charAt(0) === '/' ? match.pathname.substring(1) : match.pathname; + locationObj.$$path = decodePath(path, html5Mode); locationObj.$$search = parseKeyValue(match.search); locationObj.$$hash = decodeURIComponent(match.hash); // make sure path starts with '/'; - if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') { + if (locationObj.$$path && locationObj.$$path.charAt(0) !== '/') { locationObj.$$path = '/' + locationObj.$$path; } } +function startsWith(str, search) { + return str.slice(0, search.length) === search; +} /** * - * @param {string} begin - * @param {string} whole - * @returns {string} returns text from whole after begin or undefined if it does not begin with - * expected string. + * @param {string} base + * @param {string} url + * @returns {string} returns text from `url` after `base` or `undefined` if it does not begin with + * the expected string. */ -function beginsWith(begin, whole) { - if (whole.indexOf(begin) === 0) { - return whole.substr(begin.length); +function stripBaseUrl(base, url) { + if (startsWith(url, base)) { + return url.substr(base.length); } } - function stripHash(url) { var index = url.indexOf('#'); - return index == -1 ? url : url.substr(0, index); + return index === -1 ? url : url.substr(0, index); } - function stripFile(url) { return url.substr(0, stripHash(url).lastIndexOf('/') + 1); } @@ -9017,33 +14609,33 @@ function serverBase(url) { /** - * LocationHtml5Url represents an url + * LocationHtml5Url represents a URL * This object is exposed as $location service when HTML5 mode is enabled and supported * * @constructor * @param {string} appBase application base URL - * @param {string} basePrefix url path prefix + * @param {string} appBaseNoFile application base URL stripped of any filename + * @param {string} basePrefix URL path prefix */ -function LocationHtml5Url(appBase, basePrefix) { +function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) { this.$$html5 = true; basePrefix = basePrefix || ''; - var appBaseNoFile = stripFile(appBase); - parseAbsoluteUrl(appBase, this, appBase); + parseAbsoluteUrl(appBase, this); /** - * Parse given html5 (regular) url string into properties - * @param {string} newAbsoluteUrl HTML5 url + * Parse given HTML5 (regular) URL string into properties + * @param {string} url HTML5 URL * @private */ this.$$parse = function(url) { - var pathUrl = beginsWith(appBaseNoFile, url); + var pathUrl = stripBaseUrl(appBaseNoFile, url); if (!isString(pathUrl)) { throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url, appBaseNoFile); } - parseAppUrl(pathUrl, this, appBase); + parseAppUrl(pathUrl, this, true); if (!this.$$path) { this.$$path = '/'; @@ -9052,70 +14644,91 @@ function LocationHtml5Url(appBase, basePrefix) { this.$$compose(); }; - /** - * Compose url and update `absUrl` property - * @private - */ - this.$$compose = function() { - var search = toKeyValue(this.$$search), - hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; - - this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; - this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/' + this.$$normalizeUrl = function(url) { + return appBaseNoFile + url.substr(1); // first char is always '/' }; - this.$$rewrite = function(url) { + this.$$parseLinkUrl = function(url, relHref) { + if (relHref && relHref[0] === '#') { + // special case for links to hash fragments: + // keep the old url and only replace the hash fragment + this.hash(relHref.slice(1)); + return true; + } var appUrl, prevAppUrl; + var rewrittenUrl; + - if ( (appUrl = beginsWith(appBase, url)) !== undefined ) { + if (isDefined(appUrl = stripBaseUrl(appBase, url))) { prevAppUrl = appUrl; - if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) { - return appBaseNoFile + (beginsWith('/', appUrl) || appUrl); + if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) { + rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl); } else { - return appBase + prevAppUrl; + rewrittenUrl = appBase + prevAppUrl; } - } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) { - return appBaseNoFile + appUrl; - } else if (appBaseNoFile == url + '/') { - return appBaseNoFile; + } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) { + rewrittenUrl = appBaseNoFile + appUrl; + } else if (appBaseNoFile === url + '/') { + rewrittenUrl = appBaseNoFile; } + if (rewrittenUrl) { + this.$$parse(rewrittenUrl); + } + return !!rewrittenUrl; }; } /** - * LocationHashbangUrl represents url + * LocationHashbangUrl represents URL * This object is exposed as $location service when developer doesn't opt into html5 mode. * It also serves as the base class for html5 mode fallback on legacy browsers. * * @constructor * @param {string} appBase application base URL + * @param {string} appBaseNoFile application base URL stripped of any filename * @param {string} hashPrefix hashbang prefix */ -function LocationHashbangUrl(appBase, hashPrefix) { - var appBaseNoFile = stripFile(appBase); +function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) { - parseAbsoluteUrl(appBase, this, appBase); + parseAbsoluteUrl(appBase, this); /** - * Parse given hashbang url into properties - * @param {string} url Hashbang url + * Parse given hashbang URL into properties + * @param {string} url Hashbang URL * @private */ this.$$parse = function(url) { - var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url); - var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' - ? beginsWith(hashPrefix, withoutBaseUrl) - : (this.$$html5) - ? withoutBaseUrl - : ''; + var withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url); + var withoutHashUrl; + + if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') { + + // The rest of the URL starts with a hash so we have + // got either a hashbang path or a plain hash fragment + withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl); + if (isUndefined(withoutHashUrl)) { + // There was no hashbang prefix so we just have a hash fragment + withoutHashUrl = withoutBaseUrl; + } - if (!isString(withoutHashUrl)) { - throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url, - hashPrefix); + } else { + // There was no hashbang path nor hash fragment: + // If we are in HTML5 mode we use what is left as the path; + // Otherwise we ignore what is left + if (this.$$html5) { + withoutHashUrl = withoutBaseUrl; + } else { + withoutHashUrl = ''; + if (isUndefined(withoutBaseUrl)) { + appBase = url; + /** @type {?} */ (this).replace(); + } + } } - parseAppUrl(withoutHashUrl, this, appBase); + + parseAppUrl(withoutHashUrl, this, false); this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase); @@ -9129,27 +14742,24 @@ function LocationHashbangUrl(appBase, hashPrefix) { * * a.setAttribute('href', '/foo') * * a.pathname === '/C:/foo' //true * - * Inside of Angular, we're always using pathnames that + * Inside of AngularJS, we're always using pathnames that * do not include drive names for routing. */ - function removeWindowsDriveName (path, url, base) { + function removeWindowsDriveName(path, url, base) { /* Matches paths for file protocol on windows, such as /C:/foo/bar, and captures only /foo/bar. */ - var windowsFilePathExp = /^\/?.*?:(\/.*)/; + var windowsFilePathExp = /^\/[A-Z]:(\/.*)/; var firstPathSegmentMatch; //Get the relative path from the input URL. - if (url.indexOf(base) === 0) { + if (startsWith(url, base)) { url = url.replace(base, ''); } - /* - * The input URL intentionally contains a - * first path segment that ends with a colon. - */ + // The input URL intentionally contains a first path segment that ends with a colon. if (windowsFilePathExp.exec(url)) { return path; } @@ -9159,58 +14769,72 @@ function LocationHashbangUrl(appBase, hashPrefix) { } }; - /** - * Compose hashbang url and update `absUrl` property - * @private - */ - this.$$compose = function() { - var search = toKeyValue(this.$$search), - hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; - - this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; - this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : ''); + this.$$normalizeUrl = function(url) { + return appBase + (url ? hashPrefix + url : ''); }; - this.$$rewrite = function(url) { - if(stripHash(appBase) == stripHash(url)) { - return url; + this.$$parseLinkUrl = function(url, relHref) { + if (stripHash(appBase) === stripHash(url)) { + this.$$parse(url); + return true; } + return false; }; } /** - * LocationHashbangUrl represents url + * LocationHashbangUrl represents URL * This object is exposed as $location service when html5 history api is enabled but the browser * does not support it. * * @constructor * @param {string} appBase application base URL + * @param {string} appBaseNoFile application base URL stripped of any filename * @param {string} hashPrefix hashbang prefix */ -function LocationHashbangInHtml5Url(appBase, hashPrefix) { +function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) { this.$$html5 = true; LocationHashbangUrl.apply(this, arguments); - var appBaseNoFile = stripFile(appBase); + this.$$parseLinkUrl = function(url, relHref) { + if (relHref && relHref[0] === '#') { + // special case for links to hash fragments: + // keep the old url and only replace the hash fragment + this.hash(relHref.slice(1)); + return true; + } - this.$$rewrite = function(url) { + var rewrittenUrl; var appUrl; - if ( appBase == stripHash(url) ) { - return url; - } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) { - return appBase + hashPrefix + appUrl; - } else if ( appBaseNoFile === url + '/') { - return appBaseNoFile; + if (appBase === stripHash(url)) { + rewrittenUrl = url; + } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) { + rewrittenUrl = appBase + hashPrefix + appUrl; + } else if (appBaseNoFile === url + '/') { + rewrittenUrl = appBaseNoFile; + } + if (rewrittenUrl) { + this.$$parse(rewrittenUrl); } + return !!rewrittenUrl; + }; + + this.$$normalizeUrl = function(url) { + // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#' + return appBase + hashPrefix + url; }; } -LocationHashbangInHtml5Url.prototype = - LocationHashbangUrl.prototype = - LocationHtml5Url.prototype = { +var locationPrototype = { + + /** + * Ensure absolute URL is initialized. + * @private + */ + $$absUrl:'', /** * Are we in html5 mode? @@ -9219,11 +14843,21 @@ LocationHashbangInHtml5Url.prototype = $$html5: false, /** - * Has any change been replacing ? + * Has any change been replacing? * @private */ $$replace: false, + /** + * Compose url and update `url` and `absUrl` property + * @private + */ + $$compose: function() { + this.$$url = normalizePath(this.$$path, this.$$search, this.$$hash); + this.$$absUrl = this.$$normalizeUrl(this.$$url); + this.$$urlUpdatedByLocation = true; + }, + /** * @ngdoc method * @name $location#absUrl @@ -9231,10 +14865,17 @@ LocationHashbangInHtml5Url.prototype = * @description * This method is getter only. * - * Return full url representation with all segments encoded according to rules specified in + * Return full URL representation with all segments encoded according to rules specified in * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt). * - * @return {string} full url + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var absUrl = $location.absUrl(); + * // => "http://example.com/#/some/path?foo=bar&baz=xoxo" + * ``` + * + * @return {string} full URL */ absUrl: locationGetter('$$absUrl'), @@ -9245,22 +14886,29 @@ LocationHashbangInHtml5Url.prototype = * @description * This method is getter / setter. * - * Return url (e.g. `/path?a=b#hash`) when called without any parameter. + * Return URL (e.g. `/path?a=b#hash`) when called without any parameter. * * Change path, search and hash, when called with parameter and return `$location`. * - * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`) - * @param {string=} replace The path that will be changed + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var url = $location.url(); + * // => "/some/path?foo=bar&baz=xoxo" + * ``` + * + * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`) * @return {string} url */ - url: function(url, replace) { - if (isUndefined(url)) + url: function(url) { + if (isUndefined(url)) { return this.$$url; + } var match = PATH_MATCH.exec(url); - if (match[1]) this.path(decodeURIComponent(match[1])); - if (match[2] || match[1]) this.search(match[3] || ''); - this.hash(match[5] || '', replace); + if (match[1] || url === '') this.path(decodeURIComponent(match[1])); + if (match[2] || match[1] || url === '') this.search(match[3] || ''); + this.hash(match[5] || ''); return this; }, @@ -9272,9 +14920,16 @@ LocationHashbangInHtml5Url.prototype = * @description * This method is getter only. * - * Return protocol of current url. + * Return protocol of current URL. + * + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var protocol = $location.protocol(); + * // => "http" + * ``` * - * @return {string} protocol of current url + * @return {string} protocol of current URL */ protocol: locationGetter('$$protocol'), @@ -9285,9 +14940,24 @@ LocationHashbangInHtml5Url.prototype = * @description * This method is getter only. * - * Return host of current url. + * Return host of current URL. + * + * Note: compared to the non-AngularJS version `location.host` which returns `hostname:port`, this returns the `hostname` portion only. + * + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var host = $location.host(); + * // => "example.com" + * + * // given URL http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo + * host = $location.host(); + * // => "example.com" + * host = location.host; + * // => "example.com:8080" + * ``` * - * @return {string} host of current url. + * @return {string} host of current URL. */ host: locationGetter('$$host'), @@ -9298,7 +14968,14 @@ LocationHashbangInHtml5Url.prototype = * @description * This method is getter only. * - * Return port of current url. + * Return port of current URL. + * + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var port = $location.port(); + * // => 80 + * ``` * * @return {Number} port */ @@ -9311,18 +14988,26 @@ LocationHashbangInHtml5Url.prototype = * @description * This method is getter / setter. * - * Return path of current url when called without any parameter. + * Return path of current URL when called without any parameter. * * Change path when called with parameter and return `$location`. * * Note: Path should always begin with forward slash (/), this method will add the forward slash * if it is missing. * - * @param {string=} path New path - * @return {string} path + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var path = $location.path(); + * // => "/some/path" + * ``` + * + * @param {(string|number)=} path New path + * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter */ path: locationGetterSetter('$$path', function(path) { - return path.charAt(0) == '/' ? path : '/' + path; + path = path !== null ? path.toString() : ''; + return path.charAt(0) === '/' ? path : '/' + path; }), /** @@ -9332,28 +15017,59 @@ LocationHashbangInHtml5Url.prototype = * @description * This method is getter / setter. * - * Return search part (as object) of current url when called without any parameter. + * Return search part (as object) of current URL when called without any parameter. * * Change search part when called with parameter and return `$location`. * + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo + * var searchObject = $location.search(); + * // => {foo: 'bar', baz: 'xoxo'} + * + * // set foo to 'yipee' + * $location.search('foo', 'yipee'); + * // $location.search() => {foo: 'yipee', baz: 'xoxo'} + * ``` + * * @param {string|Object.|Object.>} search New search params - string or - * hash object. Hash object may contain an array of values, which will be decoded as duplicates in - * the url. + * hash object. + * + * When called with a single argument the method acts as a setter, setting the `search` component + * of `$location` to the specified value. + * + * If the argument is a hash object containing an array of values, these values will be encoded + * as duplicate search parameters in the URL. + * + * @param {(string|Number|Array|boolean)=} paramValue If `search` is a string or number, then `paramValue` + * will override only a single search property. * - * @param {(string|Array)=} paramValue If `search` is a string, then `paramValue` will override only a - * single search parameter. If `paramValue` is an array, it will set the parameter as a - * comma-separated value. If `paramValue` is `null`, the parameter will be deleted. + * If `paramValue` is an array, it will override the property of the `search` component of + * `$location` specified via the first argument. * - * @return {string} search + * If `paramValue` is `null`, the property specified via the first argument will be deleted. + * + * If `paramValue` is `true`, the property specified via the first argument will be added with no + * value nor trailing equal sign. + * + * @return {Object} If called with no arguments returns the parsed `search` object. If called with + * one or more arguments returns `$location` object itself. */ search: function(search, paramValue) { switch (arguments.length) { case 0: return this.$$search; case 1: - if (isString(search)) { + if (isString(search) || isNumber(search)) { + search = search.toString(); this.$$search = parseKeyValue(search); } else if (isObject(search)) { + search = copy(search, {}); + // remove object undefined or null properties + forEach(search, function(value, key) { + if (value == null) delete search[key]; + }); + this.$$search = search; } else { throw $locationMinErr('isrcharg', @@ -9379,22 +15095,31 @@ LocationHashbangInHtml5Url.prototype = * @description * This method is getter / setter. * - * Return hash fragment when called without any parameter. + * Returns the hash fragment when called without any parameters. * - * Change hash fragment when called with parameter and return `$location`. + * Changes the hash fragment when called with a parameter and returns `$location`. + * + * + * ```js + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue + * var hash = $location.hash(); + * // => "hashValue" + * ``` * - * @param {string=} hash New hash fragment + * @param {(string|number)=} hash New hash fragment * @return {string} hash */ - hash: locationGetterSetter('$$hash', identity), + hash: locationGetterSetter('$$hash', function(hash) { + return hash !== null ? hash.toString() : ''; + }), /** * @ngdoc method * @name $location#replace * * @description - * If called, all changes to $location during current `$digest` will be replacing current history - * record, instead of adding new one. + * If called, all changes to $location during the current `$digest` will replace the current history + * record, instead of adding a new one. */ replace: function() { this.$$replace = true; @@ -9402,17 +15127,60 @@ LocationHashbangInHtml5Url.prototype = } }; +forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) { + Location.prototype = Object.create(locationPrototype); + + /** + * @ngdoc method + * @name $location#state + * + * @description + * This method is getter / setter. + * + * Return the history state object when called without any parameter. + * + * Change the history state object when called with one parameter and return `$location`. + * The state object is later passed to `pushState` or `replaceState`. + * + * NOTE: This method is supported only in HTML5 mode and only in browsers supporting + * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support + * older browsers (like IE9 or Android < 4.0), don't use this method. + * + * @param {object=} state State object for pushState or replaceState + * @return {object} state + */ + Location.prototype.state = function(state) { + if (!arguments.length) { + return this.$$state; + } + + if (Location !== LocationHtml5Url || !this.$$html5) { + throw $locationMinErr('nostate', 'History API state support is available only ' + + 'in HTML5 mode and only in browsers supporting HTML5 History API'); + } + // The user might modify `stateObject` after invoking `$location.state(stateObject)` + // but we're changing the $$state reference to $browser.state() during the $digest + // so the modification window is narrow. + this.$$state = isUndefined(state) ? null : state; + this.$$urlUpdatedByLocation = true; + + return this; + }; +}); + + function locationGetter(property) { - return function() { + return /** @this */ function() { return this[property]; }; } function locationGetterSetter(property, preprocess) { - return function(value) { - if (isUndefined(value)) + return /** @this */ function(value) { + if (isUndefined(value)) { return this[property]; + } this[property] = preprocess(value); this.$$compose(); @@ -9451,17 +15219,24 @@ function locationGetterSetter(property, preprocess) { /** * @ngdoc provider * @name $locationProvider + * @this + * * @description * Use the `$locationProvider` to configure how the application deep linking paths are stored. */ -function $LocationProvider(){ - var hashPrefix = '', - html5Mode = false; +function $LocationProvider() { + var hashPrefix = '!', + html5Mode = { + enabled: false, + requireBase: true, + rewriteLinks: true + }; /** - * @ngdoc property + * @ngdoc method * @name $locationProvider#hashPrefix * @description + * The default value for the prefix is `'!'`. * @param {string=} prefix Prefix for hash part (containing path and search) * @returns {*} current value if used as getter or itself (chaining) if used as setter */ @@ -9475,15 +15250,46 @@ function $LocationProvider(){ }; /** - * @ngdoc property + * @ngdoc method * @name $locationProvider#html5Mode * @description - * @param {boolean=} mode Use HTML5 strategy if available. - * @returns {*} current value if used as getter or itself (chaining) if used as setter + * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value. + * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported + * properties: + * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to + * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not + * support `pushState`. + * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies + * whether or not a tag is required to be present. If `enabled` and `requireBase` are + * true, and a base tag is not present, an error will be thrown when `$location` is injected. + * See the {@link guide/$location $location guide for more information} + * - **rewriteLinks** - `{boolean|string}` - (default: `true`) When html5Mode is enabled, + * enables/disables URL rewriting for relative links. If set to a string, URL rewriting will + * only happen on links with an attribute that matches the given string. For example, if set + * to `'internal-link'`, then the URL will only be rewritten for `` links. + * Note that [attribute name normalization](guide/directive#normalization) does not apply + * here, so `'internalLink'` will **not** match `'internal-link'`. + * + * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter */ this.html5Mode = function(mode) { - if (isDefined(mode)) { - html5Mode = mode; + if (isBoolean(mode)) { + html5Mode.enabled = mode; + return this; + } else if (isObject(mode)) { + + if (isBoolean(mode.enabled)) { + html5Mode.enabled = mode.enabled; + } + + if (isBoolean(mode.requireBase)) { + html5Mode.requireBase = mode.requireBase; + } + + if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) { + html5Mode.rewriteLinks = mode.rewriteLinks; + } + return this; } else { return html5Mode; @@ -9495,14 +15301,21 @@ function $LocationProvider(){ * @name $location#$locationChangeStart * @eventType broadcast on root scope * @description - * Broadcasted before a URL will change. This change can be prevented by calling + * Broadcasted before a URL will change. + * + * This change can be prevented by calling * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more * details about event object. Upon successful change - * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired. + * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired. + * + * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when + * the browser supports the HTML5 History API. * * @param {Object} angularEvent Synthetic event object. * @param {string} newUrl New URL * @param {string=} oldUrl URL that was before it was changed. + * @param {string=} newState New history state object + * @param {string=} oldState History state object that was before it was changed. */ /** @@ -9512,44 +15325,91 @@ function $LocationProvider(){ * @description * Broadcasted after a URL was changed. * + * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when + * the browser supports the HTML5 History API. + * * @param {Object} angularEvent Synthetic event object. * @param {string} newUrl New URL * @param {string=} oldUrl URL that was before it was changed. + * @param {string=} newState New history state object + * @param {string=} oldState History state object that was before it was changed. */ - this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', - function( $rootScope, $browser, $sniffer, $rootElement) { + this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window', + function($rootScope, $browser, $sniffer, $rootElement, $window) { var $location, LocationMode, baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to '' initialUrl = $browser.url(), appBase; - if (html5Mode) { + if (html5Mode.enabled) { + if (!baseHref && html5Mode.requireBase) { + throw $locationMinErr('nobase', + '$location in HTML5 mode requires a tag to be present!'); + } appBase = serverBase(initialUrl) + (baseHref || '/'); LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; } else { appBase = stripHash(initialUrl); LocationMode = LocationHashbangUrl; } - $location = new LocationMode(appBase, '#' + hashPrefix); - $location.$$parse($location.$$rewrite(initialUrl)); + var appBaseNoFile = stripFile(appBase); + + $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix); + $location.$$parseLinkUrl(initialUrl, initialUrl); + + $location.$$state = $browser.state(); + + var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i; + + // Determine if two URLs are equal despite potentially having different encoding/normalizing + // such as $location.absUrl() vs $browser.url() + // See https://github.com/angular/angular.js/issues/16592 + function urlsEqual(a, b) { + return a === b || urlResolve(a).href === urlResolve(b).href; + } + + function setBrowserUrlWithFallback(url, replace, state) { + var oldUrl = $location.url(); + var oldState = $location.$$state; + try { + $browser.url(url, replace, state); + + // Make sure $location.state() returns referentially identical (not just deeply equal) + // state object; this makes possible quick checking if the state changed in the digest + // loop. Checking deep equality would be too expensive. + $location.$$state = $browser.state(); + } catch (e) { + // Restore old values if pushState fails + $location.url(oldUrl); + $location.$$state = oldState; + + throw e; + } + } $rootElement.on('click', function(event) { + var rewriteLinks = html5Mode.rewriteLinks; // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser) // currently we open nice url link and redirect then - if (event.ctrlKey || event.metaKey || event.which == 2) return; + if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return; var elm = jqLite(event.target); // traverse the DOM up to find first A tag - while (lowercase(elm[0].nodeName) !== 'a') { + while (nodeName_(elm[0]) !== 'a') { // ignore rewriting if no A tag (reached root element, or no parent - removed from document) if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return; } + if (isString(rewriteLinks) && isUndefined(elm.attr(rewriteLinks))) return; + var absHref = elm.prop('href'); + // get the actual href attribute - see + // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx + var relHref = elm.attr('href') || elm.attr('xlink:href'); if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') { // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during @@ -9557,72 +15417,115 @@ function $LocationProvider(){ absHref = urlResolve(absHref.animVal).href; } - var rewrittenUrl = $location.$$rewrite(absHref); + // Ignore when url is started with javascript: or mailto: + if (IGNORE_URI_REGEXP.test(absHref)) return; - if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) { - event.preventDefault(); - if (rewrittenUrl != $browser.url()) { + if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) { + if ($location.$$parseLinkUrl(absHref, relHref)) { + // We do a preventDefault for all urls that are part of the AngularJS application, + // in html5mode and also without, so that we are able to abort navigation without + // getting double entries in the location history. + event.preventDefault(); // update location manually - $location.$$parse(rewrittenUrl); - $rootScope.$apply(); - // hack to work around FF6 bug 684208 when scenario runner clicks on links - window.angular['ff-684208-preventDefault'] = true; + if ($location.absUrl() !== $browser.url()) { + $rootScope.$apply(); + } } } }); // rewrite hashbang url <> html5 url - if ($location.absUrl() != initialUrl) { + if ($location.absUrl() !== initialUrl) { $browser.url($location.absUrl(), true); } + var initializing = true; + // update $location when $browser url changes - $browser.onUrlChange(function(newUrl) { - if ($location.absUrl() != newUrl) { - $rootScope.$evalAsync(function() { - var oldUrl = $location.absUrl(); + $browser.onUrlChange(function(newUrl, newState) { - $location.$$parse(newUrl); - if ($rootScope.$broadcast('$locationChangeStart', newUrl, - oldUrl).defaultPrevented) { - $location.$$parse(oldUrl); - $browser.url(oldUrl); - } else { - afterLocationChange(oldUrl); - } - }); - if (!$rootScope.$$phase) $rootScope.$digest(); + if (!startsWith(newUrl, appBaseNoFile)) { + // If we are navigating outside of the app then force a reload + $window.location.href = newUrl; + return; } + + $rootScope.$evalAsync(function() { + var oldUrl = $location.absUrl(); + var oldState = $location.$$state; + var defaultPrevented; + $location.$$parse(newUrl); + $location.$$state = newState; + + defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, + newState, oldState).defaultPrevented; + + // if the location was changed by a `$locationChangeStart` handler then stop + // processing this location change + if ($location.absUrl() !== newUrl) return; + + if (defaultPrevented) { + $location.$$parse(oldUrl); + $location.$$state = oldState; + setBrowserUrlWithFallback(oldUrl, false, oldState); + } else { + initializing = false; + afterLocationChange(oldUrl, oldState); + } + }); + if (!$rootScope.$$phase) $rootScope.$digest(); }); // update browser - var changeCounter = 0; $rootScope.$watch(function $locationWatch() { - var oldUrl = $browser.url(); - var currentReplace = $location.$$replace; - - if (!changeCounter || oldUrl != $location.absUrl()) { - changeCounter++; - $rootScope.$evalAsync(function() { - if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl). - defaultPrevented) { - $location.$$parse(oldUrl); - } else { - $browser.url($location.absUrl(), currentReplace); - afterLocationChange(oldUrl); - } - }); + if (initializing || $location.$$urlUpdatedByLocation) { + $location.$$urlUpdatedByLocation = false; + + var oldUrl = $browser.url(); + var newUrl = $location.absUrl(); + var oldState = $browser.state(); + var currentReplace = $location.$$replace; + var urlOrStateChanged = !urlsEqual(oldUrl, newUrl) || + ($location.$$html5 && $sniffer.history && oldState !== $location.$$state); + + if (initializing || urlOrStateChanged) { + initializing = false; + + $rootScope.$evalAsync(function() { + var newUrl = $location.absUrl(); + var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, + $location.$$state, oldState).defaultPrevented; + + // if the location was changed by a `$locationChangeStart` handler then stop + // processing this location change + if ($location.absUrl() !== newUrl) return; + + if (defaultPrevented) { + $location.$$parse(oldUrl); + $location.$$state = oldState; + } else { + if (urlOrStateChanged) { + setBrowserUrlWithFallback(newUrl, currentReplace, + oldState === $location.$$state ? null : $location.$$state); + } + afterLocationChange(oldUrl, oldState); + } + }); + } } + $location.$$replace = false; - return changeCounter; + // we don't need to return anything because $evalAsync will make the digest loop dirty when + // there is a change }); return $location; - function afterLocationChange(oldUrl) { - $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl); + function afterLocationChange(oldUrl, oldState) { + $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl, + $location.$$state, oldState); } }]; } @@ -9638,26 +15541,36 @@ function $LocationProvider(){ * * The main purpose of this service is to simplify debugging and troubleshooting. * + * To reveal the location of the calls to `$log` in the JavaScript console, + * you can "blackbox" the AngularJS source in your browser: + * + * [Mozilla description of blackboxing](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Black_box_a_source). + * [Chrome description of blackboxing](https://developer.chrome.com/devtools/docs/blackboxing). + * + * Note: Not all browsers support blackboxing. + * * The default is to log `debug` messages. You can use * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this. * * @example - + - function LogCtrl($scope, $log) { - $scope.$log = $log; - $scope.message = 'Hello World!'; - } + angular.module('logExample', []) + .controller('LogController', ['$scope', '$log', function($scope, $log) { + $scope.$log = $log; + $scope.message = 'Hello World!'; + }]); -
+

Reload this page with open console, enter text and hit the log button...

- Message: - + +
@@ -9666,15 +15579,17 @@ function $LocationProvider(){ /** * @ngdoc provider * @name $logProvider + * @this + * * @description * Use the `$logProvider` to configure how the application logs messages */ -function $LogProvider(){ +function $LogProvider() { var debug = true, self = this; /** - * @ngdoc property + * @ngdoc method * @name $logProvider#debugEnabled * @description * @param {boolean=} flag enable or disable debug level messages @@ -9683,13 +15598,22 @@ function $LogProvider(){ this.debugEnabled = function(flag) { if (isDefined(flag)) { debug = flag; - return this; + return this; } else { return debug; } }; - this.$get = ['$window', function($window){ + this.$get = ['$window', function($window) { + // Support: IE 9-11, Edge 12-14+ + // IE/Edge display errors in such a way that it requires the user to click in 4 places + // to see the stack trace. There is no way to feature-detect it so there's a chance + // of the user agent sniffing to go wrong but since it's only about logging, this shouldn't + // break apps. Other browsers display errors in a sensible way and some of them map stack + // traces along source maps if available so it makes sense to let browsers display it + // as they want. + var formatStackTrace = msie || /\bEdge\//.test($window.navigator && $window.navigator.userAgent); + return { /** * @ngdoc method @@ -9734,7 +15658,7 @@ function $LogProvider(){ * @description * Write a debug message */ - debug: (function () { + debug: (function() { var fn = consoleLog('debug'); return function() { @@ -9742,12 +15666,12 @@ function $LogProvider(){ fn.apply(self, arguments); } }; - }()) + })() }; function formatError(arg) { - if (arg instanceof Error) { - if (arg.stack) { + if (isError(arg)) { + if (arg.stack && formatStackTrace) { arg = (arg.message && arg.stack.indexOf(arg.message) === -1) ? 'Error: ' + arg.message + '\n' + arg.stack : arg.stack; @@ -9760,139 +15684,74 @@ function $LogProvider(){ function consoleLog(type) { var console = $window.console || {}, - logFn = console[type] || console.log || noop, - hasApply = false; - - // Note: reading logFn.apply throws an error in IE11 in IE8 document mode. - // The reason behind this is that console.log has type "object" in IE8... - try { - hasApply = !!logFn.apply; - } catch (e) {} + logFn = console[type] || console.log || noop; - if (hasApply) { - return function() { - var args = []; - forEach(arguments, function(arg) { - args.push(formatError(arg)); - }); - return logFn.apply(console, args); - }; - } - - // we are IE which either doesn't have window.console => this is noop and we do nothing, - // or we are IE where console.log doesn't have apply so we log at least first 2 args - return function(arg1, arg2) { - logFn(arg1, arg2 == null ? '' : arg2); + return function() { + var args = []; + forEach(arguments, function(arg) { + args.push(formatError(arg)); + }); + // Support: IE 9 only + // console methods don't inherit from Function.prototype in IE 9 so we can't + // call `logFn.apply(console, args)` directly. + return Function.prototype.apply.call(logFn, console, args); }; } }]; } +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Any commits to this file should be reviewed with security in mind. * + * Changes to this file can potentially create security vulnerabilities. * + * An approval from 2 Core members with history of modifying * + * this file is required. * + * * + * Does the change somehow allow for arbitrary javascript to be executed? * + * Or allows for someone to change the prototype of built-in objects? * + * Or gives undesired access to variables likes document or window? * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + var $parseMinErr = minErr('$parse'); -var promiseWarningCache = {}; -var promiseWarning; -// Sandboxing Angular Expressions +var objectValueOf = {}.constructor.prototype.valueOf; + +// Sandboxing AngularJS Expressions // ------------------------------ -// Angular expressions are generally considered safe because these expressions only have direct -// access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by -// obtaining a reference to native JS functions such as the Function constructor. +// AngularJS expressions are no longer sandboxed. So it is now even easier to access arbitrary JS code by +// various means such as obtaining a reference to native JS functions like the Function constructor. // -// As an example, consider the following Angular expression: +// As an example, consider the following AngularJS expression: // -// {}.toString.constructor(alert("evil JS code")) +// {}.toString.constructor('alert("evil JS code")') // -// We want to prevent this type of access. For the sake of performance, during the lexing phase we -// disallow any "dotted" access to any member named "constructor". +// It is important to realize that if you create an expression from a string that contains user provided +// content then it is possible that your application contains a security vulnerability to an XSS style attack. // -// For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor -// while evaluating the expression, which is a stronger but more expensive test. Since reflective -// calls are expensive anyway, this is not such a big deal compared to static dereferencing. -// -// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits -// against the expression language, but not to prevent exploits that were enabled by exposing -// sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good -// practice and therefore we are not even trying to protect against interaction with an object -// explicitly exposed in this way. -// -// A developer could foil the name check by aliasing the Function constructor under a different -// name on the scope. -// -// In general, it is not possible to access a Window object from an angular expression unless a -// window or some DOM object that has a reference to window is published onto a Scope. - -function ensureSafeMemberName(name, fullExpression) { - if (name === "constructor") { - throw $parseMinErr('isecfld', - 'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } - return name; +// See https://docs.angularjs.org/guide/security + + +function getStringValue(name) { + // Property names must be strings. This means that non-string objects cannot be used + // as keys in an object. Any non-string object, including a number, is typecasted + // into a string via the toString method. + // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names + // + // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it + // to a string. It's not always possible. If `name` is an object and its `toString` method is + // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown: + // + // TypeError: Cannot convert object to primitive value + // + // For performance reasons, we don't catch this error here and allow it to propagate up the call + // stack. Note that you'll get the same error in JavaScript if you try to access a property using + // such a 'broken' object as a key. + return name + ''; } -function ensureSafeObject(obj, fullExpression) { - // nifty check if obj is Function that is fast and works across iframes and other contexts - if (obj) { - if (obj.constructor === obj) { - throw $parseMinErr('isecfn', - 'Referencing Function in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } else if (// isWindow(obj) - obj.document && obj.location && obj.alert && obj.setInterval) { - throw $parseMinErr('isecwindow', - 'Referencing the Window in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } else if (// isElement(obj) - obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) { - throw $parseMinErr('isecdom', - 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } - } - return obj; -} -var OPERATORS = { - /* jshint bitwise : false */ - 'null':function(){return null;}, - 'true':function(){return true;}, - 'false':function(){return false;}, - undefined:noop, - '+':function(self, locals, a,b){ - a=a(self, locals); b=b(self, locals); - if (isDefined(a)) { - if (isDefined(b)) { - return a + b; - } - return a; - } - return isDefined(b)?b:undefined;}, - '-':function(self, locals, a,b){ - a=a(self, locals); b=b(self, locals); - return (isDefined(a)?a:0)-(isDefined(b)?b:0); - }, - '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);}, - '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);}, - '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);}, - '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);}, - '=':noop, - '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);}, - '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);}, - '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);}, - '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);}, - '<':function(self, locals, a,b){return a(self, locals)':function(self, locals, a,b){return a(self, locals)>b(self, locals);}, - '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);}, - '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);}, - '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);}, - '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);}, - '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);}, -// '|':function(self, locals, a,b){return a|b;}, - '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));}, - '!':function(self, locals, a){return !a(self, locals);} -}; -/* jshint bitwise: true */ -var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'}; +var OPERATORS = createMap(); +forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; }); +var ESCAPE = {'n':'\n', 'f':'\f', 'r':'\r', 't':'\t', 'v':'\v', '\'':'\'', '"':'"'}; ///////////////////////////////////////// @@ -9901,85 +15760,51 @@ var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"' /** * @constructor */ -var Lexer = function (options) { +var Lexer = function Lexer(options) { this.options = options; }; Lexer.prototype = { constructor: Lexer, - lex: function (text) { + lex: function(text) { this.text = text; - this.index = 0; - this.ch = undefined; - this.lastCh = ':'; // can start regexp - this.tokens = []; - var token; - var json = []; - while (this.index < this.text.length) { - this.ch = this.text.charAt(this.index); - if (this.is('"\'')) { - this.readString(this.ch); - } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) { + var ch = this.text.charAt(this.index); + if (ch === '"' || ch === '\'') { + this.readString(ch); + } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) { this.readNumber(); - } else if (this.isIdent(this.ch)) { + } else if (this.isIdentifierStart(this.peekMultichar())) { this.readIdent(); - // identifiers can only be if the preceding char was a { or , - if (this.was('{,') && json[0] === '{' && - (token = this.tokens[this.tokens.length - 1])) { - token.json = token.text.indexOf('.') === -1; - } - } else if (this.is('(){}[].,;:?')) { - this.tokens.push({ - index: this.index, - text: this.ch, - json: (this.was(':[,') && this.is('{[')) || this.is('}]:,') - }); - if (this.is('{[')) json.unshift(this.ch); - if (this.is('}]')) json.shift(); + } else if (this.is(ch, '(){}[].,;:?')) { + this.tokens.push({index: this.index, text: ch}); this.index++; - } else if (this.isWhitespace(this.ch)) { + } else if (this.isWhitespace(ch)) { this.index++; - continue; } else { - var ch2 = this.ch + this.peek(); + var ch2 = ch + this.peek(); var ch3 = ch2 + this.peek(2); - var fn = OPERATORS[this.ch]; - var fn2 = OPERATORS[ch2]; - var fn3 = OPERATORS[ch3]; - if (fn3) { - this.tokens.push({index: this.index, text: ch3, fn: fn3}); - this.index += 3; - } else if (fn2) { - this.tokens.push({index: this.index, text: ch2, fn: fn2}); - this.index += 2; - } else if (fn) { - this.tokens.push({ - index: this.index, - text: this.ch, - fn: fn, - json: (this.was('[,:') && this.is('+-')) - }); - this.index += 1; + var op1 = OPERATORS[ch]; + var op2 = OPERATORS[ch2]; + var op3 = OPERATORS[ch3]; + if (op1 || op2 || op3) { + var token = op3 ? ch3 : (op2 ? ch2 : ch); + this.tokens.push({index: this.index, text: token, operator: true}); + this.index += token.length; } else { this.throwError('Unexpected next character ', this.index, this.index + 1); } } - this.lastCh = this.ch; } return this.tokens; }, - is: function(chars) { - return chars.indexOf(this.ch) !== -1; - }, - - was: function(chars) { - return chars.indexOf(this.lastCh) !== -1; + is: function(ch, chars) { + return chars.indexOf(ch) !== -1; }, peek: function(i) { @@ -9988,7 +15813,7 @@ Lexer.prototype = { }, isNumber: function(ch) { - return ('0' <= ch && ch <= '9'); + return ('0' <= ch && ch <= '9') && typeof ch === 'string'; }, isWhitespace: function(ch) { @@ -9997,12 +15822,48 @@ Lexer.prototype = { ch === '\n' || ch === '\v' || ch === '\u00A0'); }, - isIdent: function(ch) { + isIdentifierStart: function(ch) { + return this.options.isIdentifierStart ? + this.options.isIdentifierStart(ch, this.codePointAt(ch)) : + this.isValidIdentifierStart(ch); + }, + + isValidIdentifierStart: function(ch) { return ('a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || '_' === ch || ch === '$'); }, + isIdentifierContinue: function(ch) { + return this.options.isIdentifierContinue ? + this.options.isIdentifierContinue(ch, this.codePointAt(ch)) : + this.isValidIdentifierContinue(ch); + }, + + isValidIdentifierContinue: function(ch, cp) { + return this.isValidIdentifierStart(ch, cp) || this.isNumber(ch); + }, + + codePointAt: function(ch) { + if (ch.length === 1) return ch.charCodeAt(0); + // eslint-disable-next-line no-bitwise + return (ch.charCodeAt(0) << 10) + ch.charCodeAt(1) - 0x35FDC00; + }, + + peekMultichar: function() { + var ch = this.text.charAt(this.index); + var peek = this.peek(); + if (!peek) { + return ch; + } + var cp1 = ch.charCodeAt(0); + var cp2 = peek.charCodeAt(0); + if (cp1 >= 0xD800 && cp1 <= 0xDBFF && cp2 >= 0xDC00 && cp2 <= 0xDFFF) { + return ch + peek; + } + return ch; + }, + isExpOperator: function(ch) { return (ch === '-' || ch === '+' || this.isNumber(ch)); }, @@ -10021,19 +15882,19 @@ Lexer.prototype = { var start = this.index; while (this.index < this.text.length) { var ch = lowercase(this.text.charAt(this.index)); - if (ch == '.' || this.isNumber(ch)) { + if (ch === '.' || this.isNumber(ch)) { number += ch; } else { var peekCh = this.peek(); - if (ch == 'e' && this.isExpOperator(peekCh)) { + if (ch === 'e' && this.isExpOperator(peekCh)) { number += ch; } else if (this.isExpOperator(ch) && peekCh && this.isNumber(peekCh) && - number.charAt(number.length - 1) == 'e') { + number.charAt(number.length - 1) === 'e') { number += ch; } else if (this.isExpOperator(ch) && (!peekCh || !this.isNumber(peekCh)) && - number.charAt(number.length - 1) == 'e') { + number.charAt(number.length - 1) === 'e') { this.throwError('Invalid exponent'); } else { break; @@ -10041,88 +15902,29 @@ Lexer.prototype = { } this.index++; } - number = 1 * number; this.tokens.push({ index: start, text: number, - json: true, - fn: function() { return number; } + constant: true, + value: Number(number) }); }, readIdent: function() { - var parser = this; - - var ident = ''; var start = this.index; - - var lastDot, peekIndex, methodName, ch; - + this.index += this.peekMultichar().length; while (this.index < this.text.length) { - ch = this.text.charAt(this.index); - if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) { - if (ch === '.') lastDot = this.index; - ident += ch; - } else { + var ch = this.peekMultichar(); + if (!this.isIdentifierContinue(ch)) { break; } - this.index++; - } - - //check if this is not a method invocation and if it is back out to last dot - if (lastDot) { - peekIndex = this.index; - while (peekIndex < this.text.length) { - ch = this.text.charAt(peekIndex); - if (ch === '(') { - methodName = ident.substr(lastDot - start + 1); - ident = ident.substr(0, lastDot - start); - this.index = peekIndex; - break; - } - if (this.isWhitespace(ch)) { - peekIndex++; - } else { - break; - } - } + this.index += ch.length; } - - - var token = { + this.tokens.push({ index: start, - text: ident - }; - - // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn - if (OPERATORS.hasOwnProperty(ident)) { - token.fn = OPERATORS[ident]; - token.json = OPERATORS[ident]; - } else { - var getter = getterFn(ident, this.options, this.text); - token.fn = extend(function(self, locals) { - return (getter(self, locals)); - }, { - assign: function(self, value) { - return setter(self, ident, value, parser.text, parser.options); - } - }); - } - - this.tokens.push(token); - - if (methodName) { - this.tokens.push({ - index:lastDot, - text: '.', - json: false - }); - this.tokens.push({ - index: lastDot + 1, - text: methodName, - json: false - }); - } + text: this.text.slice(start, this.index), + identifier: true + }); }, readString: function(quote) { @@ -10137,17 +15939,14 @@ Lexer.prototype = { if (escape) { if (ch === 'u') { var hex = this.text.substring(this.index + 1, this.index + 5); - if (!hex.match(/[\da-f]{4}/i)) + if (!hex.match(/[\da-f]{4}/i)) { this.throwError('Invalid unicode escape [\\u' + hex + ']'); + } this.index += 4; string += String.fromCharCode(parseInt(hex, 16)); } else { var rep = ESCAPE[ch]; - if (rep) { - string += rep; - } else { - string += ch; - } + string = string + (rep || ch); } escape = false; } else if (ch === '\\') { @@ -10157,9 +15956,8 @@ Lexer.prototype = { this.tokens.push({ index: start, text: rawString, - string: string, - json: true, - fn: function() { return string; } + constant: true, + value: string }); return; } else { @@ -10171,907 +15969,1809 @@ Lexer.prototype = { } }; - -/** - * @constructor - */ -var Parser = function (lexer, $filter, options) { +var AST = function AST(lexer, options) { this.lexer = lexer; - this.$filter = $filter; this.options = options; }; -Parser.ZERO = extend(function () { - return 0; -}, { - constant: true -}); - -Parser.prototype = { - constructor: Parser, - - parse: function (text, json) { +AST.Program = 'Program'; +AST.ExpressionStatement = 'ExpressionStatement'; +AST.AssignmentExpression = 'AssignmentExpression'; +AST.ConditionalExpression = 'ConditionalExpression'; +AST.LogicalExpression = 'LogicalExpression'; +AST.BinaryExpression = 'BinaryExpression'; +AST.UnaryExpression = 'UnaryExpression'; +AST.CallExpression = 'CallExpression'; +AST.MemberExpression = 'MemberExpression'; +AST.Identifier = 'Identifier'; +AST.Literal = 'Literal'; +AST.ArrayExpression = 'ArrayExpression'; +AST.Property = 'Property'; +AST.ObjectExpression = 'ObjectExpression'; +AST.ThisExpression = 'ThisExpression'; +AST.LocalsExpression = 'LocalsExpression'; + +// Internal use only +AST.NGValueParameter = 'NGValueParameter'; + +AST.prototype = { + ast: function(text) { this.text = text; - - //TODO(i): strip all the obsolte json stuff from this file - this.json = json; - this.tokens = this.lexer.lex(text); - if (json) { - // The extra level of aliasing is here, just in case the lexer misses something, so that - // we prevent any accidental execution in JSON. - this.assignment = this.logicalOR; - - this.functionCall = - this.fieldAccess = - this.objectIndex = - this.filterChain = function() { - this.throwError('is not valid json', {text: text, index: 0}); - }; - } - - var value = json ? this.primary() : this.statements(); + var value = this.program(); if (this.tokens.length !== 0) { this.throwError('is an unexpected token', this.tokens[0]); } - value.literal = !!value.literal; - value.constant = !!value.constant; - return value; }, - primary: function () { - var primary; - if (this.expect('(')) { - primary = this.filterChain(); - this.consume(')'); - } else if (this.expect('[')) { - primary = this.arrayDeclaration(); - } else if (this.expect('{')) { - primary = this.object(); - } else { - var token = this.expect(); - primary = token.fn; - if (!primary) { - this.throwError('not a primary expression', token); - } - if (token.json) { - primary.constant = true; - primary.literal = true; + program: function() { + var body = []; + while (true) { + if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) + body.push(this.expressionStatement()); + if (!this.expect(';')) { + return { type: AST.Program, body: body}; } } + }, - var next, context; - while ((next = this.expect('(', '[', '.'))) { - if (next.text === '(') { - primary = this.functionCall(primary, context); - context = null; - } else if (next.text === '[') { - context = primary; - primary = this.objectIndex(primary); - } else if (next.text === '.') { - context = primary; - primary = this.fieldAccess(primary); - } else { - this.throwError('IMPOSSIBLE'); - } - } - return primary; + expressionStatement: function() { + return { type: AST.ExpressionStatement, expression: this.filterChain() }; }, - throwError: function(msg, token) { - throw $parseMinErr('syntax', - 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].', - token.text, msg, (token.index + 1), this.text, this.text.substring(token.index)); + filterChain: function() { + var left = this.expression(); + while (this.expect('|')) { + left = this.filter(left); + } + return left; }, - peekToken: function() { - if (this.tokens.length === 0) - throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); - return this.tokens[0]; + expression: function() { + return this.assignment(); }, - peek: function(e1, e2, e3, e4) { - if (this.tokens.length > 0) { - var token = this.tokens[0]; - var t = token.text; - if (t === e1 || t === e2 || t === e3 || t === e4 || - (!e1 && !e2 && !e3 && !e4)) { - return token; + assignment: function() { + var result = this.ternary(); + if (this.expect('=')) { + if (!isAssignable(result)) { + throw $parseMinErr('lval', 'Trying to assign a value to a non l-value'); } + + result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='}; } - return false; + return result; }, - expect: function(e1, e2, e3, e4){ - var token = this.peek(e1, e2, e3, e4); - if (token) { - if (this.json && !token.json) { - this.throwError('is not valid json', token); + ternary: function() { + var test = this.logicalOR(); + var alternate; + var consequent; + if (this.expect('?')) { + alternate = this.expression(); + if (this.consume(':')) { + consequent = this.expression(); + return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent}; } - this.tokens.shift(); - return token; } - return false; + return test; }, - consume: function(e1){ - if (!this.expect(e1)) { - this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); + logicalOR: function() { + var left = this.logicalAND(); + while (this.expect('||')) { + left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() }; } + return left; }, - unaryFn: function(fn, right) { - return extend(function(self, locals) { - return fn(self, locals, right); - }, { - constant:right.constant - }); + logicalAND: function() { + var left = this.equality(); + while (this.expect('&&')) { + left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()}; + } + return left; }, - ternaryFn: function(left, middle, right){ - return extend(function(self, locals){ - return left(self, locals) ? middle(self, locals) : right(self, locals); - }, { - constant: left.constant && middle.constant && right.constant - }); + equality: function() { + var left = this.relational(); + var token; + while ((token = this.expect('==','!=','===','!=='))) { + left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() }; + } + return left; }, - binaryFn: function(left, fn, right) { - return extend(function(self, locals) { - return fn(self, locals, left, right); - }, { - constant:left.constant && right.constant - }); + relational: function() { + var left = this.additive(); + var token; + while ((token = this.expect('<', '>', '<=', '>='))) { + left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() }; + } + return left; }, - statements: function() { - var statements = []; - while (true) { - if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) - statements.push(this.filterChain()); - if (!this.expect(';')) { - // optimize for the common case where there is only one statement. - // TODO(size): maybe we should not support multiple statements? - return (statements.length === 1) - ? statements[0] - : function(self, locals) { - var value; - for (var i = 0; i < statements.length; i++) { - var statement = statements[i]; - if (statement) { - value = statement(self, locals); - } - } - return value; - }; - } + additive: function() { + var left = this.multiplicative(); + var token; + while ((token = this.expect('+','-'))) { + left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() }; } + return left; }, - filterChain: function() { - var left = this.expression(); + multiplicative: function() { + var left = this.unary(); var token; - while (true) { - if ((token = this.expect('|'))) { - left = this.binaryFn(left, token.fn, this.filter()); - } else { - return left; - } + while ((token = this.expect('*','/','%'))) { + left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() }; } + return left; }, - filter: function() { - var token = this.expect(); - var fn = this.$filter(token.text); - var argsFn = []; - while (true) { - if ((token = this.expect(':'))) { - argsFn.push(this.expression()); - } else { - var fnInvoke = function(self, locals, input) { - var args = [input]; - for (var i = 0; i < argsFn.length; i++) { - args.push(argsFn[i](self, locals)); - } - return fn.apply(self, args); - }; - return function() { - return fnInvoke; - }; - } - } - }, - - expression: function() { - return this.assignment(); - }, - - assignment: function() { - var left = this.ternary(); - var right; + unary: function() { var token; - if ((token = this.expect('='))) { - if (!left.assign) { - this.throwError('implies assignment but [' + - this.text.substring(0, token.index) + '] can not be assigned to', token); - } - right = this.ternary(); - return function(scope, locals) { - return left.assign(scope, right(scope, locals), locals); - }; + if ((token = this.expect('+', '-', '!'))) { + return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() }; + } else { + return this.primary(); } - return left; }, - ternary: function() { - var left = this.logicalOR(); - var middle; - var token; - if ((token = this.expect('?'))) { - middle = this.ternary(); - if ((token = this.expect(':'))) { - return this.ternaryFn(left, middle, this.ternary()); - } else { - this.throwError('expected :', token); - } + primary: function() { + var primary; + if (this.expect('(')) { + primary = this.filterChain(); + this.consume(')'); + } else if (this.expect('[')) { + primary = this.arrayDeclaration(); + } else if (this.expect('{')) { + primary = this.object(); + } else if (this.selfReferential.hasOwnProperty(this.peek().text)) { + primary = copy(this.selfReferential[this.consume().text]); + } else if (this.options.literals.hasOwnProperty(this.peek().text)) { + primary = { type: AST.Literal, value: this.options.literals[this.consume().text]}; + } else if (this.peek().identifier) { + primary = this.identifier(); + } else if (this.peek().constant) { + primary = this.constant(); } else { - return left; + this.throwError('not a primary expression', this.peek()); } - }, - logicalOR: function() { - var left = this.logicalAND(); - var token; - while (true) { - if ((token = this.expect('||'))) { - left = this.binaryFn(left, token.fn, this.logicalAND()); + var next; + while ((next = this.expect('(', '[', '.'))) { + if (next.text === '(') { + primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() }; + this.consume(')'); + } else if (next.text === '[') { + primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true }; + this.consume(']'); + } else if (next.text === '.') { + primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false }; } else { - return left; + this.throwError('IMPOSSIBLE'); } } + return primary; }, - logicalAND: function() { - var left = this.equality(); - var token; - if ((token = this.expect('&&'))) { - left = this.binaryFn(left, token.fn, this.logicalAND()); - } - return left; - }, - - equality: function() { - var left = this.relational(); - var token; - if ((token = this.expect('==','!=','===','!=='))) { - left = this.binaryFn(left, token.fn, this.equality()); - } - return left; - }, - - relational: function() { - var left = this.additive(); - var token; - if ((token = this.expect('<', '>', '<=', '>='))) { - left = this.binaryFn(left, token.fn, this.relational()); - } - return left; - }, - - additive: function() { - var left = this.multiplicative(); - var token; - while ((token = this.expect('+','-'))) { - left = this.binaryFn(left, token.fn, this.multiplicative()); - } - return left; - }, - - multiplicative: function() { - var left = this.unary(); - var token; - while ((token = this.expect('*','/','%'))) { - left = this.binaryFn(left, token.fn, this.unary()); - } - return left; - }, + filter: function(baseExpression) { + var args = [baseExpression]; + var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true}; - unary: function() { - var token; - if (this.expect('+')) { - return this.primary(); - } else if ((token = this.expect('-'))) { - return this.binaryFn(Parser.ZERO, token.fn, this.unary()); - } else if ((token = this.expect('!'))) { - return this.unaryFn(token.fn, this.unary()); - } else { - return this.primary(); + while (this.expect(':')) { + args.push(this.expression()); } - }, - - fieldAccess: function(object) { - var parser = this; - var field = this.expect().text; - var getter = getterFn(field, this.options, this.text); - - return extend(function(scope, locals, self) { - return getter(self || object(scope, locals)); - }, { - assign: function(scope, value, locals) { - return setter(object(scope, locals), field, value, parser.text, parser.options); - } - }); - }, - - objectIndex: function(obj) { - var parser = this; - - var indexFn = this.expression(); - this.consume(']'); - return extend(function(self, locals) { - var o = obj(self, locals), - i = indexFn(self, locals), - v, p; - - if (!o) return undefined; - v = ensureSafeObject(o[i], parser.text); - if (v && v.then && parser.options.unwrapPromises) { - p = v; - if (!('$$v' in v)) { - p.$$v = undefined; - p.then(function(val) { p.$$v = val; }); - } - v = v.$$v; - } - return v; - }, { - assign: function(self, value, locals) { - var key = indexFn(self, locals); - // prevent overwriting of Function.constructor which would break ensureSafeObject check - var safe = ensureSafeObject(obj(self, locals), parser.text); - return safe[key] = value; - } - }); + return result; }, - functionCall: function(fn, contextGetter) { - var argsFn = []; + parseArguments: function() { + var args = []; if (this.peekToken().text !== ')') { do { - argsFn.push(this.expression()); + args.push(this.filterChain()); } while (this.expect(',')); } - this.consume(')'); - - var parser = this; - - return function(scope, locals) { - var args = []; - var context = contextGetter ? contextGetter(scope, locals) : scope; - - for (var i = 0; i < argsFn.length; i++) { - args.push(argsFn[i](scope, locals)); - } - var fnPtr = fn(scope, locals, context) || noop; - - ensureSafeObject(context, parser.text); - ensureSafeObject(fnPtr, parser.text); + return args; + }, - // IE stupidity! (IE doesn't have apply for some native functions) - var v = fnPtr.apply - ? fnPtr.apply(context, args) - : fnPtr(args[0], args[1], args[2], args[3], args[4]); + identifier: function() { + var token = this.consume(); + if (!token.identifier) { + this.throwError('is not a valid identifier', token); + } + return { type: AST.Identifier, name: token.text }; + }, - return ensureSafeObject(v, parser.text); - }; + constant: function() { + // TODO check that it is a constant + return { type: AST.Literal, value: this.consume().value }; }, - // This is used with json array declaration - arrayDeclaration: function () { - var elementFns = []; - var allConstant = true; + arrayDeclaration: function() { + var elements = []; if (this.peekToken().text !== ']') { do { if (this.peek(']')) { // Support trailing commas per ES5.1. break; } - var elementFn = this.expression(); - elementFns.push(elementFn); - if (!elementFn.constant) { - allConstant = false; - } + elements.push(this.expression()); } while (this.expect(',')); } this.consume(']'); - return extend(function(self, locals) { - var array = []; - for (var i = 0; i < elementFns.length; i++) { - array.push(elementFns[i](self, locals)); - } - return array; - }, { - literal: true, - constant: allConstant - }); + return { type: AST.ArrayExpression, elements: elements }; }, - object: function () { - var keyValues = []; - var allConstant = true; + object: function() { + var properties = [], property; if (this.peekToken().text !== '}') { do { if (this.peek('}')) { // Support trailing commas per ES5.1. break; } - var token = this.expect(), - key = token.string || token.text; - this.consume(':'); - var value = this.expression(); - keyValues.push({key: key, value: value}); - if (!value.constant) { - allConstant = false; + property = {type: AST.Property, kind: 'init'}; + if (this.peek().constant) { + property.key = this.constant(); + property.computed = false; + this.consume(':'); + property.value = this.expression(); + } else if (this.peek().identifier) { + property.key = this.identifier(); + property.computed = false; + if (this.peek(':')) { + this.consume(':'); + property.value = this.expression(); + } else { + property.value = property.key; + } + } else if (this.peek('[')) { + this.consume('['); + property.key = this.expression(); + this.consume(']'); + property.computed = true; + this.consume(':'); + property.value = this.expression(); + } else { + this.throwError('invalid key', this.peek()); } + properties.push(property); } while (this.expect(',')); } this.consume('}'); - return extend(function(self, locals) { - var object = {}; - for (var i = 0; i < keyValues.length; i++) { - var keyValue = keyValues[i]; - object[keyValue.key] = keyValue.value(self, locals); - } - return object; - }, { - literal: true, - constant: allConstant - }); - } -}; + return {type: AST.ObjectExpression, properties: properties }; + }, + throwError: function(msg, token) { + throw $parseMinErr('syntax', + 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].', + token.text, msg, (token.index + 1), this.text, this.text.substring(token.index)); + }, -////////////////////////////////////////////////// -// Parser helper functions -////////////////////////////////////////////////// + consume: function(e1) { + if (this.tokens.length === 0) { + throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); + } -function setter(obj, path, setValue, fullExp, options) { - //needed? - options = options || {}; + var token = this.expect(e1); + if (!token) { + this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); + } + return token; + }, - var element = path.split('.'), key; - for (var i = 0; element.length > 1; i++) { - key = ensureSafeMemberName(element.shift(), fullExp); - var propertyObj = obj[key]; - if (!propertyObj) { - propertyObj = {}; - obj[key] = propertyObj; + peekToken: function() { + if (this.tokens.length === 0) { + throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); } - obj = propertyObj; - if (obj.then && options.unwrapPromises) { - promiseWarning(fullExp); - if (!("$$v" in obj)) { - (function(promise) { - promise.then(function(val) { promise.$$v = val; }); } - )(obj); - } - if (obj.$$v === undefined) { - obj.$$v = {}; + return this.tokens[0]; + }, + + peek: function(e1, e2, e3, e4) { + return this.peekAhead(0, e1, e2, e3, e4); + }, + + peekAhead: function(i, e1, e2, e3, e4) { + if (this.tokens.length > i) { + var token = this.tokens[i]; + var t = token.text; + if (t === e1 || t === e2 || t === e3 || t === e4 || + (!e1 && !e2 && !e3 && !e4)) { + return token; } - obj = obj.$$v; } + return false; + }, + + expect: function(e1, e2, e3, e4) { + var token = this.peek(e1, e2, e3, e4); + if (token) { + this.tokens.shift(); + return token; + } + return false; + }, + + selfReferential: { + 'this': {type: AST.ThisExpression }, + '$locals': {type: AST.LocalsExpression } } - key = ensureSafeMemberName(element.shift(), fullExp); - obj[key] = setValue; - return setValue; +}; + +function ifDefined(v, d) { + return typeof v !== 'undefined' ? v : d; } -var getterFnCache = {}; +function plusFn(l, r) { + if (typeof l === 'undefined') return r; + if (typeof r === 'undefined') return l; + return l + r; +} -/** - * Implementation of the "Black Hole" variant from: - * - http://jsperf.com/angularjs-parse-getter/4 - * - http://jsperf.com/path-evaluation-simplified/7 - */ -function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) { - ensureSafeMemberName(key0, fullExp); - ensureSafeMemberName(key1, fullExp); - ensureSafeMemberName(key2, fullExp); - ensureSafeMemberName(key3, fullExp); - ensureSafeMemberName(key4, fullExp); - - return !options.unwrapPromises - ? function cspSafeGetter(scope, locals) { - var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope; - - if (pathVal == null) return pathVal; - pathVal = pathVal[key0]; - - if (!key1) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key1]; - - if (!key2) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key2]; - - if (!key3) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key3]; - - if (!key4) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key4]; - - return pathVal; - } - : function cspSafePromiseEnabledGetter(scope, locals) { - var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope, - promise; - - if (pathVal == null) return pathVal; - - pathVal = pathVal[key0]; - if (pathVal && pathVal.then) { - promiseWarning(fullExp); - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } +function isStateless($filter, filterName) { + var fn = $filter(filterName); + return !fn.$stateful; +} - if (!key1) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key1]; - if (pathVal && pathVal.then) { - promiseWarning(fullExp); - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } +var PURITY_ABSOLUTE = 1; +var PURITY_RELATIVE = 2; - if (!key2) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key2]; - if (pathVal && pathVal.then) { - promiseWarning(fullExp); - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } +// Detect nodes which could depend on non-shallow state of objects +function isPure(node, parentIsPure) { + switch (node.type) { + // Computed members might invoke a stateful toString() + case AST.MemberExpression: + if (node.computed) { + return false; + } + break; - if (!key3) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key3]; - if (pathVal && pathVal.then) { - promiseWarning(fullExp); - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } + // Unary always convert to primative + case AST.UnaryExpression: + return PURITY_ABSOLUTE; - if (!key4) return pathVal; - if (pathVal == null) return undefined; - pathVal = pathVal[key4]; - if (pathVal && pathVal.then) { - promiseWarning(fullExp); - if (!("$$v" in pathVal)) { - promise = pathVal; - promise.$$v = undefined; - promise.then(function(val) { promise.$$v = val; }); - } - pathVal = pathVal.$$v; - } - return pathVal; - }; + // The binary + operator can invoke a stateful toString(). + case AST.BinaryExpression: + return node.operator !== '+' ? PURITY_ABSOLUTE : false; + + // Functions / filters probably read state from within objects + case AST.CallExpression: + return false; + } + + return (undefined === parentIsPure) ? PURITY_RELATIVE : parentIsPure; } -function simpleGetterFn1(key0, fullExp) { - ensureSafeMemberName(key0, fullExp); +function findConstantAndWatchExpressions(ast, $filter, parentIsPure) { + var allConstants; + var argsToWatch; + var isStatelessFilter; - return function simpleGetterFn1(scope, locals) { - if (scope == null) return undefined; - return ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0]; - }; + var astIsPure = ast.isPure = isPure(ast, parentIsPure); + + switch (ast.type) { + case AST.Program: + allConstants = true; + forEach(ast.body, function(expr) { + findConstantAndWatchExpressions(expr.expression, $filter, astIsPure); + allConstants = allConstants && expr.expression.constant; + }); + ast.constant = allConstants; + break; + case AST.Literal: + ast.constant = true; + ast.toWatch = []; + break; + case AST.UnaryExpression: + findConstantAndWatchExpressions(ast.argument, $filter, astIsPure); + ast.constant = ast.argument.constant; + ast.toWatch = ast.argument.toWatch; + break; + case AST.BinaryExpression: + findConstantAndWatchExpressions(ast.left, $filter, astIsPure); + findConstantAndWatchExpressions(ast.right, $filter, astIsPure); + ast.constant = ast.left.constant && ast.right.constant; + ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch); + break; + case AST.LogicalExpression: + findConstantAndWatchExpressions(ast.left, $filter, astIsPure); + findConstantAndWatchExpressions(ast.right, $filter, astIsPure); + ast.constant = ast.left.constant && ast.right.constant; + ast.toWatch = ast.constant ? [] : [ast]; + break; + case AST.ConditionalExpression: + findConstantAndWatchExpressions(ast.test, $filter, astIsPure); + findConstantAndWatchExpressions(ast.alternate, $filter, astIsPure); + findConstantAndWatchExpressions(ast.consequent, $filter, astIsPure); + ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant; + ast.toWatch = ast.constant ? [] : [ast]; + break; + case AST.Identifier: + ast.constant = false; + ast.toWatch = [ast]; + break; + case AST.MemberExpression: + findConstantAndWatchExpressions(ast.object, $filter, astIsPure); + if (ast.computed) { + findConstantAndWatchExpressions(ast.property, $filter, astIsPure); + } + ast.constant = ast.object.constant && (!ast.computed || ast.property.constant); + ast.toWatch = ast.constant ? [] : [ast]; + break; + case AST.CallExpression: + isStatelessFilter = ast.filter ? isStateless($filter, ast.callee.name) : false; + allConstants = isStatelessFilter; + argsToWatch = []; + forEach(ast.arguments, function(expr) { + findConstantAndWatchExpressions(expr, $filter, astIsPure); + allConstants = allConstants && expr.constant; + argsToWatch.push.apply(argsToWatch, expr.toWatch); + }); + ast.constant = allConstants; + ast.toWatch = isStatelessFilter ? argsToWatch : [ast]; + break; + case AST.AssignmentExpression: + findConstantAndWatchExpressions(ast.left, $filter, astIsPure); + findConstantAndWatchExpressions(ast.right, $filter, astIsPure); + ast.constant = ast.left.constant && ast.right.constant; + ast.toWatch = [ast]; + break; + case AST.ArrayExpression: + allConstants = true; + argsToWatch = []; + forEach(ast.elements, function(expr) { + findConstantAndWatchExpressions(expr, $filter, astIsPure); + allConstants = allConstants && expr.constant; + argsToWatch.push.apply(argsToWatch, expr.toWatch); + }); + ast.constant = allConstants; + ast.toWatch = argsToWatch; + break; + case AST.ObjectExpression: + allConstants = true; + argsToWatch = []; + forEach(ast.properties, function(property) { + findConstantAndWatchExpressions(property.value, $filter, astIsPure); + allConstants = allConstants && property.value.constant; + argsToWatch.push.apply(argsToWatch, property.value.toWatch); + if (property.computed) { + //`{[key]: value}` implicitly does `key.toString()` which may be non-pure + findConstantAndWatchExpressions(property.key, $filter, /*parentIsPure=*/false); + allConstants = allConstants && property.key.constant; + argsToWatch.push.apply(argsToWatch, property.key.toWatch); + } + }); + ast.constant = allConstants; + ast.toWatch = argsToWatch; + break; + case AST.ThisExpression: + ast.constant = false; + ast.toWatch = []; + break; + case AST.LocalsExpression: + ast.constant = false; + ast.toWatch = []; + break; + } } -function simpleGetterFn2(key0, key1, fullExp) { - ensureSafeMemberName(key0, fullExp); - ensureSafeMemberName(key1, fullExp); +function getInputs(body) { + if (body.length !== 1) return; + var lastExpression = body[0].expression; + var candidate = lastExpression.toWatch; + if (candidate.length !== 1) return candidate; + return candidate[0] !== lastExpression ? candidate : undefined; +} - return function simpleGetterFn2(scope, locals) { - if (scope == null) return undefined; - scope = ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0]; - return scope == null ? undefined : scope[key1]; - }; +function isAssignable(ast) { + return ast.type === AST.Identifier || ast.type === AST.MemberExpression; } -function getterFn(path, options, fullExp) { - // Check whether the cache has this getter already. - // We can use hasOwnProperty directly on the cache because we ensure, - // see below, that the cache never stores a path called 'hasOwnProperty' - if (getterFnCache.hasOwnProperty(path)) { - return getterFnCache[path]; +function assignableAST(ast) { + if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) { + return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='}; } +} - var pathKeys = path.split('.'), - pathKeysLength = pathKeys.length, - fn; - - // When we have only 1 or 2 tokens, use optimized special case closures. - // http://jsperf.com/angularjs-parse-getter/6 - if (!options.unwrapPromises && pathKeysLength === 1) { - fn = simpleGetterFn1(pathKeys[0], fullExp); - } else if (!options.unwrapPromises && pathKeysLength === 2) { - fn = simpleGetterFn2(pathKeys[0], pathKeys[1], fullExp); - } else if (options.csp) { - if (pathKeysLength < 6) { - fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, - options); - } else { - fn = function(scope, locals) { - var i = 0, val; - do { - val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], - pathKeys[i++], fullExp, options)(scope, locals); +function isLiteral(ast) { + return ast.body.length === 0 || + ast.body.length === 1 && ( + ast.body[0].expression.type === AST.Literal || + ast.body[0].expression.type === AST.ArrayExpression || + ast.body[0].expression.type === AST.ObjectExpression); +} - locals = undefined; // clear after first iteration - scope = val; - } while (i < pathKeysLength); - return val; - }; - } - } else { - var code = 'var p;\n'; - forEach(pathKeys, function(key, index) { - ensureSafeMemberName(key, fullExp); - code += 'if(s == null) return undefined;\n' + - 's='+ (index - // we simply dereference 's' on any .dot notation - ? 's' - // but if we are first then we check locals first, and if so read it first - : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' + - (options.unwrapPromises - ? 'if (s && s.then) {\n' + - ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' + - ' if (!("$$v" in s)) {\n' + - ' p=s;\n' + - ' p.$$v = undefined;\n' + - ' p.then(function(v) {p.$$v=v;});\n' + - '}\n' + - ' s=s.$$v\n' + - '}\n' - : ''); - }); - code += 'return s;'; - - /* jshint -W054 */ - var evaledFnGetter = new Function('s', 'k', 'pw', code); // s=scope, k=locals, pw=promiseWarning - /* jshint +W054 */ - evaledFnGetter.toString = valueFn(code); - fn = options.unwrapPromises ? function(scope, locals) { - return evaledFnGetter(scope, locals, promiseWarning); - } : evaledFnGetter; - } +function isConstant(ast) { + return ast.constant; +} - // Only cache the value if it's not going to mess up the cache object - // This is more performant that using Object.prototype.hasOwnProperty.call - if (path !== 'hasOwnProperty') { - getterFnCache[path] = fn; - } - return fn; +function ASTCompiler($filter) { + this.$filter = $filter; } -/////////////////////////////////// +ASTCompiler.prototype = { + compile: function(ast) { + var self = this; + this.state = { + nextId: 0, + filters: {}, + fn: {vars: [], body: [], own: {}}, + assign: {vars: [], body: [], own: {}}, + inputs: [] + }; + findConstantAndWatchExpressions(ast, self.$filter); + var extra = ''; + var assignable; + this.stage = 'assign'; + if ((assignable = assignableAST(ast))) { + this.state.computing = 'assign'; + var result = this.nextId(); + this.recurse(assignable, result); + this.return_(result); + extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l'); + } + var toWatch = getInputs(ast.body); + self.stage = 'inputs'; + forEach(toWatch, function(watch, key) { + var fnKey = 'fn' + key; + self.state[fnKey] = {vars: [], body: [], own: {}}; + self.state.computing = fnKey; + var intoId = self.nextId(); + self.recurse(watch, intoId); + self.return_(intoId); + self.state.inputs.push({name: fnKey, isPure: watch.isPure}); + watch.watchId = key; + }); + this.state.computing = 'fn'; + this.stage = 'main'; + this.recurse(ast); + var fnString = + // The build and minification steps remove the string "use strict" from the code, but this is done using a regex. + // This is a workaround for this until we do a better job at only removing the prefix only when we should. + '"' + this.USE + ' ' + this.STRICT + '";\n' + + this.filterPrefix() + + 'var fn=' + this.generateFunction('fn', 's,l,a,i') + + extra + + this.watchFns() + + 'return fn;'; + + // eslint-disable-next-line no-new-func + var fn = (new Function('$filter', + 'getStringValue', + 'ifDefined', + 'plus', + fnString))( + this.$filter, + getStringValue, + ifDefined, + plusFn); + this.state = this.stage = undefined; + return fn; + }, -/** - * @ngdoc service - * @name $parse - * @kind function - * - * @description - * - * Converts Angular {@link guide/expression expression} into a function. - * - * ```js - * var getter = $parse('user.name'); - * var setter = getter.assign; - * var context = {user:{name:'angular'}}; - * var locals = {user:{name:'local'}}; - * - * expect(getter(context)).toEqual('angular'); - * setter(context, 'newValue'); - * expect(context.user.name).toEqual('newValue'); - * expect(getter(context, locals)).toEqual('local'); - * ``` - * - * - * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: - * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. - * - * The returned function also has the following properties: - * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript - * literal. - * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript - * constant literals. - * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be - * set to a function to change its value on the given context. - * - */ + USE: 'use', + STRICT: 'strict', -/** - * @ngdoc provider - * @name $parseProvider - * @function - * - * @description - * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} - * service. - */ -function $ParseProvider() { - var cache = {}; + watchFns: function() { + var result = []; + var inputs = this.state.inputs; + var self = this; + forEach(inputs, function(input) { + result.push('var ' + input.name + '=' + self.generateFunction(input.name, 's')); + if (input.isPure) { + result.push(input.name, '.isPure=' + JSON.stringify(input.isPure) + ';'); + } + }); + if (inputs.length) { + result.push('fn.inputs=[' + inputs.map(function(i) { return i.name; }).join(',') + '];'); + } + return result.join(''); + }, - var $parseOptions = { - csp: false, - unwrapPromises: false, - logPromiseWarnings: true - }; + generateFunction: function(name, params) { + return 'function(' + params + '){' + + this.varsPrefix(name) + + this.body(name) + + '};'; + }, + filterPrefix: function() { + var parts = []; + var self = this; + forEach(this.state.filters, function(id, filter) { + parts.push(id + '=$filter(' + self.escape(filter) + ')'); + }); + if (parts.length) return 'var ' + parts.join(',') + ';'; + return ''; + }, - /** - * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future. - * - * @ngdoc method - * @name $parseProvider#unwrapPromises - * @description - * - * **This feature is deprecated, see deprecation notes below for more info** - * - * If set to true (default is false), $parse will unwrap promises automatically when a promise is - * found at any part of the expression. In other words, if set to true, the expression will always - * result in a non-promise value. - * - * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled, - * the fulfillment value is used in place of the promise while evaluating the expression. - * - * **Deprecation notice** - * - * This is a feature that didn't prove to be wildly useful or popular, primarily because of the - * dichotomy between data access in templates (accessed as raw values) and controller code - * (accessed as promises). - * - * In most code we ended up resolving promises manually in controllers anyway and thus unifying - * the model access there. - * - * Other downsides of automatic promise unwrapping: - * - * - when building components it's often desirable to receive the raw promises - * - adds complexity and slows down expression evaluation - * - makes expression code pre-generation unattractive due to the amount of code that needs to be - * generated - * - makes IDE auto-completion and tool support hard - * - * **Warning Logs** - * - * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a - * promise (to reduce the noise, each expression is logged only once). To disable this logging use - * `$parseProvider.logPromiseWarnings(false)` api. - * - * - * @param {boolean=} value New value. - * @returns {boolean|self} Returns the current setting when used as getter and self if used as - * setter. - */ - this.unwrapPromises = function(value) { - if (isDefined(value)) { - $parseOptions.unwrapPromises = !!value; - return this; + varsPrefix: function(section) { + return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : ''; + }, + + body: function(section) { + return this.state[section].body.join(''); + }, + + recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) { + var left, right, self = this, args, expression, computed; + recursionFn = recursionFn || noop; + if (!skipWatchIdCheck && isDefined(ast.watchId)) { + intoId = intoId || this.nextId(); + this.if_('i', + this.lazyAssign(intoId, this.computedMember('i', ast.watchId)), + this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true) + ); + return; + } + switch (ast.type) { + case AST.Program: + forEach(ast.body, function(expression, pos) { + self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; }); + if (pos !== ast.body.length - 1) { + self.current().body.push(right, ';'); + } else { + self.return_(right); + } + }); + break; + case AST.Literal: + expression = this.escape(ast.value); + this.assign(intoId, expression); + recursionFn(intoId || expression); + break; + case AST.UnaryExpression: + this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; }); + expression = ast.operator + '(' + this.ifDefined(right, 0) + ')'; + this.assign(intoId, expression); + recursionFn(expression); + break; + case AST.BinaryExpression: + this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; }); + this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; }); + if (ast.operator === '+') { + expression = this.plus(left, right); + } else if (ast.operator === '-') { + expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0); + } else { + expression = '(' + left + ')' + ast.operator + '(' + right + ')'; + } + this.assign(intoId, expression); + recursionFn(expression); + break; + case AST.LogicalExpression: + intoId = intoId || this.nextId(); + self.recurse(ast.left, intoId); + self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId)); + recursionFn(intoId); + break; + case AST.ConditionalExpression: + intoId = intoId || this.nextId(); + self.recurse(ast.test, intoId); + self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId)); + recursionFn(intoId); + break; + case AST.Identifier: + intoId = intoId || this.nextId(); + if (nameId) { + nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s'); + nameId.computed = false; + nameId.name = ast.name; + } + self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)), + function() { + self.if_(self.stage === 'inputs' || 's', function() { + if (create && create !== 1) { + self.if_( + self.isNull(self.nonComputedMember('s', ast.name)), + self.lazyAssign(self.nonComputedMember('s', ast.name), '{}')); + } + self.assign(intoId, self.nonComputedMember('s', ast.name)); + }); + }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name)) + ); + recursionFn(intoId); + break; + case AST.MemberExpression: + left = nameId && (nameId.context = this.nextId()) || this.nextId(); + intoId = intoId || this.nextId(); + self.recurse(ast.object, left, undefined, function() { + self.if_(self.notNull(left), function() { + if (ast.computed) { + right = self.nextId(); + self.recurse(ast.property, right); + self.getStringValue(right); + if (create && create !== 1) { + self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}')); + } + expression = self.computedMember(left, right); + self.assign(intoId, expression); + if (nameId) { + nameId.computed = true; + nameId.name = right; + } + } else { + if (create && create !== 1) { + self.if_(self.isNull(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}')); + } + expression = self.nonComputedMember(left, ast.property.name); + self.assign(intoId, expression); + if (nameId) { + nameId.computed = false; + nameId.name = ast.property.name; + } + } + }, function() { + self.assign(intoId, 'undefined'); + }); + recursionFn(intoId); + }, !!create); + break; + case AST.CallExpression: + intoId = intoId || this.nextId(); + if (ast.filter) { + right = self.filter(ast.callee.name); + args = []; + forEach(ast.arguments, function(expr) { + var argument = self.nextId(); + self.recurse(expr, argument); + args.push(argument); + }); + expression = right + '(' + args.join(',') + ')'; + self.assign(intoId, expression); + recursionFn(intoId); + } else { + right = self.nextId(); + left = {}; + args = []; + self.recurse(ast.callee, right, left, function() { + self.if_(self.notNull(right), function() { + forEach(ast.arguments, function(expr) { + self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) { + args.push(argument); + }); + }); + if (left.name) { + expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')'; + } else { + expression = right + '(' + args.join(',') + ')'; + } + self.assign(intoId, expression); + }, function() { + self.assign(intoId, 'undefined'); + }); + recursionFn(intoId); + }); + } + break; + case AST.AssignmentExpression: + right = this.nextId(); + left = {}; + this.recurse(ast.left, undefined, left, function() { + self.if_(self.notNull(left.context), function() { + self.recurse(ast.right, right); + expression = self.member(left.context, left.name, left.computed) + ast.operator + right; + self.assign(intoId, expression); + recursionFn(intoId || expression); + }); + }, 1); + break; + case AST.ArrayExpression: + args = []; + forEach(ast.elements, function(expr) { + self.recurse(expr, ast.constant ? undefined : self.nextId(), undefined, function(argument) { + args.push(argument); + }); + }); + expression = '[' + args.join(',') + ']'; + this.assign(intoId, expression); + recursionFn(intoId || expression); + break; + case AST.ObjectExpression: + args = []; + computed = false; + forEach(ast.properties, function(property) { + if (property.computed) { + computed = true; + } + }); + if (computed) { + intoId = intoId || this.nextId(); + this.assign(intoId, '{}'); + forEach(ast.properties, function(property) { + if (property.computed) { + left = self.nextId(); + self.recurse(property.key, left); + } else { + left = property.key.type === AST.Identifier ? + property.key.name : + ('' + property.key.value); + } + right = self.nextId(); + self.recurse(property.value, right); + self.assign(self.member(intoId, left, property.computed), right); + }); + } else { + forEach(ast.properties, function(property) { + self.recurse(property.value, ast.constant ? undefined : self.nextId(), undefined, function(expr) { + args.push(self.escape( + property.key.type === AST.Identifier ? property.key.name : + ('' + property.key.value)) + + ':' + expr); + }); + }); + expression = '{' + args.join(',') + '}'; + this.assign(intoId, expression); + } + recursionFn(intoId || expression); + break; + case AST.ThisExpression: + this.assign(intoId, 's'); + recursionFn(intoId || 's'); + break; + case AST.LocalsExpression: + this.assign(intoId, 'l'); + recursionFn(intoId || 'l'); + break; + case AST.NGValueParameter: + this.assign(intoId, 'v'); + recursionFn(intoId || 'v'); + break; + } + }, + + getHasOwnProperty: function(element, property) { + var key = element + '.' + property; + var own = this.current().own; + if (!own.hasOwnProperty(key)) { + own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')'); + } + return own[key]; + }, + + assign: function(id, value) { + if (!id) return; + this.current().body.push(id, '=', value, ';'); + return id; + }, + + filter: function(filterName) { + if (!this.state.filters.hasOwnProperty(filterName)) { + this.state.filters[filterName] = this.nextId(true); + } + return this.state.filters[filterName]; + }, + + ifDefined: function(id, defaultValue) { + return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')'; + }, + + plus: function(left, right) { + return 'plus(' + left + ',' + right + ')'; + }, + + return_: function(id) { + this.current().body.push('return ', id, ';'); + }, + + if_: function(test, alternate, consequent) { + if (test === true) { + alternate(); } else { - return $parseOptions.unwrapPromises; + var body = this.current().body; + body.push('if(', test, '){'); + alternate(); + body.push('}'); + if (consequent) { + body.push('else{'); + consequent(); + body.push('}'); + } } - }; + }, + not: function(expression) { + return '!(' + expression + ')'; + }, - /** - * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future. - * - * @ngdoc method - * @name $parseProvider#logPromiseWarnings - * @description - * - * Controls whether Angular should log a warning on any encounter of a promise in an expression. - * - * The default is set to `true`. - * - * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well. - * - * @param {boolean=} value New value. - * @returns {boolean|self} Returns the current setting when used as getter and self if used as - * setter. - */ - this.logPromiseWarnings = function(value) { - if (isDefined(value)) { - $parseOptions.logPromiseWarnings = value; - return this; + isNull: function(expression) { + return expression + '==null'; + }, + + notNull: function(expression) { + return expression + '!=null'; + }, + + nonComputedMember: function(left, right) { + var SAFE_IDENTIFIER = /^[$_a-zA-Z][$_a-zA-Z0-9]*$/; + var UNSAFE_CHARACTERS = /[^$_a-zA-Z0-9]/g; + if (SAFE_IDENTIFIER.test(right)) { + return left + '.' + right; } else { - return $parseOptions.logPromiseWarnings; + return left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]'; } - }; + }, + + computedMember: function(left, right) { + return left + '[' + right + ']'; + }, + member: function(left, right, computed) { + if (computed) return this.computedMember(left, right); + return this.nonComputedMember(left, right); + }, - this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) { - $parseOptions.csp = $sniffer.csp; + getStringValue: function(item) { + this.assign(item, 'getStringValue(' + item + ')'); + }, - promiseWarning = function promiseWarningFn(fullExp) { - if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return; - promiseWarningCache[fullExp] = true; - $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' + - 'Automatic unwrapping of promises in Angular expressions is deprecated.'); + lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) { + var self = this; + return function() { + self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck); }; + }, - return function(exp) { - var parsedExpression; + lazyAssign: function(id, value) { + var self = this; + return function() { + self.assign(id, value); + }; + }, - switch (typeof exp) { - case 'string': + stringEscapeRegex: /[^ a-zA-Z0-9]/g, - if (cache.hasOwnProperty(exp)) { - return cache[exp]; - } + stringEscapeFn: function(c) { + return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4); + }, - var lexer = new Lexer($parseOptions); - var parser = new Parser(lexer, $filter, $parseOptions); - parsedExpression = parser.parse(exp, false); + escape: function(value) { + if (isString(value)) return '\'' + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + '\''; + if (isNumber(value)) return value.toString(); + if (value === true) return 'true'; + if (value === false) return 'false'; + if (value === null) return 'null'; + if (typeof value === 'undefined') return 'undefined'; - if (exp !== 'hasOwnProperty') { - // Only cache the value if it's not going to mess up the cache object - // This is more performant that using Object.prototype.hasOwnProperty.call - cache[exp] = parsedExpression; - } + throw $parseMinErr('esc', 'IMPOSSIBLE'); + }, - return parsedExpression; + nextId: function(skip, init) { + var id = 'v' + (this.state.nextId++); + if (!skip) { + this.current().vars.push(id + (init ? '=' + init : '')); + } + return id; + }, - case 'function': - return exp; + current: function() { + return this.state[this.state.computing]; + } +}; - default: - return noop; + +function ASTInterpreter($filter) { + this.$filter = $filter; +} + +ASTInterpreter.prototype = { + compile: function(ast) { + var self = this; + findConstantAndWatchExpressions(ast, self.$filter); + var assignable; + var assign; + if ((assignable = assignableAST(ast))) { + assign = this.recurse(assignable); + } + var toWatch = getInputs(ast.body); + var inputs; + if (toWatch) { + inputs = []; + forEach(toWatch, function(watch, key) { + var input = self.recurse(watch); + input.isPure = watch.isPure; + watch.input = input; + inputs.push(input); + watch.watchId = key; + }); + } + var expressions = []; + forEach(ast.body, function(expression) { + expressions.push(self.recurse(expression.expression)); + }); + var fn = ast.body.length === 0 ? noop : + ast.body.length === 1 ? expressions[0] : + function(scope, locals) { + var lastValue; + forEach(expressions, function(exp) { + lastValue = exp(scope, locals); + }); + return lastValue; + }; + if (assign) { + fn.assign = function(scope, value, locals) { + return assign(scope, locals, value); + }; + } + if (inputs) { + fn.inputs = inputs; + } + return fn; + }, + + recurse: function(ast, context, create) { + var left, right, self = this, args; + if (ast.input) { + return this.inputs(ast.input, ast.watchId); + } + switch (ast.type) { + case AST.Literal: + return this.value(ast.value, context); + case AST.UnaryExpression: + right = this.recurse(ast.argument); + return this['unary' + ast.operator](right, context); + case AST.BinaryExpression: + left = this.recurse(ast.left); + right = this.recurse(ast.right); + return this['binary' + ast.operator](left, right, context); + case AST.LogicalExpression: + left = this.recurse(ast.left); + right = this.recurse(ast.right); + return this['binary' + ast.operator](left, right, context); + case AST.ConditionalExpression: + return this['ternary?:']( + this.recurse(ast.test), + this.recurse(ast.alternate), + this.recurse(ast.consequent), + context + ); + case AST.Identifier: + return self.identifier(ast.name, context, create); + case AST.MemberExpression: + left = this.recurse(ast.object, false, !!create); + if (!ast.computed) { + right = ast.property.name; + } + if (ast.computed) right = this.recurse(ast.property); + return ast.computed ? + this.computedMember(left, right, context, create) : + this.nonComputedMember(left, right, context, create); + case AST.CallExpression: + args = []; + forEach(ast.arguments, function(expr) { + args.push(self.recurse(expr)); + }); + if (ast.filter) right = this.$filter(ast.callee.name); + if (!ast.filter) right = this.recurse(ast.callee, true); + return ast.filter ? + function(scope, locals, assign, inputs) { + var values = []; + for (var i = 0; i < args.length; ++i) { + values.push(args[i](scope, locals, assign, inputs)); + } + var value = right.apply(undefined, values, inputs); + return context ? {context: undefined, name: undefined, value: value} : value; + } : + function(scope, locals, assign, inputs) { + var rhs = right(scope, locals, assign, inputs); + var value; + if (rhs.value != null) { + var values = []; + for (var i = 0; i < args.length; ++i) { + values.push(args[i](scope, locals, assign, inputs)); + } + value = rhs.value.apply(rhs.context, values); + } + return context ? {value: value} : value; + }; + case AST.AssignmentExpression: + left = this.recurse(ast.left, true, 1); + right = this.recurse(ast.right); + return function(scope, locals, assign, inputs) { + var lhs = left(scope, locals, assign, inputs); + var rhs = right(scope, locals, assign, inputs); + lhs.context[lhs.name] = rhs; + return context ? {value: rhs} : rhs; + }; + case AST.ArrayExpression: + args = []; + forEach(ast.elements, function(expr) { + args.push(self.recurse(expr)); + }); + return function(scope, locals, assign, inputs) { + var value = []; + for (var i = 0; i < args.length; ++i) { + value.push(args[i](scope, locals, assign, inputs)); + } + return context ? {value: value} : value; + }; + case AST.ObjectExpression: + args = []; + forEach(ast.properties, function(property) { + if (property.computed) { + args.push({key: self.recurse(property.key), + computed: true, + value: self.recurse(property.value) + }); + } else { + args.push({key: property.key.type === AST.Identifier ? + property.key.name : + ('' + property.key.value), + computed: false, + value: self.recurse(property.value) + }); + } + }); + return function(scope, locals, assign, inputs) { + var value = {}; + for (var i = 0; i < args.length; ++i) { + if (args[i].computed) { + value[args[i].key(scope, locals, assign, inputs)] = args[i].value(scope, locals, assign, inputs); + } else { + value[args[i].key] = args[i].value(scope, locals, assign, inputs); + } + } + return context ? {value: value} : value; + }; + case AST.ThisExpression: + return function(scope) { + return context ? {value: scope} : scope; + }; + case AST.LocalsExpression: + return function(scope, locals) { + return context ? {value: locals} : locals; + }; + case AST.NGValueParameter: + return function(scope, locals, assign) { + return context ? {value: assign} : assign; + }; + } + }, + + 'unary+': function(argument, context) { + return function(scope, locals, assign, inputs) { + var arg = argument(scope, locals, assign, inputs); + if (isDefined(arg)) { + arg = +arg; + } else { + arg = 0; } + return context ? {value: arg} : arg; }; - }]; + }, + 'unary-': function(argument, context) { + return function(scope, locals, assign, inputs) { + var arg = argument(scope, locals, assign, inputs); + if (isDefined(arg)) { + arg = -arg; + } else { + arg = -0; + } + return context ? {value: arg} : arg; + }; + }, + 'unary!': function(argument, context) { + return function(scope, locals, assign, inputs) { + var arg = !argument(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary+': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var lhs = left(scope, locals, assign, inputs); + var rhs = right(scope, locals, assign, inputs); + var arg = plusFn(lhs, rhs); + return context ? {value: arg} : arg; + }; + }, + 'binary-': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var lhs = left(scope, locals, assign, inputs); + var rhs = right(scope, locals, assign, inputs); + var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0); + return context ? {value: arg} : arg; + }; + }, + 'binary*': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary/': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary%': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary===': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary!==': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary==': function(left, right, context) { + return function(scope, locals, assign, inputs) { + // eslint-disable-next-line eqeqeq + var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary!=': function(left, right, context) { + return function(scope, locals, assign, inputs) { + // eslint-disable-next-line eqeqeq + var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary<': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary>': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary<=': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary>=': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary&&': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'binary||': function(left, right, context) { + return function(scope, locals, assign, inputs) { + var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + 'ternary?:': function(test, alternate, consequent, context) { + return function(scope, locals, assign, inputs) { + var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs); + return context ? {value: arg} : arg; + }; + }, + value: function(value, context) { + return function() { return context ? {context: undefined, name: undefined, value: value} : value; }; + }, + identifier: function(name, context, create) { + return function(scope, locals, assign, inputs) { + var base = locals && (name in locals) ? locals : scope; + if (create && create !== 1 && base && base[name] == null) { + base[name] = {}; + } + var value = base ? base[name] : undefined; + if (context) { + return {context: base, name: name, value: value}; + } else { + return value; + } + }; + }, + computedMember: function(left, right, context, create) { + return function(scope, locals, assign, inputs) { + var lhs = left(scope, locals, assign, inputs); + var rhs; + var value; + if (lhs != null) { + rhs = right(scope, locals, assign, inputs); + rhs = getStringValue(rhs); + if (create && create !== 1) { + if (lhs && !(lhs[rhs])) { + lhs[rhs] = {}; + } + } + value = lhs[rhs]; + } + if (context) { + return {context: lhs, name: rhs, value: value}; + } else { + return value; + } + }; + }, + nonComputedMember: function(left, right, context, create) { + return function(scope, locals, assign, inputs) { + var lhs = left(scope, locals, assign, inputs); + if (create && create !== 1) { + if (lhs && lhs[right] == null) { + lhs[right] = {}; + } + } + var value = lhs != null ? lhs[right] : undefined; + if (context) { + return {context: lhs, name: right, value: value}; + } else { + return value; + } + }; + }, + inputs: function(input, watchId) { + return function(scope, value, locals, inputs) { + if (inputs) return inputs[watchId]; + return input(scope, value, locals); + }; + } +}; + +/** + * @constructor + */ +function Parser(lexer, $filter, options) { + this.ast = new AST(lexer, options); + this.astCompiler = options.csp ? new ASTInterpreter($filter) : + new ASTCompiler($filter); +} + +Parser.prototype = { + constructor: Parser, + + parse: function(text) { + var ast = this.getAst(text); + var fn = this.astCompiler.compile(ast.ast); + fn.literal = isLiteral(ast.ast); + fn.constant = isConstant(ast.ast); + fn.oneTime = ast.oneTime; + return fn; + }, + + getAst: function(exp) { + var oneTime = false; + exp = exp.trim(); + + if (exp.charAt(0) === ':' && exp.charAt(1) === ':') { + oneTime = true; + exp = exp.substring(2); + } + return { + ast: this.ast.ast(exp), + oneTime: oneTime + }; + } +}; + +function getValueOf(value) { + return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value); } +/////////////////////////////////// + /** * @ngdoc service - * @name $q - * @requires $rootScope - * + * @name $parse + * @kind function + * + * @description + * + * Converts AngularJS {@link guide/expression expression} into a function. + * + * ```js + * var getter = $parse('user.name'); + * var setter = getter.assign; + * var context = {user:{name:'AngularJS'}}; + * var locals = {user:{name:'local'}}; + * + * expect(getter(context)).toEqual('AngularJS'); + * setter(context, 'newValue'); + * expect(context.user.name).toEqual('newValue'); + * expect(getter(context, locals)).toEqual('local'); + * ``` + * + * + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: + * + * * `context` – `{object}` – an object against which any expressions embedded in the strings + * are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values in + * `context`. + * + * The returned function also has the following properties: + * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript + * literal. + * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript + * constant literals. + * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be + * set to a function to change its value on the given context. + * + */ + + +/** + * @ngdoc provider + * @name $parseProvider + * @this + * + * @description + * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} + * service. + */ +function $ParseProvider() { + var cache = createMap(); + var literals = { + 'true': true, + 'false': false, + 'null': null, + 'undefined': undefined + }; + var identStart, identContinue; + + /** + * @ngdoc method + * @name $parseProvider#addLiteral + * @description + * + * Configure $parse service to add literal values that will be present as literal at expressions. + * + * @param {string} literalName Token for the literal value. The literal name value must be a valid literal name. + * @param {*} literalValue Value for this literal. All literal values must be primitives or `undefined`. + * + **/ + this.addLiteral = function(literalName, literalValue) { + literals[literalName] = literalValue; + }; + + /** + * @ngdoc method + * @name $parseProvider#setIdentifierFns + * + * @description + * + * Allows defining the set of characters that are allowed in AngularJS expressions. The function + * `identifierStart` will get called to know if a given character is a valid character to be the + * first character for an identifier. The function `identifierContinue` will get called to know if + * a given character is a valid character to be a follow-up identifier character. The functions + * `identifierStart` and `identifierContinue` will receive as arguments the single character to be + * identifier and the character code point. These arguments will be `string` and `numeric`. Keep in + * mind that the `string` parameter can be two characters long depending on the character + * representation. It is expected for the function to return `true` or `false`, whether that + * character is allowed or not. + * + * Since this function will be called extensively, keep the implementation of these functions fast, + * as the performance of these functions have a direct impact on the expressions parsing speed. + * + * @param {function=} identifierStart The function that will decide whether the given character is + * a valid identifier start character. + * @param {function=} identifierContinue The function that will decide whether the given character is + * a valid identifier continue character. + */ + this.setIdentifierFns = function(identifierStart, identifierContinue) { + identStart = identifierStart; + identContinue = identifierContinue; + return this; + }; + + this.$get = ['$filter', function($filter) { + var noUnsafeEval = csp().noUnsafeEval; + var $parseOptions = { + csp: noUnsafeEval, + literals: copy(literals), + isIdentifierStart: isFunction(identStart) && identStart, + isIdentifierContinue: isFunction(identContinue) && identContinue + }; + $parse.$$getAst = $$getAst; + return $parse; + + function $parse(exp, interceptorFn) { + var parsedExpression, cacheKey; + + switch (typeof exp) { + case 'string': + exp = exp.trim(); + cacheKey = exp; + + parsedExpression = cache[cacheKey]; + + if (!parsedExpression) { + var lexer = new Lexer($parseOptions); + var parser = new Parser(lexer, $filter, $parseOptions); + parsedExpression = parser.parse(exp); + + cache[cacheKey] = addWatchDelegate(parsedExpression); + } + return addInterceptor(parsedExpression, interceptorFn); + + case 'function': + return addInterceptor(exp, interceptorFn); + + default: + return addInterceptor(noop, interceptorFn); + } + } + + function $$getAst(exp) { + var lexer = new Lexer($parseOptions); + var parser = new Parser(lexer, $filter, $parseOptions); + return parser.getAst(exp).ast; + } + + function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) { + + if (newValue == null || oldValueOfValue == null) { // null/undefined + return newValue === oldValueOfValue; + } + + if (typeof newValue === 'object') { + + // attempt to convert the value to a primitive type + // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can + // be cheaply dirty-checked + newValue = getValueOf(newValue); + + if (typeof newValue === 'object' && !compareObjectIdentity) { + // objects/arrays are not supported - deep-watching them would be too expensive + return false; + } + + // fall-through to the primitive equality check + } + + //Primitive or NaN + // eslint-disable-next-line no-self-compare + return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue); + } + + function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) { + var inputExpressions = parsedExpression.inputs; + var lastResult; + + if (inputExpressions.length === 1) { + var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails + inputExpressions = inputExpressions[0]; + return scope.$watch(function expressionInputWatch(scope) { + var newInputValue = inputExpressions(scope); + if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf, inputExpressions.isPure)) { + lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]); + oldInputValueOf = newInputValue && getValueOf(newInputValue); + } + return lastResult; + }, listener, objectEquality, prettyPrintExpression); + } + + var oldInputValueOfValues = []; + var oldInputValues = []; + for (var i = 0, ii = inputExpressions.length; i < ii; i++) { + oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails + oldInputValues[i] = null; + } + + return scope.$watch(function expressionInputsWatch(scope) { + var changed = false; + + for (var i = 0, ii = inputExpressions.length; i < ii; i++) { + var newInputValue = inputExpressions[i](scope); + if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i], inputExpressions[i].isPure))) { + oldInputValues[i] = newInputValue; + oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue); + } + } + + if (changed) { + lastResult = parsedExpression(scope, undefined, undefined, oldInputValues); + } + + return lastResult; + }, listener, objectEquality, prettyPrintExpression); + } + + function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) { + var isDone = parsedExpression.literal ? isAllDefined : isDefined; + var unwatch, lastValue; + + var exp = parsedExpression.$$intercepted || parsedExpression; + var post = parsedExpression.$$interceptor || identity; + + var useInputs = parsedExpression.inputs && !exp.inputs; + + // Propogate the literal/inputs/constant attributes + // ... but not oneTime since we are handling it + oneTimeWatch.literal = parsedExpression.literal; + oneTimeWatch.constant = parsedExpression.constant; + oneTimeWatch.inputs = parsedExpression.inputs; + + // Allow other delegates to run on this wrapped expression + addWatchDelegate(oneTimeWatch); + + unwatch = scope.$watch(oneTimeWatch, listener, objectEquality, prettyPrintExpression); + + return unwatch; + + function unwatchIfDone() { + if (isDone(lastValue)) { + unwatch(); + } + } + + function oneTimeWatch(scope, locals, assign, inputs) { + lastValue = useInputs && inputs ? inputs[0] : exp(scope, locals, assign, inputs); + if (isDone(lastValue)) { + scope.$$postDigest(unwatchIfDone); + } + return post(lastValue); + } + } + + function isAllDefined(value) { + var allDefined = true; + forEach(value, function(val) { + if (!isDefined(val)) allDefined = false; + }); + return allDefined; + } + + function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) { + var unwatch = scope.$watch(function constantWatch(scope) { + unwatch(); + return parsedExpression(scope); + }, listener, objectEquality); + return unwatch; + } + + function addWatchDelegate(parsedExpression) { + if (parsedExpression.constant) { + parsedExpression.$$watchDelegate = constantWatchDelegate; + } else if (parsedExpression.oneTime) { + parsedExpression.$$watchDelegate = oneTimeWatchDelegate; + } else if (parsedExpression.inputs) { + parsedExpression.$$watchDelegate = inputsWatchDelegate; + } + + return parsedExpression; + } + + function chainInterceptors(first, second) { + function chainedInterceptor(value) { + return second(first(value)); + } + chainedInterceptor.$stateful = first.$stateful || second.$stateful; + chainedInterceptor.$$pure = first.$$pure && second.$$pure; + + return chainedInterceptor; + } + + function addInterceptor(parsedExpression, interceptorFn) { + if (!interceptorFn) return parsedExpression; + + // Extract any existing interceptors out of the parsedExpression + // to ensure the original parsedExpression is always the $$intercepted + if (parsedExpression.$$interceptor) { + interceptorFn = chainInterceptors(parsedExpression.$$interceptor, interceptorFn); + parsedExpression = parsedExpression.$$intercepted; + } + + var useInputs = false; + + var fn = function interceptedExpression(scope, locals, assign, inputs) { + var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs); + return interceptorFn(value); + }; + + // Maintain references to the interceptor/intercepted + fn.$$intercepted = parsedExpression; + fn.$$interceptor = interceptorFn; + + // Propogate the literal/oneTime/constant attributes + fn.literal = parsedExpression.literal; + fn.oneTime = parsedExpression.oneTime; + fn.constant = parsedExpression.constant; + + // Treat the interceptor like filters. + // If it is not $stateful then only watch its inputs. + // If the expression itself has no inputs then use the full expression as an input. + if (!interceptorFn.$stateful) { + useInputs = !parsedExpression.inputs; + fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression]; + + if (!interceptorFn.$$pure) { + fn.inputs = fn.inputs.map(function(e) { + // Remove the isPure flag of inputs when it is not absolute because they are now wrapped in a + // non-pure interceptor function. + if (e.isPure === PURITY_RELATIVE) { + return function depurifier(s) { return e(s); }; + } + return e; + }); + } + } + + return addWatchDelegate(fn); + } + }]; +} + +/** + * @ngdoc service + * @name $q + * @requires $rootScope + * * @description - * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). + * A service that helps you run functions asynchronously, and use their return values (or exceptions) + * when they are done processing. + * + * This is a [Promises/A+](https://promisesaplus.com/)-compliant implementation of promises/deferred + * objects inspired by [Kris Kowal's Q](https://github.com/kriskowal/q). + * + * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred + * implementations, and the other which resembles ES6 (ES2015) promises to some degree. + * + * ## $q constructor + * + * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver` + * function as the first argument. This is similar to the native Promise implementation from ES6, + * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are + * available yet. + * + * It can be used like so: + * + * ```js + * // for the purpose of this example let's assume that variables `$q` and `okToGreet` + * // are available in the current lexical scope (they could have been injected or passed in). + * + * function asyncGreet(name) { + * // perform some asynchronous operation, resolve or reject the promise when appropriate. + * return $q(function(resolve, reject) { + * setTimeout(function() { + * if (okToGreet(name)) { + * resolve('Hello, ' + name + '!'); + * } else { + * reject('Greeting ' + name + ' is not allowed.'); + * } + * }, 1000); + * }); + * } + * + * var promise = asyncGreet('Robin Hood'); + * promise.then(function(greeting) { + * alert('Success: ' + greeting); + * }, function(reason) { + * alert('Failed: ' + reason); + * }); + * ``` + * + * Note: progress/notify callbacks are not currently supported via the ES6-style interface. + * + * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise. + * + * However, the more traditional CommonJS-style usage is still available, and documented below. * * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an * interface for interacting with an object that represents the result of an action that is @@ -11081,24 +17781,20 @@ function $ParseProvider() { * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. * * ```js - * // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet` + * // for the purpose of this example let's assume that variables `$q` and `okToGreet` * // are available in the current lexical scope (they could have been injected or passed in). * * function asyncGreet(name) { * var deferred = $q.defer(); * * setTimeout(function() { - * // since this fn executes async in a future turn of the event loop, we need to wrap - * // our code into an $apply call so that the model changes are properly observed. - * scope.$apply(function() { - * deferred.notify('About to greet ' + name + '.'); + * deferred.notify('About to greet ' + name + '.'); * - * if (okToGreet(name)) { - * deferred.resolve('Hello, ' + name + '!'); - * } else { - * deferred.reject('Greeting ' + name + ' is not allowed.'); - * } - * }); + * if (okToGreet(name)) { + * deferred.resolve('Hello, ' + name + '!'); + * } else { + * deferred.reject('Greeting ' + name + ' is not allowed.'); + * } * }, 1000); * * return deferred.promise; @@ -11123,8 +17819,7 @@ function $ParseProvider() { * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the * section on serial or parallel joining of promises. * - * - * # The Deferred API + * ## The Deferred API * * A new instance of deferred is constructed by calling `$q.defer()`. * @@ -11146,7 +17841,7 @@ function $ParseProvider() { * - promise – `{Promise}` – promise object associated with this deferred. * * - * # The Promise API + * ## The Promise API * * A new promise instance is created when a deferred instance is created and can be retrieved by * calling `deferred.promise`. @@ -11156,30 +17851,29 @@ function $ParseProvider() { * * **Methods** * - * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or + * - `then(successCallback, [errorCallback], [notifyCallback])` – regardless of when the promise was or * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously * as soon as the result is available. The callbacks are called with a single argument: the result * or rejection reason. Additionally, the notify callback may be called zero or more times to * provide a progress indication, before the promise is resolved or rejected. * * This method *returns a new promise* which is resolved or rejected via the return value of the - * `successCallback`, `errorCallback`. It also notifies via the return value of the - * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback - * method. + * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved + * with the value which is resolved in that promise using + * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)). + * It also notifies via the return value of the `notifyCallback` method. The promise cannot be + * resolved or rejected from the notifyCallback method. The errorCallback and notifyCallback + * arguments are optional. * * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` * - * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise, + * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise, * but to do so without modifying the final value. This is useful to release resources or do some * clean-up that needs to be done whether the promise was rejected or resolved. See the [full * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for * more information. * - * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as - * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to - * make your code IE8 and Android 2.x compatible. - * - * # Chaining promises + * ## Chaining promises * * Because calling the `then` method of a promise returns a new derived promise, it is easily * possible to create a chain of promises: @@ -11199,17 +17893,17 @@ function $ParseProvider() { * $http's response interceptors. * * - * # Differences between Kris Kowal's Q and $q + * ## Differences between Kris Kowal's Q and $q * * There are two main differences: * * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation - * mechanism in angular, which means faster propagation of resolution or rejection into your + * mechanism in AngularJS, which means faster propagation of resolution or rejection into your * models and avoiding unnecessary browser repaints, which would result in flickering UI. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains * all the important functionality needed for common async tasks. * - * # Testing + * ## Testing * * ```js * it('should simulate promise', inject(function($q, $rootScope) { @@ -11232,188 +17926,282 @@ function $ParseProvider() { * expect(resolvedValue).toEqual(123); * })); * ``` + * + * @param {function(function, function)} resolver Function which is responsible for resolving or + * rejecting the newly created promise. The first parameter is a function which resolves the + * promise, the second parameter is a function which rejects the promise. + * + * @returns {Promise} The newly created promise. + */ +/** + * @ngdoc provider + * @name $qProvider + * @this + * + * @description */ function $QProvider() { - + var errorOnUnhandledRejections = true; this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { return qFactory(function(callback) { $rootScope.$evalAsync(callback); - }, $exceptionHandler); + }, $exceptionHandler, errorOnUnhandledRejections); }]; + + /** + * @ngdoc method + * @name $qProvider#errorOnUnhandledRejections + * @kind function + * + * @description + * Retrieves or overrides whether to generate an error when a rejected promise is not handled. + * This feature is enabled by default. + * + * @param {boolean=} value Whether to generate an error when a rejected promise is not handled. + * @returns {boolean|ng.$qProvider} Current value when called without a new value or self for + * chaining otherwise. + */ + this.errorOnUnhandledRejections = function(value) { + if (isDefined(value)) { + errorOnUnhandledRejections = value; + return this; + } else { + return errorOnUnhandledRejections; + } + }; } +/** @this */ +function $$QProvider() { + var errorOnUnhandledRejections = true; + this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) { + return qFactory(function(callback) { + $browser.defer(callback); + }, $exceptionHandler, errorOnUnhandledRejections); + }]; + + this.errorOnUnhandledRejections = function(value) { + if (isDefined(value)) { + errorOnUnhandledRejections = value; + return this; + } else { + return errorOnUnhandledRejections; + } + }; +} /** * Constructs a promise manager. * - * @param {function(Function)} nextTick Function for executing functions in the next turn. + * @param {function(function)} nextTick Function for executing functions in the next turn. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for * debugging purposes. + * @param {boolean=} errorOnUnhandledRejections Whether an error should be generated on unhandled + * promises rejections. * @returns {object} Promise manager. */ -function qFactory(nextTick, exceptionHandler) { +function qFactory(nextTick, exceptionHandler, errorOnUnhandledRejections) { + var $qMinErr = minErr('$q', TypeError); + var queueSize = 0; + var checkQueue = []; /** * @ngdoc method - * @name $q#defer - * @function + * @name ng.$q#defer + * @kind function * * @description * Creates a `Deferred` object which represents a task which will finish in the future. * * @returns {Deferred} Returns a new instance of deferred. */ - var defer = function() { - var pending = [], - value, deferred; - - deferred = { - - resolve: function(val) { - if (pending) { - var callbacks = pending; - pending = undefined; - value = ref(val); - - if (callbacks.length) { - nextTick(function() { - var callback; - for (var i = 0, ii = callbacks.length; i < ii; i++) { - callback = callbacks[i]; - value.then(callback[0], callback[1], callback[2]); - } - }); - } - } - }, - + function defer() { + return new Deferred(); + } - reject: function(reason) { - deferred.resolve(createInternalRejectedPromise(reason)); - }, + function Deferred() { + var promise = this.promise = new Promise(); + //Non prototype methods necessary to support unbound execution :/ + this.resolve = function(val) { resolvePromise(promise, val); }; + this.reject = function(reason) { rejectPromise(promise, reason); }; + this.notify = function(progress) { notifyPromise(promise, progress); }; + } - notify: function(progress) { - if (pending) { - var callbacks = pending; + function Promise() { + this.$$state = { status: 0 }; + } - if (pending.length) { - nextTick(function() { - var callback; - for (var i = 0, ii = callbacks.length; i < ii; i++) { - callback = callbacks[i]; - callback[2](progress); - } - }); - } - } - }, + extend(Promise.prototype, { + then: function(onFulfilled, onRejected, progressBack) { + if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) { + return this; + } + var result = new Promise(); + this.$$state.pending = this.$$state.pending || []; + this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]); + if (this.$$state.status > 0) scheduleProcessQueue(this.$$state); - promise: { - then: function(callback, errback, progressback) { - var result = defer(); + return result; + }, - var wrappedCallback = function(value) { - try { - result.resolve((isFunction(callback) ? callback : defaultCallback)(value)); - } catch(e) { - result.reject(e); - exceptionHandler(e); - } - }; + 'catch': function(callback) { + return this.then(null, callback); + }, - var wrappedErrback = function(reason) { - try { - result.resolve((isFunction(errback) ? errback : defaultErrback)(reason)); - } catch(e) { - result.reject(e); - exceptionHandler(e); - } - }; + 'finally': function(callback, progressBack) { + return this.then(function(value) { + return handleCallback(value, resolve, callback); + }, function(error) { + return handleCallback(error, reject, callback); + }, progressBack); + } + }); - var wrappedProgressback = function(progress) { - try { - result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress)); - } catch(e) { - exceptionHandler(e); - } - }; + function processQueue(state) { + var fn, promise, pending; - if (pending) { - pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]); + pending = state.pending; + state.processScheduled = false; + state.pending = undefined; + try { + for (var i = 0, ii = pending.length; i < ii; ++i) { + markQStateExceptionHandled(state); + promise = pending[i][0]; + fn = pending[i][state.status]; + try { + if (isFunction(fn)) { + resolvePromise(promise, fn(state.value)); + } else if (state.status === 1) { + resolvePromise(promise, state.value); } else { - value.then(wrappedCallback, wrappedErrback, wrappedProgressback); + rejectPromise(promise, state.value); + } + } catch (e) { + rejectPromise(promise, e); + // This error is explicitly marked for being passed to the $exceptionHandler + if (e && e.$$passToExceptionHandler === true) { + exceptionHandler(e); } + } + } + } finally { + --queueSize; + if (errorOnUnhandledRejections && queueSize === 0) { + nextTick(processChecks); + } + } + } - return result.promise; - }, - - "catch": function(callback) { - return this.then(null, callback); - }, + function processChecks() { + // eslint-disable-next-line no-unmodified-loop-condition + while (!queueSize && checkQueue.length) { + var toCheck = checkQueue.shift(); + if (!isStateExceptionHandled(toCheck)) { + markQStateExceptionHandled(toCheck); + var errorMessage = 'Possibly unhandled rejection: ' + toDebugString(toCheck.value); + if (isError(toCheck.value)) { + exceptionHandler(toCheck.value, errorMessage); + } else { + exceptionHandler(errorMessage); + } + } + } + } - "finally": function(callback) { + function scheduleProcessQueue(state) { + if (errorOnUnhandledRejections && !state.pending && state.status === 2 && !isStateExceptionHandled(state)) { + if (queueSize === 0 && checkQueue.length === 0) { + nextTick(processChecks); + } + checkQueue.push(state); + } + if (state.processScheduled || !state.pending) return; + state.processScheduled = true; + ++queueSize; + nextTick(function() { processQueue(state); }); + } - function makePromise(value, resolved) { - var result = defer(); - if (resolved) { - result.resolve(value); - } else { - result.reject(value); - } - return result.promise; - } + function resolvePromise(promise, val) { + if (promise.$$state.status) return; + if (val === promise) { + $$reject(promise, $qMinErr( + 'qcycle', + 'Expected promise to be resolved with value other than itself \'{0}\'', + val)); + } else { + $$resolve(promise, val); + } - function handleCallback(value, isResolved) { - var callbackOutput = null; - try { - callbackOutput = (callback ||defaultCallback)(); - } catch(e) { - return makePromise(e, false); - } - if (callbackOutput && isFunction(callbackOutput.then)) { - return callbackOutput.then(function() { - return makePromise(value, isResolved); - }, function(error) { - return makePromise(error, false); - }); - } else { - return makePromise(value, isResolved); - } - } + } - return this.then(function(value) { - return handleCallback(value, true); - }, function(error) { - return handleCallback(error, false); - }); - } + function $$resolve(promise, val) { + var then; + var done = false; + try { + if (isObject(val) || isFunction(val)) then = val.then; + if (isFunction(then)) { + promise.$$state.status = -1; + then.call(val, doResolve, doReject, doNotify); + } else { + promise.$$state.value = val; + promise.$$state.status = 1; + scheduleProcessQueue(promise.$$state); } - }; + } catch (e) { + doReject(e); + } - return deferred; - }; + function doResolve(val) { + if (done) return; + done = true; + $$resolve(promise, val); + } + function doReject(val) { + if (done) return; + done = true; + $$reject(promise, val); + } + function doNotify(progress) { + notifyPromise(promise, progress); + } + } + function rejectPromise(promise, reason) { + if (promise.$$state.status) return; + $$reject(promise, reason); + } - var ref = function(value) { - if (value && isFunction(value.then)) return value; - return { - then: function(callback) { - var result = defer(); - nextTick(function() { - result.resolve(callback(value)); - }); - return result.promise; - } - }; - }; + function $$reject(promise, reason) { + promise.$$state.value = reason; + promise.$$state.status = 2; + scheduleProcessQueue(promise.$$state); + } + + function notifyPromise(promise, progress) { + var callbacks = promise.$$state.pending; + if ((promise.$$state.status <= 0) && callbacks && callbacks.length) { + nextTick(function() { + var callback, result; + for (var i = 0, ii = callbacks.length; i < ii; i++) { + result = callbacks[i][0]; + callback = callbacks[i][3]; + try { + notifyPromise(result, isFunction(callback) ? callback(progress) : progress); + } catch (e) { + exceptionHandler(e); + } + } + }); + } + } /** * @ngdoc method * @name $q#reject - * @function + * @kind function * * @description * Creates a promise that is resolved as rejected with the specified `reason`. This api should be @@ -11446,34 +18234,32 @@ function qFactory(nextTick, exceptionHandler) { * @param {*} reason Constant, message, exception or an object representing the rejection reason. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`. */ - var reject = function(reason) { - var result = defer(); - result.reject(reason); - return result.promise; - }; - - var createInternalRejectedPromise = function(reason) { - return { - then: function(callback, errback) { - var result = defer(); - nextTick(function() { - try { - result.resolve((isFunction(errback) ? errback : defaultErrback)(reason)); - } catch(e) { - result.reject(e); - exceptionHandler(e); - } - }); - return result.promise; - } - }; - }; + function reject(reason) { + var result = new Promise(); + rejectPromise(result, reason); + return result; + } + function handleCallback(value, resolver, callback) { + var callbackOutput = null; + try { + if (isFunction(callback)) callbackOutput = callback(); + } catch (e) { + return reject(e); + } + if (isPromiseLike(callbackOutput)) { + return callbackOutput.then(function() { + return resolver(value); + }, reject); + } else { + return resolver(value); + } + } /** * @ngdoc method * @name $q#when - * @function + * @kind function * * @description * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. @@ -11481,71 +18267,39 @@ function qFactory(nextTick, exceptionHandler) { * the promise comes from a source that can't be trusted. * * @param {*} value Value or a promise + * @param {Function=} successCallback + * @param {Function=} errorCallback + * @param {Function=} progressCallback * @returns {Promise} Returns a promise of the passed value or promise */ - var when = function(value, callback, errback, progressback) { - var result = defer(), - done; - - var wrappedCallback = function(value) { - try { - return (isFunction(callback) ? callback : defaultCallback)(value); - } catch (e) { - exceptionHandler(e); - return reject(e); - } - }; - - var wrappedErrback = function(reason) { - try { - return (isFunction(errback) ? errback : defaultErrback)(reason); - } catch (e) { - exceptionHandler(e); - return reject(e); - } - }; - - var wrappedProgressback = function(progress) { - try { - return (isFunction(progressback) ? progressback : defaultCallback)(progress); - } catch (e) { - exceptionHandler(e); - } - }; - - nextTick(function() { - ref(value).then(function(value) { - if (done) return; - done = true; - result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback)); - }, function(reason) { - if (done) return; - done = true; - result.resolve(wrappedErrback(reason)); - }, function(progress) { - if (done) return; - result.notify(wrappedProgressback(progress)); - }); - }); - - return result.promise; - }; - - function defaultCallback(value) { - return value; - } - - function defaultErrback(reason) { - return reject(reason); + function when(value, callback, errback, progressBack) { + var result = new Promise(); + resolvePromise(result, value); + return result.then(callback, errback, progressBack); } + /** + * @ngdoc method + * @name $q#resolve + * @kind function + * + * @description + * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6. + * + * @param {*} value Value or a promise + * @param {Function=} successCallback + * @param {Function=} errorCallback + * @param {Function=} progressCallback + * @returns {Promise} Returns a promise of the passed value or promise + */ + var resolve = when; /** * @ngdoc method * @name $q#all - * @function + * @kind function * * @description * Combines multiple promises into a single promise that is resolved when all of the input @@ -11557,47 +18311,111 @@ function qFactory(nextTick, exceptionHandler) { * If any of the promises is resolved with a rejection, this resulting promise will be rejected * with the same rejection value. */ + function all(promises) { - var deferred = defer(), + var result = new Promise(), counter = 0, results = isArray(promises) ? [] : {}; forEach(promises, function(promise, key) { counter++; - ref(promise).then(function(value) { - if (results.hasOwnProperty(key)) return; + when(promise).then(function(value) { results[key] = value; - if (!(--counter)) deferred.resolve(results); + if (!(--counter)) resolvePromise(result, results); }, function(reason) { - if (results.hasOwnProperty(key)) return; - deferred.reject(reason); + rejectPromise(result, reason); }); }); if (counter === 0) { - deferred.resolve(results); + resolvePromise(result, results); } + return result; + } + + /** + * @ngdoc method + * @name $q#race + * @kind function + * + * @description + * Returns a promise that resolves or rejects as soon as one of those promises + * resolves or rejects, with the value or reason from that promise. + * + * @param {Array.|Object.} promises An array or hash of promises. + * @returns {Promise} a promise that resolves or rejects as soon as one of the `promises` + * resolves or rejects, with the value or reason from that promise. + */ + + function race(promises) { + var deferred = defer(); + + forEach(promises, function(promise) { + when(promise).then(deferred.resolve, deferred.reject); + }); + return deferred.promise; } - return { - defer: defer, - reject: reject, - when: when, - all: all - }; + function $Q(resolver) { + if (!isFunction(resolver)) { + throw $qMinErr('norslvr', 'Expected resolverFn, got \'{0}\'', resolver); + } + + var promise = new Promise(); + + function resolveFn(value) { + resolvePromise(promise, value); + } + + function rejectFn(reason) { + rejectPromise(promise, reason); + } + + resolver(resolveFn, rejectFn); + + return promise; + } + + // Let's make the instanceof operator work for promises, so that + // `new $q(fn) instanceof $q` would evaluate to true. + $Q.prototype = Promise.prototype; + + $Q.defer = defer; + $Q.reject = reject; + $Q.when = when; + $Q.resolve = resolve; + $Q.all = all; + $Q.race = race; + + return $Q; +} + +function isStateExceptionHandled(state) { + return !!state.pur; +} +function markQStateExceptionHandled(state) { + state.pur = true; +} +function markQExceptionHandled(q) { + // Built-in `$q` promises will always have a `$$state` property. This check is to allow + // overwriting `$q` with a different promise library (e.g. Bluebird + angular-bluebird-promises). + // (Currently, this is the only method that might be called with a promise, even if it is not + // created by the built-in `$q`.) + if (q.$$state) { + markQStateExceptionHandled(q.$$state); + } } -function $$RAFProvider(){ //rAF +/** @this */ +function $$RAFProvider() { //rAF this.$get = ['$window', '$timeout', function($window, $timeout) { var requestAnimationFrame = $window.requestAnimationFrame || - $window.webkitRequestAnimationFrame || - $window.mozRequestAnimationFrame; + $window.webkitRequestAnimationFrame; var cancelAnimationFrame = $window.cancelAnimationFrame || $window.webkitCancelAnimationFrame || - $window.mozCancelAnimationFrame || $window.webkitCancelRequestAnimationFrame; var rafSupported = !!requestAnimationFrame; @@ -11635,15 +18453,15 @@ function $$RAFProvider(){ //rAF * exposed as $$____ properties * * Loop operations are optimized by using while(count--) { ... } - * - this means that in order to keep the same order of execution as addition we have to add - * items to the array at the beginning (shift) instead of at the end (push) + * - This means that in order to keep the same order of execution as addition we have to add + * items to the array at the beginning (unshift) instead of at the end (push) * * Child scopes are created and removed often - * - Using an array would be slow since inserts in middle are expensive so we use linked list + * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists * - * There are few watches then a lot of observers. This is why you don't want the observer to be - * implemented in the same way as watch. Watch requires return of initialization function which - * are expensive to construct. + * There are fewer watches than observers. This is why you don't want the observer to be implemented + * in the same way as watch. Watch requires return of the initialization function which is expensive + * to construct. */ @@ -11680,18 +18498,21 @@ function $$RAFProvider(){ //rAF /** * @ngdoc service * @name $rootScope + * @this + * * @description * * Every application has a single root {@link ng.$rootScope.Scope scope}. * All other scopes are descendant scopes of the root scope. Scopes provide separation * between the model and the view, via a mechanism for watching the model for changes. - * They also provide an event emission/broadcast and subscription facility. See the + * They also provide event emission/broadcast and subscription facility. See the * {@link guide/scope developer guide on scopes}. */ -function $RootScopeProvider(){ +function $RootScopeProvider() { var TTL = 10; var $rootScopeMinErr = minErr('$rootScope'); var lastDirtyWatch = null; + var applyAsyncId = null; this.digestTtl = function(value) { if (arguments.length) { @@ -11700,8 +18521,55 @@ function $RootScopeProvider(){ return TTL; }; - this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser', - function( $injector, $exceptionHandler, $parse, $browser) { + function createChildScopeClass(parent) { + function ChildScope() { + this.$$watchers = this.$$nextSibling = + this.$$childHead = this.$$childTail = null; + this.$$listeners = {}; + this.$$listenerCount = {}; + this.$$watchersCount = 0; + this.$id = nextUid(); + this.$$ChildScope = null; + this.$$suspended = false; + } + ChildScope.prototype = parent; + return ChildScope; + } + + this.$get = ['$exceptionHandler', '$parse', '$browser', + function($exceptionHandler, $parse, $browser) { + + function destroyChildScope($event) { + $event.currentScope.$$destroyed = true; + } + + function cleanUpScope($scope) { + + // Support: IE 9 only + if (msie === 9) { + // There is a memory leak in IE9 if all child scopes are not disconnected + // completely when a scope is destroyed. So this code will recurse up through + // all this scopes children + // + // See issue https://github.com/angular/angular.js/issues/10706 + if ($scope.$$childHead) { + cleanUpScope($scope.$$childHead); + } + if ($scope.$$nextSibling) { + cleanUpScope($scope.$$nextSibling); + } + } + + // The code below works around IE9 and V8's memory leaks + // + // See: + // - https://code.google.com/p/v8/issues/detail?id=2073#c26 + // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 + // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 + + $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead = + $scope.$$childTail = $scope.$root = $scope.$$watchers = null; + } /** * @ngdoc type @@ -11711,21 +18579,17 @@ function $RootScopeProvider(){ * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the * {@link auto.$injector $injector}. Child scopes are created using the * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when - * compiled HTML template is executed.) + * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for + * an in-depth introduction and usage examples. * - * Here is a simple scope snippet to show how you can interact with the scope. - * ```html - * - * ``` * - * # Inheritance + * ## Inheritance * A scope can inherit from a parent scope, as in this example: * ```js var parent = $rootScope; var child = parent.$new(); parent.salutation = "Hello"; - child.name = "World"; expect(child.salutation).toEqual('Hello'); child.salutation = "Welcome"; @@ -11733,6 +18597,10 @@ function $RootScopeProvider(){ expect(parent.salutation).toEqual('Hello'); * ``` * + * When interacting with `Scope` in tests, additional helper methods are available on the + * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional + * details. + * * * @param {Object.=} providers Map of service factory which need to be * provided for the current scope. Defaults to {@link ng}. @@ -11748,36 +18616,51 @@ function $RootScopeProvider(){ this.$$phase = this.$parent = this.$$watchers = this.$$nextSibling = this.$$prevSibling = this.$$childHead = this.$$childTail = null; - this['this'] = this.$root = this; + this.$root = this; this.$$destroyed = false; - this.$$asyncQueue = []; - this.$$postDigestQueue = []; + this.$$suspended = false; this.$$listeners = {}; this.$$listenerCount = {}; - this.$$isolateBindings = {}; + this.$$watchersCount = 0; + this.$$isolateBindings = null; } /** * @ngdoc property * @name $rootScope.Scope#$id - * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for - * debugging. + * + * @description + * Unique scope ID (monotonically increasing) useful for debugging. */ + /** + * @ngdoc property + * @name $rootScope.Scope#$parent + * + * @description + * Reference to the parent scope. + */ + + /** + * @ngdoc property + * @name $rootScope.Scope#$root + * + * @description + * Reference to the root scope. + */ Scope.prototype = { constructor: Scope, /** * @ngdoc method * @name $rootScope.Scope#$new - * @function + * @kind function * * @description * Creates a new child {@link ng.$rootScope.Scope scope}. * - * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and - * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the - * scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. + * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event. + * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}. * * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is * desired for the scope and its child scopes to be permanently detached from the parent and @@ -11788,70 +18671,84 @@ function $RootScopeProvider(){ * When creating widgets, it is useful for the widget to not accidentally read parent * state. * + * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent` + * of the newly created scope. Defaults to `this` scope if not provided. + * This is used when creating a transclude scope to correctly place it + * in the scope hierarchy while maintaining the correct prototypical + * inheritance. + * * @returns {Object} The newly created child scope. * */ - $new: function(isolate) { - var ChildScope, - child; + $new: function(isolate, parent) { + var child; + + parent = parent || this; if (isolate) { child = new Scope(); child.$root = this.$root; - // ensure that there is just one async queue per $rootScope and its children - child.$$asyncQueue = this.$$asyncQueue; - child.$$postDigestQueue = this.$$postDigestQueue; } else { - ChildScope = function() {}; // should be anonymous; This is so that when the minifier munges - // the name it does not become random set of chars. This will then show up as class - // name in the web inspector. - ChildScope.prototype = this; - child = new ChildScope(); - child.$id = nextUid(); - } - child['this'] = child; - child.$$listeners = {}; - child.$$listenerCount = {}; - child.$parent = this; - child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null; - child.$$prevSibling = this.$$childTail; - if (this.$$childHead) { - this.$$childTail.$$nextSibling = child; - this.$$childTail = child; + // Only create a child scope class if somebody asks for one, + // but cache it to allow the VM to optimize lookups. + if (!this.$$ChildScope) { + this.$$ChildScope = createChildScopeClass(this); + } + child = new this.$$ChildScope(); + } + child.$parent = parent; + child.$$prevSibling = parent.$$childTail; + if (parent.$$childHead) { + parent.$$childTail.$$nextSibling = child; + parent.$$childTail = child; } else { - this.$$childHead = this.$$childTail = child; + parent.$$childHead = parent.$$childTail = child; } + + // When the new scope is not isolated or we inherit from `this`, and + // the parent scope is destroyed, the property `$$destroyed` is inherited + // prototypically. In all other cases, this property needs to be set + // when the parent scope is destroyed. + // The listener needs to be added after the parent is set + if (isolate || parent !== this) child.$on('$destroy', destroyChildScope); + return child; }, /** * @ngdoc method * @name $rootScope.Scope#$watch - * @function + * @kind function * * @description * Registers a `listener` callback to be executed whenever the `watchExpression` changes. * * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest - * $digest()} and should return the value that will be watched. (Since - * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the - * `watchExpression` can execute multiple times per - * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.) + * $digest()} and should return the value that will be watched. (`watchExpression` should not change + * its value when executed multiple times with the same input because it may be executed multiple + * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be + * [idempotent](http://en.wikipedia.org/wiki/Idempotence).) * - The `listener` is called only when the value from the current `watchExpression` and the * previous call to `watchExpression` are not equal (with the exception of the initial run, - * see below). The inequality is determined according to - * {@link angular.equals} function. To save the value of the object for later comparison, - * the {@link angular.copy} function is used. It also means that watching complex options - * will have adverse memory and performance implications. + * see below). Inequality is determined according to reference inequality, + * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) + * via the `!==` Javascript operator, unless `objectEquality == true` + * (see next point) + * - When `objectEquality == true`, inequality of the `watchExpression` is determined + * according to the {@link angular.equals} function. To save the value of the object for + * later comparison, the {@link angular.copy} function is used. This therefore means that + * watching complex objects will have adverse memory and performance implications. + * - This should not be used to watch for changes in objects that are (or contain) + * [File](https://developer.mozilla.org/docs/Web/API/File) objects due to limitations with {@link angular.copy `angular.copy`}. * - The watch `listener` may change the model, which may trigger other `listener`s to fire. * This is achieved by rerunning the watchers until no changes are detected. The rerun * iteration limit is 10 to prevent an infinite loop deadlock. * * * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called, - * you can register a `watchExpression` function with no `listener`. (Since `watchExpression` - * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a - * change is detected, be prepared for multiple calls to your listener.) + * you can register a `watchExpression` function with no `listener`. (Be prepared for + * multiple calls to your `watchExpression` because it will execute multiple times in a + * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.) * * After a watcher is registered with the scope, the `listener` fn is called asynchronously * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the @@ -11860,10 +18757,9 @@ function $RootScopeProvider(){ * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the * listener was called due to initialization. * - * The example below contains an illustration of using a function as your $watch listener * * - * # Example + * @example * ```js // let's assume that scope was dependency injected as the $rootScope var scope = $rootScope; @@ -11877,23 +18773,27 @@ function $RootScopeProvider(){ expect(scope.counter).toEqual(0); scope.$digest(); - // no variable change - expect(scope.counter).toEqual(0); + // the listener is always called during the first $digest loop after it was registered + expect(scope.counter).toEqual(1); - scope.name = 'adam'; scope.$digest(); + // but now it will not be called unless the value changes expect(scope.counter).toEqual(1); + scope.name = 'adam'; + scope.$digest(); + expect(scope.counter).toEqual(2); + - // Using a listener function + // Using a function as a watchExpression var food; scope.foodCounter = 0; expect(scope.foodCounter).toEqual(0); scope.$watch( - // This is the listener function + // This function returns the value being watched. It is called for each turn of the $digest loop function() { return food; }, - // This is the change handler + // This is the change listener, called when the value returned from the above function changes function(newValue, oldValue) { if ( newValue !== oldValue ) { // Only increment the counter if the value changed @@ -11923,63 +18823,150 @@ function $RootScopeProvider(){ * * - `string`: Evaluated as {@link guide/expression expression} * - `function(scope)`: called with current `scope` as a parameter. - * @param {(function()|string)=} listener Callback called whenever the return value of - * the `watchExpression` changes. + * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value + * of `watchExpression` changes. * - * - `string`: Evaluated as {@link guide/expression expression} - * - `function(newValue, oldValue, scope)`: called with current and previous values as - * parameters. - * - * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of + * - `newVal` contains the current value of the `watchExpression` + * - `oldVal` contains the previous value of the `watchExpression` + * - `scope` refers to the current scope + * @param {boolean=} [objectEquality=false] Compare for object equality using {@link angular.equals} instead of * comparing for reference equality. * @returns {function()} Returns a deregistration function for this listener. */ - $watch: function(watchExp, listener, objectEquality) { + $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) { + var get = $parse(watchExp); + var fn = isFunction(listener) ? listener : noop; + + if (get.$$watchDelegate) { + return get.$$watchDelegate(this, fn, objectEquality, get, watchExp); + } var scope = this, - get = compileToFn(watchExp, 'watch'), array = scope.$$watchers, watcher = { - fn: listener, + fn: fn, last: initWatchVal, get: get, - exp: watchExp, + exp: prettyPrintExpression || watchExp, eq: !!objectEquality }; lastDirtyWatch = null; - // in the case user pass string, we need to compile it, do we really need this ? - if (!isFunction(listener)) { - var listenFn = compileToFn(listener || noop, 'listener'); - watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);}; - } - - if (typeof watchExp == 'string' && get.constant) { - var originalFn = watcher.fn; - watcher.fn = function(newVal, oldVal, scope) { - originalFn.call(this, newVal, oldVal, scope); - arrayRemove(array, watcher); - }; - } - if (!array) { array = scope.$$watchers = []; + array.$$digestWatchIndex = -1; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array.unshift(watcher); - - return function() { - arrayRemove(array, watcher); + array.$$digestWatchIndex++; + incrementWatchersCount(this, 1); + + return function deregisterWatch() { + var index = arrayRemove(array, watcher); + if (index >= 0) { + incrementWatchersCount(scope, -1); + if (index < array.$$digestWatchIndex) { + array.$$digestWatchIndex--; + } + } lastDirtyWatch = null; }; }, + /** + * @ngdoc method + * @name $rootScope.Scope#$watchGroup + * @kind function + * + * @description + * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`. + * If any one expression in the collection changes the `listener` is executed. + * + * - The items in the `watchExpressions` array are observed via the standard `$watch` operation. Their return + * values are examined for changes on every call to `$digest`. + * - The `listener` is called whenever any expression in the `watchExpressions` array changes. + * + * @param {Array.} watchExpressions Array of expressions that will be individually + * watched using {@link ng.$rootScope.Scope#$watch $watch()} + * + * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any + * expression in `watchExpressions` changes + * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching + * those of `watchExpression` + * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching + * those of `watchExpression` + * The `scope` refers to the current scope. + * @returns {function()} Returns a de-registration function for all listeners. + */ + $watchGroup: function(watchExpressions, listener) { + var oldValues = new Array(watchExpressions.length); + var newValues = new Array(watchExpressions.length); + var deregisterFns = []; + var self = this; + var changeReactionScheduled = false; + var firstRun = true; + + if (!watchExpressions.length) { + // No expressions means we call the listener ASAP + var shouldCall = true; + self.$evalAsync(function() { + if (shouldCall) listener(newValues, newValues, self); + }); + return function deregisterWatchGroup() { + shouldCall = false; + }; + } + + if (watchExpressions.length === 1) { + // Special case size of one + return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) { + newValues[0] = value; + oldValues[0] = oldValue; + listener(newValues, (value === oldValue) ? newValues : oldValues, scope); + }); + } + + forEach(watchExpressions, function(expr, i) { + var unwatchFn = self.$watch(expr, function watchGroupSubAction(value) { + newValues[i] = value; + if (!changeReactionScheduled) { + changeReactionScheduled = true; + self.$evalAsync(watchGroupAction); + } + }); + deregisterFns.push(unwatchFn); + }); + + function watchGroupAction() { + changeReactionScheduled = false; + + try { + if (firstRun) { + firstRun = false; + listener(newValues, newValues, self); + } else { + listener(newValues, oldValues, self); + } + } finally { + for (var i = 0; i < watchExpressions.length; i++) { + oldValues[i] = newValues[i]; + } + } + } + + return function deregisterWatchGroup() { + while (deregisterFns.length) { + deregisterFns.shift()(); + } + }; + }, + /** * @ngdoc method * @name $rootScope.Scope#$watchCollection - * @function + * @kind function * * @description * Shallow watches the properties of an object and fires whenever any of the properties change @@ -11992,7 +18979,7 @@ function $RootScopeProvider(){ * adding, removing, and moving items belonging to an object or array. * * - * # Example + * @example * ```js $scope.names = ['igor', 'matias', 'misko', 'james']; $scope.dataCount = 4; @@ -12032,6 +19019,12 @@ function $RootScopeProvider(){ * de-registration function is executed, the internal watch operation is terminated. */ $watchCollection: function(obj, listener) { + // Mark the interceptor as + // ... $$pure when literal since the instance will change when any input changes + $watchCollectionInterceptor.$$pure = $parse(obj).literal; + // ... $stateful when non-literal since we must read the state of the collection + $watchCollectionInterceptor.$stateful = !$watchCollectionInterceptor.$$pure; + var self = this; // the current value, updated on each dirty-check run var newValue; @@ -12043,15 +19036,18 @@ function $RootScopeProvider(){ // only track veryOldValue if the listener is asking for it var trackVeryOldValue = (listener.length > 1); var changeDetected = 0; - var objGetter = $parse(obj); + var changeDetector = $parse(obj, $watchCollectionInterceptor); var internalArray = []; var internalObject = {}; var initRun = true; var oldLength = 0; - function $watchCollectionWatch() { - newValue = objGetter(self); - var newLength, key; + function $watchCollectionInterceptor(_value) { + newValue = _value; + var newLength, key, bothNaN, newItem, oldItem; + + // If the new value is undefined, then return undefined as the watch may be a one-time watch + if (isUndefined(newValue)) return; if (!isObject(newValue)) { // if primitive if (oldValue !== newValue) { @@ -12075,11 +19071,14 @@ function $RootScopeProvider(){ } // copy the items to oldValue and look for changes. for (var i = 0; i < newLength; i++) { - var bothNaN = (oldValue[i] !== oldValue[i]) && - (newValue[i] !== newValue[i]); - if (!bothNaN && (oldValue[i] !== newValue[i])) { + oldItem = oldValue[i]; + newItem = newValue[i]; + + // eslint-disable-next-line no-self-compare + bothNaN = (oldItem !== oldItem) && (newItem !== newItem); + if (!bothNaN && (oldItem !== newItem)) { changeDetected++; - oldValue[i] = newValue[i]; + oldValue[i] = newItem; } } } else { @@ -12092,16 +19091,21 @@ function $RootScopeProvider(){ // copy the items to oldValue and look for changes. newLength = 0; for (key in newValue) { - if (newValue.hasOwnProperty(key)) { + if (hasOwnProperty.call(newValue, key)) { newLength++; - if (oldValue.hasOwnProperty(key)) { - if (oldValue[key] !== newValue[key]) { + newItem = newValue[key]; + oldItem = oldValue[key]; + + if (key in oldValue) { + // eslint-disable-next-line no-self-compare + bothNaN = (oldItem !== oldItem) && (newItem !== newItem); + if (!bothNaN && (oldItem !== newItem)) { changeDetected++; - oldValue[key] = newValue[key]; + oldValue[key] = newItem; } } else { oldLength++; - oldValue[key] = newValue[key]; + oldValue[key] = newItem; changeDetected++; } } @@ -12109,8 +19113,8 @@ function $RootScopeProvider(){ if (oldLength > newLength) { // we used to have more keys, need to find them and destroy them. changeDetected++; - for(key in oldValue) { - if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) { + for (key in oldValue) { + if (!hasOwnProperty.call(newValue, key)) { oldLength--; delete oldValue[key]; } @@ -12149,13 +19153,13 @@ function $RootScopeProvider(){ } } - return this.$watch($watchCollectionWatch, $watchCollectionAction); + return this.$watch(changeDetector, $watchCollectionAction); }, /** * @ngdoc method * @name $rootScope.Scope#$digest - * @function + * @kind function * * @description * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and @@ -12169,7 +19173,7 @@ function $RootScopeProvider(){ * {@link ng.directive:ngController controllers} or in * {@link ng.$compileProvider#directive directives}. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within - * a {@link ng.$compileProvider#directive directives}), which will force a `$digest()`. + * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`. * * If you want to be notified whenever `$digest()` is called, * you can register a `watchExpression` function with @@ -12177,7 +19181,7 @@ function $RootScopeProvider(){ * * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. * - * # Example + * @example * ```js var scope = ...; scope.name = 'misko'; @@ -12190,27 +19194,37 @@ function $RootScopeProvider(){ expect(scope.counter).toEqual(0); scope.$digest(); - // no variable change - expect(scope.counter).toEqual(0); + // the listener is always called during the first $digest loop after it was registered + expect(scope.counter).toEqual(1); - scope.name = 'adam'; scope.$digest(); + // but now it will not be called unless the value changes expect(scope.counter).toEqual(1); + + scope.name = 'adam'; + scope.$digest(); + expect(scope.counter).toEqual(2); * ``` * */ $digest: function() { - var watch, value, last, + var watch, value, last, fn, get, watchers, - asyncQueue = this.$$asyncQueue, - postDigestQueue = this.$$postDigestQueue, - length, dirty, ttl = TTL, - next, current, target = this, + next, current, target = asyncQueue.length ? $rootScope : this, watchLog = [], - logIdx, logMsg, asyncTask; + logIdx, asyncTask; beginPhase('$digest'); + // Check for changes to browser url that happened in sync before the call to $digest + $browser.$$checkUrlChange(); + + if (this === $rootScope && applyAsyncId !== null) { + // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then + // cancel the scheduled $apply and flush the queue of expressions to be evaluated. + $browser.defer.cancel(applyAsyncId); + flushApplyAsync(); + } lastDirtyWatch = null; @@ -12218,45 +19232,50 @@ function $RootScopeProvider(){ dirty = false; current = target; - while(asyncQueue.length) { + // It's safe for asyncQueuePosition to be a local variable here because this loop can't + // be reentered recursively. Calling $digest from a function passed to $evalAsync would + // lead to a '$digest already in progress' error. + for (var asyncQueuePosition = 0; asyncQueuePosition < asyncQueue.length; asyncQueuePosition++) { try { - asyncTask = asyncQueue.shift(); - asyncTask.scope.$eval(asyncTask.expression); + asyncTask = asyncQueue[asyncQueuePosition]; + fn = asyncTask.fn; + fn(asyncTask.scope, asyncTask.locals); } catch (e) { - clearPhase(); $exceptionHandler(e); } lastDirtyWatch = null; } + asyncQueue.length = 0; traverseScopesLoop: do { // "traverse the scopes" loop - if ((watchers = current.$$watchers)) { + if ((watchers = !current.$$suspended && current.$$watchers)) { // process our watches - length = watchers.length; - while (length--) { + watchers.$$digestWatchIndex = watchers.length; + while (watchers.$$digestWatchIndex--) { try { - watch = watchers[length]; + watch = watchers[watchers.$$digestWatchIndex]; // Most common watches are on primitives, in which case we can short // circuit it with === operator, only when === fails do we use .equals if (watch) { - if ((value = watch.get(current)) !== (last = watch.last) && + get = watch.get; + if ((value = get(current)) !== (last = watch.last) && !(watch.eq ? equals(value, last) - : (typeof value == 'number' && typeof last == 'number' - && isNaN(value) && isNaN(last)))) { + : (isNumberNaN(value) && isNumberNaN(last)))) { dirty = true; lastDirtyWatch = watch; - watch.last = watch.eq ? copy(value) : value; - watch.fn(value, ((last === initWatchVal) ? value : last), current); + watch.last = watch.eq ? copy(value, null) : value; + fn = watch.fn; + fn(value, ((last === initWatchVal) ? value : last), current); if (ttl < 5) { logIdx = 4 - ttl; if (!watchLog[logIdx]) watchLog[logIdx] = []; - logMsg = (isFunction(watch.exp)) - ? 'fn: ' + (watch.exp.name || watch.exp.toString()) - : watch.exp; - logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last); - watchLog[logIdx].push(logMsg); + watchLog[logIdx].push({ + msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp, + newVal: value, + oldVal: last + }); } } else if (watch === lastDirtyWatch) { // If the most recently dirty watcher is now clean, short circuit since the remaining watchers @@ -12266,7 +19285,6 @@ function $RootScopeProvider(){ } } } catch (e) { - clearPhase(); $exceptionHandler(e); } } @@ -12275,9 +19293,11 @@ function $RootScopeProvider(){ // Insanity Warning: scope depth-first traversal // yes, this code is a bit crazy, but it works and we have tests to prove it! // this piece should be kept in sync with the traversal in $broadcast - if (!(next = (current.$$childHead || + // (though it differs due to having the extra check for $$suspended and does not + // check $$listenerCount) + if (!(next = ((!current.$$suspended && current.$$watchersCount && current.$$childHead) || (current !== target && current.$$nextSibling)))) { - while(current !== target && !(next = current.$$nextSibling)) { + while (current !== target && !(next = current.$$nextSibling)) { current = current.$parent; } } @@ -12285,54 +19305,149 @@ function $RootScopeProvider(){ // `break traverseScopesLoop;` takes us to here - if((dirty || asyncQueue.length) && !(ttl--)) { + if ((dirty || asyncQueue.length) && !(ttl--)) { clearPhase(); throw $rootScopeMinErr('infdig', '{0} $digest() iterations reached. Aborting!\n' + 'Watchers fired in the last 5 iterations: {1}', - TTL, toJson(watchLog)); + TTL, watchLog); } } while (dirty || asyncQueue.length); clearPhase(); - while(postDigestQueue.length) { + // postDigestQueuePosition isn't local here because this loop can be reentered recursively. + while (postDigestQueuePosition < postDigestQueue.length) { try { - postDigestQueue.shift()(); + postDigestQueue[postDigestQueuePosition++](); } catch (e) { $exceptionHandler(e); } } - }, + postDigestQueue.length = postDigestQueuePosition = 0; + // Check for changes to browser url that happened during the $digest + // (for which no event is fired; e.g. via `history.pushState()`) + $browser.$$checkUrlChange(); + }, /** - * @ngdoc event - * @name $rootScope.Scope#$destroy - * @eventType broadcast on scope being destroyed + * @ngdoc method + * @name $rootScope.Scope#$suspend + * @kind function * * @description - * Broadcasted when a scope and its children are being destroyed. + * Suspend watchers of this scope subtree so that they will not be invoked during digest. * - * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to - * clean up DOM bindings before an element is removed from the DOM. + * This can be used to optimize your application when you know that running those watchers + * is redundant. + * + * **Warning** + * + * Suspending scopes from the digest cycle can have unwanted and difficult to debug results. + * Only use this approach if you are confident that you know what you are doing and have + * ample tests to ensure that bindings get updated as you expect. + * + * Some of the things to consider are: + * + * * Any external event on a directive/component will not trigger a digest while the hosting + * scope is suspended - even if the event handler calls `$apply()` or `$rootScope.$digest()`. + * * Transcluded content exists on a scope that inherits from outside a directive but exists + * as a child of the directive's containing scope. If the containing scope is suspended the + * transcluded scope will also be suspended, even if the scope from which the transcluded + * scope inherits is not suspended. + * * Multiple directives trying to manage the suspended status of a scope can confuse each other: + * * A call to `$suspend()` on an already suspended scope is a no-op. + * * A call to `$resume()` on a non-suspended scope is a no-op. + * * If two directives suspend a scope, then one of them resumes the scope, the scope will no + * longer be suspended. This could result in the other directive believing a scope to be + * suspended when it is not. + * * If a parent scope is suspended then all its descendants will be also excluded from future + * digests whether or not they have been suspended themselves. Note that this also applies to + * isolate child scopes. + * * Calling `$digest()` directly on a descendant of a suspended scope will still run the watchers + * for that scope and its descendants. When digesting we only check whether the current scope is + * locally suspended, rather than checking whether it has a suspended ancestor. + * * Calling `$resume()` on a scope that has a suspended ancestor will not cause the scope to be + * included in future digests until all its ancestors have been resumed. + * * Resolved promises, e.g. from explicit `$q` deferreds and `$http` calls, trigger `$apply()` + * against the `$rootScope` and so will still trigger a global digest even if the promise was + * initiated by a component that lives on a suspended scope. */ + $suspend: function() { + this.$$suspended = true; + }, /** * @ngdoc method - * @name $rootScope.Scope#$destroy - * @function + * @name $rootScope.Scope#$isSuspended + * @kind function * * @description - * Removes the current scope (and all of its children) from the parent scope. Removal implies - * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer - * propagate to the current scope and its children. Removal also implies that the current - * scope is eligible for garbage collection. + * Call this method to determine if this scope has been explicitly suspended. It will not + * tell you whether an ancestor has been suspended. + * To determine if this scope will be excluded from a digest triggered at the $rootScope, + * for example, you must check all its ancestors: * - * The `$destroy()` is usually used by directives such as - * {@link ng.directive:ngRepeat ngRepeat} for managing the - * unrolling of the loop. + * ``` + * function isExcludedFromDigest(scope) { + * while(scope) { + * if (scope.$isSuspended()) return true; + * scope = scope.$parent; + * } + * return false; + * ``` + * + * Be aware that a scope may not be included in digests if it has a suspended ancestor, + * even if `$isSuspended()` returns false. + * + * @returns true if the current scope has been suspended. + */ + $isSuspended: function() { + return this.$$suspended; + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$resume + * @kind function + * + * @description + * Resume watchers of this scope subtree in case it was suspended. + * + * See {@link $rootScope.Scope#$suspend} for information about the dangers of using this approach. + */ + $resume: function() { + this.$$suspended = false; + }, + + /** + * @ngdoc event + * @name $rootScope.Scope#$destroy + * @eventType broadcast on scope being destroyed + * + * @description + * Broadcasted when a scope and its children are being destroyed. + * + * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to + * clean up DOM bindings before an element is removed from the DOM. + */ + + /** + * @ngdoc method + * @name $rootScope.Scope#$destroy + * @kind function + * + * @description + * Removes the current scope (and all of its children) from the parent scope. Removal implies + * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer + * propagate to the current scope and its children. Removal also implies that the current + * scope is eligible for garbage collection. + * + * The `$destroy()` is usually used by directives such as + * {@link ng.directive:ngRepeat ngRepeat} for managing the + * unrolling of the loop. * * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope. * Application code can register a `$destroy` event handler that will give it a chance to @@ -12342,55 +19457,51 @@ function $RootScopeProvider(){ * clean up DOM bindings before an element is removed from the DOM. */ $destroy: function() { - // we can't destroy the root scope or a scope that has been already destroyed + // We can't destroy a scope that has been already destroyed. if (this.$$destroyed) return; var parent = this.$parent; this.$broadcast('$destroy'); this.$$destroyed = true; - if (this === $rootScope) return; - forEach(this.$$listenerCount, bind(null, decrementListenerCount, this)); + if (this === $rootScope) { + //Remove handlers attached to window when $rootScope is removed + $browser.$$applicationDestroyed(); + } + + incrementWatchersCount(this, -this.$$watchersCount); + for (var eventName in this.$$listenerCount) { + decrementListenerCount(this, this.$$listenerCount[eventName], eventName); + } // sever all the references to parent scopes (after this cleanup, the current scope should // not be retained by any of our references and should be eligible for garbage collection) - if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; - if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling; + if (parent && parent.$$childHead === this) parent.$$childHead = this.$$nextSibling; + if (parent && parent.$$childTail === this) parent.$$childTail = this.$$prevSibling; if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; - - // All of the code below is bogus code that works around V8's memory leak via optimized code - // and inline caches. - // - // see: - // - https://code.google.com/p/v8/issues/detail?id=2073#c26 - // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909 - // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451 - - this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = - this.$$childTail = this.$root = null; - - // don't reset these to null in case some async task tries to register a listener/watch/task + // Disable listeners, watchers and apply/digest methods + this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop; + this.$on = this.$watch = this.$watchGroup = function() { return noop; }; this.$$listeners = {}; - this.$$watchers = this.$$asyncQueue = this.$$postDigestQueue = []; - // prevent NPEs since these methods have references to properties we nulled out - this.$destroy = this.$digest = this.$apply = noop; - this.$on = this.$watch = function() { return noop; }; + // Disconnect the next sibling to prevent `cleanUpScope` destroying those too + this.$$nextSibling = null; + cleanUpScope(this); }, /** * @ngdoc method * @name $rootScope.Scope#$eval - * @function + * @kind function * * @description * Executes the `expression` on the current scope and returns the result. Any exceptions in - * the expression are propagated (uncaught). This is useful when evaluating Angular + * the expression are propagated (uncaught). This is useful when evaluating AngularJS * expressions. * - * # Example + * @example * ```js var scope = ng.$rootScope.Scope(); scope.a = 1; @@ -12400,7 +19511,7 @@ function $RootScopeProvider(){ expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); * ``` * - * @param {(string|function())=} expression An angular expression to be executed. + * @param {(string|function())=} expression An AngularJS expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. @@ -12415,7 +19526,7 @@ function $RootScopeProvider(){ /** * @ngdoc method * @name $rootScope.Scope#$evalAsync - * @function + * @kind function * * @description * Executes the expression on the current scope at a later point in time. @@ -12435,45 +19546,45 @@ function $RootScopeProvider(){ * will be scheduled. However, it is encouraged to always call code that changes the model * from within an `$apply` call. That includes code evaluated via `$evalAsync`. * - * @param {(string|function())=} expression An angular expression to be executed. + * @param {(string|function())=} expression An AngularJS expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with the current `scope` parameter. * + * @param {(object)=} locals Local variables object, useful for overriding values in scope. */ - $evalAsync: function(expr) { + $evalAsync: function(expr, locals) { // if we are outside of an $digest loop and this is the first time we are scheduling async // task also schedule async auto-flush - if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) { + if (!$rootScope.$$phase && !asyncQueue.length) { $browser.defer(function() { - if ($rootScope.$$asyncQueue.length) { + if (asyncQueue.length) { $rootScope.$digest(); } - }); + }, null, '$evalAsync'); } - this.$$asyncQueue.push({scope: this, expression: expr}); + asyncQueue.push({scope: this, fn: $parse(expr), locals: locals}); }, - $$postDigest : function(fn) { - this.$$postDigestQueue.push(fn); + $$postDigest: function(fn) { + postDigestQueue.push(fn); }, /** * @ngdoc method * @name $rootScope.Scope#$apply - * @function + * @kind function * * @description - * `$apply()` is used to execute an expression in angular from outside of the angular + * `$apply()` is used to execute an expression in AngularJS from outside of the AngularJS * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). - * Because we are calling into the angular framework we need to perform proper scope life + * Because we are calling into the AngularJS framework we need to perform proper scope life * cycle of {@link ng.$exceptionHandler exception handling}, * {@link ng.$rootScope.Scope#$digest executing watches}. * - * ## Life cycle + * **Life cycle: Pseudo-Code of `$apply()`** * - * # Pseudo-Code of `$apply()` * ```js function $apply(expr) { try { @@ -12497,7 +19608,7 @@ function $RootScopeProvider(){ * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. * * - * @param {(string|function())=} exp An angular expression to be executed. + * @param {(string|function())=} exp An AngularJS expression to be executed. * * - `string`: execute using the rules as defined in {@link guide/expression expression}. * - `function(scope)`: execute the function with current `scope` parameter. @@ -12507,24 +19618,58 @@ function $RootScopeProvider(){ $apply: function(expr) { try { beginPhase('$apply'); - return this.$eval(expr); + try { + return this.$eval(expr); + } finally { + clearPhase(); + } } catch (e) { $exceptionHandler(e); } finally { - clearPhase(); try { $rootScope.$digest(); } catch (e) { $exceptionHandler(e); + // eslint-disable-next-line no-unsafe-finally throw e; } } }, + /** + * @ngdoc method + * @name $rootScope.Scope#$applyAsync + * @kind function + * + * @description + * Schedule the invocation of $apply to occur at a later time. The actual time difference + * varies across browsers, but is typically around ~10 milliseconds. + * + * This can be used to queue up multiple expressions which need to be evaluated in the same + * digest. + * + * @param {(string|function())=} exp An AngularJS expression to be executed. + * + * - `string`: execute using the rules as defined in {@link guide/expression expression}. + * - `function(scope)`: execute the function with current `scope` parameter. + */ + $applyAsync: function(expr) { + var scope = this; + if (expr) { + applyAsyncQueue.push($applyAsyncExpression); + } + expr = $parse(expr); + scheduleApplyAsync(); + + function $applyAsyncExpression() { + scope.$eval(expr); + } + }, + /** * @ngdoc method * @name $rootScope.Scope#$on - * @function + * @kind function * * @description * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for @@ -12535,7 +19680,8 @@ function $RootScopeProvider(){ * * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or * `$broadcast`-ed. - * - `currentScope` - `{Scope}`: the current scope which is handling the event. + * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the + * event propagates through the scope hierarchy, this property is set to null. * - `name` - `{string}`: name of the event. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel * further event propagation (available only for events that were `$emit`-ed). @@ -12564,8 +19710,14 @@ function $RootScopeProvider(){ var self = this; return function() { - namedListeners[indexOf(namedListeners, listener)] = null; - decrementListenerCount(self, 1, name); + var indexOfListener = namedListeners.indexOf(listener); + if (indexOfListener !== -1) { + // Use delete in the hope of the browser deallocating the memory for the array entry, + // while not shifting the array indexes of other listeners. + // See issue https://github.com/angular/angular.js/issues/16135 + delete namedListeners[indexOfListener]; + decrementListenerCount(self, 1, name); + } }; }, @@ -12573,7 +19725,7 @@ function $RootScopeProvider(){ /** * @ngdoc method * @name $rootScope.Scope#$emit - * @function + * @kind function * * @description * Dispatches an event `name` upwards through the scope hierarchy notifying the @@ -12612,7 +19764,7 @@ function $RootScopeProvider(){ do { namedListeners = scope.$$listeners[name] || empty; event.currentScope = scope; - for (i=0, length=namedListeners.length; i= 8 ) { - normalizedVal = urlResolve(uri).href; - if (normalizedVal !== '' && !normalizedVal.match(regex)) { - return 'unsafe:'+normalizedVal; - } + return function sanitizeUri(uri, isMediaUrl) { + // if (!uri) return uri; + var regex = isMediaUrl ? imgSrcSanitizationTrustedUrlList : aHrefSanitizationTrustedUrlList; + var normalizedVal = urlResolve(uri && uri.trim()).href; + if (normalizedVal !== '' && !normalizedVal.match(regex)) { + return 'unsafe:' + normalizedVal; } return uri; }; }; } +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Any commits to this file should be reviewed with security in mind. * + * Changes to this file can potentially create security vulnerabilities. * + * An approval from 2 Core members with history of modifying * + * this file is required. * + * * + * Does the change somehow allow for arbitrary javascript to be executed? * + * Or allows for someone to change the prototype of built-in objects? * + * Or gives undesired access to variables likes document or window? * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/* exported $SceProvider, $SceDelegateProvider */ + var $sceMinErr = minErr('$sce'); var SCE_CONTEXTS = { + // HTML is used when there's HTML rendered (e.g. ng-bind-html, iframe srcdoc binding). HTML: 'html', + + // Style statements or stylesheets. Currently unused in AngularJS. CSS: 'css', + + // An URL used in a context where it refers to the source of media, which are not expected to be run + // as scripts, such as an image, audio, video, etc. + MEDIA_URL: 'mediaUrl', + + // An URL used in a context where it does not refer to a resource that loads code. + // A value that can be trusted as a URL can also trusted as a MEDIA_URL. URL: 'url', - // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a - // url. (e.g. ng-include, script src, templateUrl) + + // RESOURCE_URL is a subtype of URL used where the referred-to resource could be interpreted as + // code. (e.g. ng-include, script src binding, templateUrl) + // A value that can be trusted as a RESOURCE_URL, can also trusted as a URL and a MEDIA_URL. RESOURCE_URL: 'resourceUrl', + + // Script. Currently unused in AngularJS. JS: 'js' }; // Helper functions follow. -// Copied from: -// http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962 -// Prereq: s is a string. -function escapeForRegexp(s) { - return s.replace(/([-()\[\]{}+?*.$\^|,:# + * AngularJS strongly relies on contextual escaping for the security of bindings: disabling or + * modifying this might cause cross site scripting (XSS) vulnerabilities. For libraries owners, + * changes to this service will also influence users, so be extra careful and document your changes. + *
+ * * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to @@ -12907,121 +20153,177 @@ function adjustMatchers(matchers) { * The default instance of `$sceDelegate` should work out of the box with little pain. While you * can override it completely to change the behavior of `$sce`, the common case would * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting - * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as - * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist - * $sceDelegateProvider.resourceUrlWhitelist} and {@link - * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} + * your own trusted and banned resource lists for trusting URLs used for loading AngularJS resources + * such as templates. Refer {@link ng.$sceDelegateProvider#trustedResourceUrlList + * $sceDelegateProvider.trustedResourceUrlList} and {@link + * ng.$sceDelegateProvider#bannedResourceUrlList $sceDelegateProvider.bannedResourceUrlList} */ /** * @ngdoc provider * @name $sceDelegateProvider + * @this + * * @description * * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate - * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure - * that the URLs used for sourcing Angular templates are safe. Refer {@link - * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and - * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist} + * $sceDelegate service}, used as a delegate for {@link ng.$sce Strict Contextual Escaping (SCE)}. + * + * The `$sceDelegateProvider` allows one to get/set the `trustedResourceUrlList` and + * `bannedResourceUrlList` used to ensure that the URLs used for sourcing AngularJS templates and + * other script-running URLs are safe (all places that use the `$sce.RESOURCE_URL` context). See + * {@link ng.$sceDelegateProvider#trustedResourceUrlList + * $sceDelegateProvider.trustedResourceUrlList} and + * {@link ng.$sceDelegateProvider#bannedResourceUrlList $sceDelegateProvider.bannedResourceUrlList}, * - * For the general details about this service in Angular, read the main page for {@link ng.$sce + * For the general details about this service in AngularJS, read the main page for {@link ng.$sce * Strict Contextual Escaping (SCE)}. * * **Example**: Consider the following case.
* * - your app is hosted at url `http://myapp.example.com/` * - but some of your templates are hosted on other domains you control such as - * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc. + * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`. * * Here is what a secure configuration for this scenario might look like: * - *
- *    angular.module('myApp', []).config(function($sceDelegateProvider) {
- *      $sceDelegateProvider.resourceUrlWhitelist([
- *        // Allow same origin resource loads.
- *        'self',
- *        // Allow loading from our assets domain.  Notice the difference between * and **.
- *        'http://srv*.assets.example.com/**']);
- *
- *      // The blacklist overrides the whitelist so the open redirect here is blocked.
- *      $sceDelegateProvider.resourceUrlBlacklist([
- *        'http://myapp.example.com/clickThru**']);
- *      });
- * 
+ * ``` + * angular.module('myApp', []).config(function($sceDelegateProvider) { + * $sceDelegateProvider.trustedResourceUrlList([ + * // Allow same origin resource loads. + * 'self', + * // Allow loading from our assets domain. Notice the difference between * and **. + * 'http://srv*.assets.example.com/**' + * ]); + * + * // The banned resource URL list overrides the trusted resource URL list so the open redirect + * // here is blocked. + * $sceDelegateProvider.bannedResourceUrlList([ + * 'http://myapp.example.com/clickThru**' + * ]); + * }); + * ``` + * Note that an empty trusted resource URL list will block every resource URL from being loaded, and will require + * you to manually mark each one as trusted with `$sce.trustAsResourceUrl`. However, templates + * requested by {@link ng.$templateRequest $templateRequest} that are present in + * {@link ng.$templateCache $templateCache} will not go through this check. If you have a mechanism + * to populate your templates in that cache at config time, then it is a good idea to remove 'self' + * from the trusted resource URL lsit. This helps to mitigate the security impact of certain types + * of issues, like for instance attacker-controlled `ng-includes`. */ function $SceDelegateProvider() { this.SCE_CONTEXTS = SCE_CONTEXTS; // Resource URLs can also be trusted by policy. - var resourceUrlWhitelist = ['self'], - resourceUrlBlacklist = []; + var trustedResourceUrlList = ['self'], + bannedResourceUrlList = []; /** * @ngdoc method - * @name $sceDelegateProvider#resourceUrlWhitelist - * @function - * - * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value - * provided. This must be an array or null. A snapshot of this array is used so further - * changes to the array are ignored. + * @name $sceDelegateProvider#trustedResourceUrlList + * @kind function * + * @param {Array=} trustedResourceUrlList When provided, replaces the trustedResourceUrlList with + * the value provided. This must be an array or null. A snapshot of this array is used so + * further changes to the array are ignored. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items * allowed in this array. * - * Note: **an empty whitelist array will block all URLs**! + * @return {Array} The currently set trusted resource URL array. * - * @return {Array} the currently set whitelist array. + * @description + * Sets/Gets the list trusted of resource URLs. * - * The **default value** when no whitelist has been explicitly set is `['self']` allowing only - * same origin resource requests. + * The **default value** when no `trustedResourceUrlList` has been explicitly set is `['self']` + * allowing only same origin resource requests. * - * @description - * Sets/Gets the whitelist of trusted resource URLs. + *
+ * **Note:** the default `trustedResourceUrlList` of 'self' is not recommended if your app shares + * its origin with other apps! It is a good idea to limit it to only your application's directory. + *
*/ - this.resourceUrlWhitelist = function (value) { + this.trustedResourceUrlList = function(value) { if (arguments.length) { - resourceUrlWhitelist = adjustMatchers(value); + trustedResourceUrlList = adjustMatchers(value); } - return resourceUrlWhitelist; + return trustedResourceUrlList; }; /** * @ngdoc method - * @name $sceDelegateProvider#resourceUrlBlacklist - * @function + * @name $sceDelegateProvider#resourceUrlWhitelist + * @kind function * - * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value - * provided. This must be an array or null. A snapshot of this array is used so further - * changes to the array are ignored. + * @deprecated + * sinceVersion="1.8.1" * - * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items - * allowed in this array. + * This method is deprecated. Use {@link $sceDelegateProvider#trustedResourceUrlList + * trustedResourceUrlList} instead. + */ + Object.defineProperty(this, 'resourceUrlWhitelist', { + get: function() { + return this.trustedResourceUrlList; + }, + set: function(value) { + this.trustedResourceUrlList = value; + } + }); + + /** + * @ngdoc method + * @name $sceDelegateProvider#bannedResourceUrlList + * @kind function * - * The typical usage for the blacklist is to **block + * @param {Array=} bannedResourceUrlList When provided, replaces the `bannedResourceUrlList` with + * the value provided. This must be an array or null. A snapshot of this array is used so + * further changes to the array are ignored.

+ * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items + * allowed in this array.

+ * The typical usage for the `bannedResourceUrlList` is to **block * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as * these would otherwise be trusted but actually return content from the redirected domain. + *

+ * Finally, **the banned resource URL list overrides the trusted resource URL list** and has + * the final say. * - * Finally, **the blacklist overrides the whitelist** and has the final say. - * - * @return {Array} the currently set blacklist array. - * - * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there - * is no blacklist.) + * @return {Array} The currently set `bannedResourceUrlList` array. * * @description - * Sets/Gets the blacklist of trusted resource URLs. + * Sets/Gets the `bannedResourceUrlList` of trusted resource URLs. + * + * The **default value** when no trusted resource URL list has been explicitly set is the empty + * array (i.e. there is no `bannedResourceUrlList`.) */ - - this.resourceUrlBlacklist = function (value) { + this.bannedResourceUrlList = function(value) { if (arguments.length) { - resourceUrlBlacklist = adjustMatchers(value); + bannedResourceUrlList = adjustMatchers(value); } - return resourceUrlBlacklist; + return bannedResourceUrlList; }; - this.$get = ['$injector', function($injector) { + /** + * @ngdoc method + * @name $sceDelegateProvider#resourceUrlBlacklist + * @kind function + * + * @deprecated + * sinceVersion="1.8.1" + * + * This method is deprecated. Use {@link $sceDelegateProvider#bannedResourceUrlList + * bannedResourceUrlList} instead. + */ + Object.defineProperty(this, 'resourceUrlBlacklist', { + get: function() { + return this.bannedResourceUrlList; + }, + set: function(value) { + this.bannedResourceUrlList = value; + } + }); + + this.$get = ['$injector', '$$sanitizeUri', function($injector, $$sanitizeUri) { var htmlSanitizer = function htmlSanitizer(html) { throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); @@ -13034,7 +20336,7 @@ function $SceDelegateProvider() { function matchUrl(matcher, parsedUrl) { if (matcher === 'self') { - return urlIsSameOrigin(parsedUrl); + return urlIsSameOrigin(parsedUrl) || urlIsSameOriginAsBaseUrl(parsedUrl); } else { // definitely a regex. See adjustMatchers() return !!matcher.exec(parsedUrl.href); @@ -13044,17 +20346,17 @@ function $SceDelegateProvider() { function isResourceUrlAllowedByPolicy(url) { var parsedUrl = urlResolve(url.toString()); var i, n, allowed = false; - // Ensure that at least one item from the whitelist allows this url. - for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) { - if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) { + // Ensure that at least one item from the trusted resource URL list allows this url. + for (i = 0, n = trustedResourceUrlList.length; i < n; i++) { + if (matchUrl(trustedResourceUrlList[i], parsedUrl)) { allowed = true; break; } } if (allowed) { - // Ensure that no item from the blacklist blocked this url. - for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) { - if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) { + // Ensure that no item from the banned resource URL list has blocked this url. + for (i = 0, n = bannedResourceUrlList.length; i < n; i++) { + if (matchUrl(bannedResourceUrlList[i], parsedUrl)) { allowed = false; break; } @@ -13086,7 +20388,8 @@ function $SceDelegateProvider() { byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); - byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.MEDIA_URL] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.URL] = generateHolderType(byType[SCE_CONTEXTS.MEDIA_URL]); byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); @@ -13095,17 +20398,24 @@ function $SceDelegateProvider() { * @name $sceDelegate#trustAs * * @description - * Returns an object that is trusted by angular for use in specified strict - * contextual escaping contexts (such as ng-bind-html, ng-include, any src - * attribute interpolation, any dom event binding attribute interpolation - * such as for onclick, etc.) that uses the provided value. - * See {@link ng.$sce $sce} for enabling strict contextual escaping. - * - * @param {string} type The kind of context in which this value is safe for use. e.g. url, - * resourceUrl, html, js and css. - * @param {*} value The value that that should be considered trusted/safe. - * @returns {*} A value that can be used to stand in for the provided `value` in places - * where Angular expects a $sce.trustAs() return value. + * Returns a trusted representation of the parameter for the specified context. This trusted + * object will later on be used as-is, without any security check, by bindings or directives + * that require this security context. + * For instance, marking a string as trusted for the `$sce.HTML` context will entirely bypass + * the potential `$sanitize` call in corresponding `$sce.HTML` bindings or directives, such as + * `ng-bind-html`. Note that in most cases you won't need to call this function: if you have the + * sanitizer loaded, passing the value itself will render all the HTML that does not pose a + * security risk. + * + * See {@link ng.$sceDelegate#getTrusted getTrusted} for the function that will consume those + * trusted values, and {@link ng.$sce $sce} for general documentation about strict contextual + * escaping. + * + * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`, + * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`. + * + * @param {*} value The value that should be considered trusted. + * @return {*} A trusted representation of value, that can be used in the given context. */ function trustAs(type, trustedValue) { var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); @@ -13114,7 +20424,7 @@ function $SceDelegateProvider() { 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', type, trustedValue); } - if (trustedValue === null || trustedValue === undefined || trustedValue === '') { + if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') { return trustedValue; } // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting @@ -13137,11 +20447,11 @@ function $SceDelegateProvider() { * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. * * If the passed parameter is not a value that had been returned by {@link - * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is. + * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, it must be returned as-is. * * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} - * call or anything else. - * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs + * call or anything else. + * @return {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns * `value` unchanged. */ @@ -13158,28 +20468,56 @@ function $SceDelegateProvider() { * @name $sceDelegate#getTrusted * * @description - * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and - * returns the originally supplied value if the queried context type is a supertype of the - * created type. If this condition isn't satisfied, throws an exception. + * Given an object and a security context in which to assign it, returns a value that's safe to + * use in this context, which was represented by the parameter. To do so, this function either + * unwraps the safe type it has been given (for instance, a {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`} result), or it might try to sanitize the value given, depending on + * the context and sanitizer availablility. + * + * The contexts that can be sanitized are $sce.MEDIA_URL, $sce.URL and $sce.HTML. The first two are available + * by default, and the third one relies on the `$sanitize` service (which may be loaded through + * the `ngSanitize` module). Furthermore, for $sce.RESOURCE_URL context, a plain string may be + * accepted if the resource url policy defined by {@link ng.$sceDelegateProvider#trustedResourceUrlList + * `$sceDelegateProvider.trustedResourceUrlList`} and {@link ng.$sceDelegateProvider#bannedResourceUrlList + * `$sceDelegateProvider.bannedResourceUrlList`} accepts that resource. + * + * This function will throw if the safe type isn't appropriate for this context, or if the + * value given cannot be accepted in the context (which might be caused by sanitization not + * being available, or the value not being recognized as safe). + * + *

+ * Disabling auto-escaping is extremely dangerous, it usually creates a Cross Site Scripting + * (XSS) vulnerability in your application. + *
* - * @param {string} type The kind of context in which this value is to be used. + * @param {string} type The context in which this value is to be used (such as `$sce.HTML`). * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs - * `$sceDelegate.trustAs`} call. - * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs - * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception. + * `$sceDelegate.trustAs`} call, or anything else (which will not be considered trusted.) + * @return {*} A version of the value that's safe to use in the given context, or throws an + * exception if this is impossible. */ function getTrusted(type, maybeTrusted) { - if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') { + if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') { return maybeTrusted; } var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); + // If maybeTrusted is a trusted class instance or subclass instance, then unwrap and return + // as-is. if (constructor && maybeTrusted instanceof constructor) { return maybeTrusted.$$unwrapTrustedValue(); } - // If we get here, then we may only take one of two actions. - // 1. sanitize the value for the requested type, or - // 2. throw an exception. - if (type === SCE_CONTEXTS.RESOURCE_URL) { + + // If maybeTrusted is a trusted class instance but not of the correct trusted type + // then unwrap it and allow it to pass through to the rest of the checks + if (isFunction(maybeTrusted.$$unwrapTrustedValue)) { + maybeTrusted = maybeTrusted.$$unwrapTrustedValue(); + } + + // If we get here, then we will either sanitize the value or throw an exception. + if (type === SCE_CONTEXTS.MEDIA_URL || type === SCE_CONTEXTS.URL) { + // we attempt to sanitize non-resource URLs + return $$sanitizeUri(maybeTrusted.toString(), type === SCE_CONTEXTS.MEDIA_URL); + } else if (type === SCE_CONTEXTS.RESOURCE_URL) { if (isResourceUrlAllowedByPolicy(maybeTrusted)) { return maybeTrusted; } else { @@ -13188,8 +20526,10 @@ function $SceDelegateProvider() { maybeTrusted.toString()); } } else if (type === SCE_CONTEXTS.HTML) { + // htmlSanitizer throws its own error when no sanitizer is available. return htmlSanitizer(maybeTrusted); } + // Default error when the $sce service has no way to make the input safe. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); } @@ -13203,6 +20543,8 @@ function $SceDelegateProvider() { /** * @ngdoc provider * @name $sceProvider + * @this + * * @description * * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. @@ -13212,47 +20554,51 @@ function $SceDelegateProvider() { * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. */ -/* jshint maxlen: false*/ - /** * @ngdoc service * @name $sce - * @function + * @kind function * * @description * * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. * - * # Strict Contextual Escaping + * ## Strict Contextual Escaping + * + * Strict Contextual Escaping (SCE) is a mode in which AngularJS constrains bindings to only render + * trusted values. Its goal is to assist in writing code in a way that (a) is secure by default, and + * (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier. + * + * ### Overview * - * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain - * contexts to result in a value that is marked as safe to use for that context. One example of - * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer - * to these contexts as privileged or SCE contexts. + * To systematically block XSS security bugs, AngularJS treats all values as untrusted by default in + * HTML or sensitive URL bindings. When binding untrusted values, AngularJS will automatically + * run security checks on them (sanitizations, trusted URL resource, depending on context), or throw + * when it cannot guarantee the security of the result. That behavior depends strongly on contexts: + * HTML can be sanitized, but template URLs cannot, for instance. * - * As of version 1.2, Angular ships with SCE enabled by default. + * To illustrate this, consider the `ng-bind-html` directive. It renders its value directly as HTML: + * we call that the *context*. When given an untrusted input, AngularJS will attempt to sanitize it + * before rendering if a sanitizer is available, and throw otherwise. To bypass sanitization and + * render the input as-is, you will need to mark it as trusted for that context before attempting + * to bind it. * - * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows - * one to execute arbitrary javascript by the use of the expression() syntax. Refer - * to learn more about them. - * You can ensure your document is in standards mode and not quirks mode by adding `` - * to the top of your HTML document. + * As of version 1.2, AngularJS ships with SCE enabled by default. * - * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for - * security vulnerabilities such as XSS, clickjacking, etc. a lot easier. + * ### In practice * * Here's an example of a binding in a privileged context: * - *
- *     
- *     
- *
+ * ``` + * + *
+ * ``` * * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE - * disabled, this application allows the user to render arbitrary HTML into the DIV. - * In a more realistic example, one may be rendering user comments, blog articles, etc. via - * bindings. (HTML is just one example of a context where rendering user controlled input creates - * security vulnerabilities.) + * disabled, this application allows the user to render arbitrary HTML into the DIV, which would + * be an XSS security bug. In a more realistic example, one may be rendering user comments, blog + * articles, etc. via bindings. (HTML is just one example of a context where rendering user + * controlled input creates security vulnerabilities.) * * For the case of HTML, you might use a library, either on the client side, or on the server side, * to sanitize unsafe HTML before binding to the value and rendering it in the document. @@ -13262,50 +20608,54 @@ function $SceDelegateProvider() { * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some * properties/fields and forgot to update the binding to the sanitized value? * - * To be secure by default, you want to ensure that any such bindings are disallowed unless you can - * determine that something explicitly says it's safe to use a value for binding in that - * context. You can then audit your code (a simple grep would do) to ensure that this is only done - * for those values that you can easily tell are safe - because they were received from your server, - * sanitized by your library, etc. You can organize your codebase to help with this - perhaps - * allowing only the files in a specific directory to do this. Ensuring that the internal API - * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. + * To be secure by default, AngularJS makes sure bindings go through that sanitization, or + * any similar validation process, unless there's a good reason to trust the given value in this + * context. That trust is formalized with a function call. This means that as a developer, you + * can assume all untrusted bindings are safe. Then, to audit your code for binding security issues, + * you just need to ensure the values you mark as trusted indeed are safe - because they were + * received from your server, sanitized by your library, etc. You can organize your codebase to + * help with this - perhaps allowing only the files in a specific directory to do this. + * Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then + * becomes a more manageable task. * * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs} * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to - * obtain values that will be accepted by SCE / privileged contexts. + * build the trusted versions of your values. * - * - * ## How does it work? + * ### How does it work? * * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted - * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link - * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the - * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. + * $sce.getTrusted(context, value)} rather than to the value directly. Think of this function as + * a way to enforce the required security context in your data sink. Directives use {@link + * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs + * the {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals. Also, + * when binding without directives, AngularJS will understand the context of your bindings + * automatically. * * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly * simplified): * - *
- *   var ngBindHtmlDirective = ['$sce', function($sce) {
- *     return function(scope, element, attr) {
- *       scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
- *         element.html(value || '');
- *       });
- *     };
- *   }];
- * 
+ * ``` + * var ngBindHtmlDirective = ['$sce', function($sce) { + * return function(scope, element, attr) { + * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) { + * element.html(value || ''); + * }); + * }; + * }]; + * ``` * - * ## Impact on loading templates + * ### Impact on loading templates * * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as * `templateUrl`'s specified by {@link guide/directive directives}. * - * By default, Angular only loads templates from the same domain and protocol as the application + * By default, AngularJS only loads templates from the same domain and protocol as the application * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or - * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist - * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. + * protocols, you may either add them to the {@link ng.$sceDelegateProvider#trustedResourceUrlList + * trustedResourceUrlList} or {@link ng.$sce#trustAsResourceUrl wrap them} into trusted values. * * *Please note*: * The browser's @@ -13316,40 +20666,58 @@ function $SceDelegateProvider() { * won't work on all browsers. Also, loading templates from `file://` URL does not work on some * browsers. * - * ## This feels like too much overhead for the developer? + * ### This feels like too much overhead * * It's important to remember that SCE only applies to interpolation expressions. * * If your expressions are constant literals, they're automatically trusted and you don't need to - * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g. - * `
`) just works. - * - * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them - * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here. + * call `$sce.trustAs` on them (e.g. + * `
`) just works (remember to include the + * `ngSanitize` module). The `$sceDelegate` will also use the `$sanitize` service if it is available + * when binding untrusted values to `$sce.HTML` context. + * AngularJS provides an implementation in `angular-sanitize.js`, and if you + * wish to use it, you will also need to depend on the {@link ngSanitize `ngSanitize`} module in + * your application. * * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load * templates in `ng-include` from your application's domain without having to even know about SCE. * It blocks loading templates from other domains or loading templates over http from an https * served document. You can change these by setting your own custom {@link - * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link - * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs. + * ng.$sceDelegateProvider#trustedResourceUrlList trusted resource URL list} and {@link + * ng.$sceDelegateProvider#bannedResourceUrlList banned resource URL list} for matching such URLs. * * This significantly reduces the overhead. It is far easier to pay the small overhead and have an * application that's secure and can be audited to verify that with much more ease than bolting * security onto an application later. * * - * ## What trusted context types are supported? + * ### What trusted context types are supported? * * | Context | Notes | * |---------------------|----------------| - * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. | + * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. | * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. | - * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`
Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. | + * | `$sce.MEDIA_URL` | For URLs that are safe to render as media. Is automatically converted from string by sanitizing when needed. | + * | `$sce.URL` | For URLs that are safe to follow as links. Is automatically converted from string by sanitizing when needed. Note that `$sce.URL` makes a stronger statement about the URL than `$sce.MEDIA_URL` does and therefore contexts requiring values trusted for `$sce.URL` can be used anywhere that values trusted for `$sce.MEDIA_URL` are required.| + * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.)

Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` or `$sce.MEDIA_URL` do and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` or `$sce.MEDIA_URL` are required.

The {@link $sceDelegateProvider#trustedResourceUrlList $sceDelegateProvider#trustedResourceUrlList()} and {@link $sceDelegateProvider#bannedResourceUrlList $sceDelegateProvider#bannedResourceUrlList()} can be used to restrict trusted origins for `RESOURCE_URL` | * | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. | * - * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist}
+ * + *
+ * Be aware that, before AngularJS 1.7.0, `a[href]` and `img[src]` used to sanitize their + * interpolated values directly rather than rely upon {@link ng.$sce#getTrusted `$sce.getTrusted`}. + * + * **As of 1.7.0, this is no longer the case.** + * + * Now such interpolations are marked as requiring `$sce.URL` (for `a[href]`) or `$sce.MEDIA_URL` + * (for `img[src]`), so that the sanitization happens (via `$sce.getTrusted...`) when the `$interpolate` + * service evaluates the expressions. + *
+ * + * There are no CSS or JS context bindings in AngularJS currently, so their corresponding `$sce.trustAs` + * functions aren't useful yet. This might evolve. + * + * ### Format of items in {@link ng.$sceDelegateProvider#trustedResourceUrlList trustedResourceUrlList}/{@link ng.$sceDelegateProvider#bannedResourceUrlList bannedResourceUrlList} * * Each element in these arrays must be one of the following: * @@ -13362,22 +20730,22 @@ function $SceDelegateProvider() { * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters * match themselves. * - `*`: matches zero or more occurrences of any character other than one of the following 6 - * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use - * in a whitelist. + * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use + * for matching resource URL lists. * - `**`: matches zero or more occurrences of *any* character. As such, it's not - * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g. + * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might - * not have been the intention.) It's usage at the very end of the path is ok. (e.g. + * not have been the intention.) Its usage at the very end of the path is ok. (e.g. * http://foo.example.com/templates/**). * - **RegExp** (*see caveat below*) * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to * accidentally introduce a bug when one updates a complex expression (imho, all regexes should - * have good test coverage.). For instance, the use of `.` in the regex is correct only in a + * have good test coverage). For instance, the use of `.` in the regex is correct only in a * small number of cases. A `.` character in the regex used when matching the scheme or a * subdomain could be matched against a `:` or literal `.` that was likely not intended. It * is highly recommended to use the string patterns and only fall back to regular expressions - * if they as a last resort. + * as a last resort. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is * matched against the **entire** *normalized / absolute URL* of the resource being tested * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags @@ -13387,7 +20755,7 @@ function $SceDelegateProvider() { * remember to escape your regular expression (and be aware that you might need more than * one level of escaping depending on your templating engine and the way you interpolated * the value.) Do make use of your platform's escaping mechanism as it might be good - * enough before coding your own. e.g. Ruby has + * enough before coding your own. E.g. Ruby has * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape) * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape). * Javascript lacks a similar built in function for escaping. Take a look at Google @@ -13396,68 +20764,67 @@ function $SceDelegateProvider() { * * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. * - * ## Show me an example using SCE. + * ### Show me an example using SCE. * - * @example - - -
-

- User comments
- By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when - $sanitize is available. If $sanitize isn't available, this results in an error instead of an - exploit. -
-
- {{userComment.name}}: - -
-
-
-
-
- - - var mySceApp = angular.module('mySceApp', ['ngSanitize']); - - mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) { - var self = this; - $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) { - self.userComments = userComments; - }); - self.explicitlyTrustedHtml = $sce.trustAsHtml( - 'Hover over this text.'); - }); - - - -[ - { "name": "Alice", - "htmlComment": - "Is anyone reading this?" - }, - { "name": "Bob", - "htmlComment": "Yes! Am I the only other one?" - } -] - - - - describe('SCE doc demo', function() { - it('should sanitize untrusted values', function() { - expect(element(by.css('.htmlComment')).getInnerHtml()) - .toBe('Is anyone reading this?'); - }); - - it('should NOT sanitize explicitly trusted values', function() { - expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe( - 'Hover over this text.'); - }); - }); - -
+ * + * + *
+ *

+ * User comments
+ * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when + * $sanitize is available. If $sanitize isn't available, this results in an error instead of an + * exploit. + *
+ *
+ * {{userComment.name}}: + * + *
+ *
+ *
+ *
+ *
+ * + * + * angular.module('mySceApp', ['ngSanitize']) + * .controller('AppController', ['$http', '$templateCache', '$sce', + * function AppController($http, $templateCache, $sce) { + * var self = this; + * $http.get('test_data.json', {cache: $templateCache}).then(function(response) { + * self.userComments = response.data; + * }); + * self.explicitlyTrustedHtml = $sce.trustAsHtml( + * 'Hover over this text.'); + * }]); + * + * + * + * [ + * { "name": "Alice", + * "htmlComment": + * "Is anyone reading this?" + * }, + * { "name": "Bob", + * "htmlComment": "Yes! Am I the only other one?" + * } + * ] + * + * + * + * describe('SCE doc demo', function() { + * it('should sanitize untrusted values', function() { + * expect(element.all(by.css('.htmlComment')).first().getAttribute('innerHTML')) + * .toBe('Is anyone reading this?'); + * }); + * + * it('should NOT sanitize explicitly trusted values', function() { + * expect(element(by.id('explicitlyTrustedHtml')).getAttribute('innerHTML')).toBe( + * 'Hover over this text.'); + * }); + * }); + * + *
* * * @@ -13467,20 +20834,20 @@ function $SceDelegateProvider() { * for little coding overhead. It will be much harder to take an SCE disabled application and * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE * for cases where you have a lot of existing code that was written before SCE was introduced and - * you're migrating them a module at a time. + * you're migrating them a module at a time. Also do note that this is an app-wide setting, so if + * you are writing a library, you will cause security bugs applications using it. * * That said, here's how you can completely disable SCE: * - *
- *   angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
- *     // Completely disable SCE.  For demonstration purposes only!
- *     // Do not use in new projects.
- *     $sceProvider.enabled(false);
- *   });
- * 
+ * ``` + * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) { + * // Completely disable SCE. For demonstration purposes only! + * // Do not use in new projects or libraries. + * $sceProvider.enabled(false); + * }); + * ``` * */ -/* jshint maxlen: 100 */ function $SceProvider() { var enabled = true; @@ -13488,15 +20855,15 @@ function $SceProvider() { /** * @ngdoc method * @name $sceProvider#enabled - * @function + * @kind function * - * @param {boolean=} value If provided, then enables/disables SCE. - * @return {boolean} true if SCE is enabled, false otherwise. + * @param {boolean=} value If provided, then enables/disables SCE application-wide. + * @return {boolean} True if SCE is enabled, false otherwise. * * @description * Enables/disables SCE and returns the current value. */ - this.enabled = function (value) { + this.enabled = function(value) { if (arguments.length) { enabled = !!value; } @@ -13522,7 +20889,7 @@ function $SceProvider() { * such a value. * * - getTrusted(contextEnum, value) - * This function should return the a value that is safe to use in the context specified by + * This function should return the value that is safe to use in the context specified by * contextEnum or throw and exception otherwise. * * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be @@ -13545,36 +20912,37 @@ function $SceProvider() { * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value) * will also succeed. * - * Inheritance happens to capture this in a natural way. In some future, we - * may not use inheritance anymore. That is OK because no code outside of - * sce.js and sceSpecs.js would need to be aware of this detail. + * Inheritance happens to capture this in a natural way. In some future, we may not use + * inheritance anymore. That is OK because no code outside of sce.js and sceSpecs.js would need to + * be aware of this detail. */ - this.$get = ['$parse', '$sniffer', '$sceDelegate', function( - $parse, $sniffer, $sceDelegate) { - // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows + this.$get = ['$parse', '$sceDelegate', function( + $parse, $sceDelegate) { + // Support: IE 9-11 only + // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow // the "expression(javascript expression)" syntax which is insecure. - if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) { + if (enabled && msie < 8) { throw $sceMinErr('iequirks', - 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' + + 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' + 'mode. You can fix this by adding the text to the top of your HTML ' + 'document. See http://docs.angularjs.org/api/ng.$sce for more information.'); } - var sce = copy(SCE_CONTEXTS); + var sce = shallowCopy(SCE_CONTEXTS); /** * @ngdoc method * @name $sce#isEnabled - * @function + * @kind function * - * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you - * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. + * @return {Boolean} True if SCE is enabled, false otherwise. If you want to set the value, you + * have to do it at module config time on {@link ng.$sceProvider $sceProvider}. * * @description * Returns a boolean indicating if SCE is enabled. */ - sce.isEnabled = function () { + sce.isEnabled = function() { return enabled; }; sce.trustAs = $sceDelegate.trustAs; @@ -13588,31 +20956,31 @@ function $SceProvider() { /** * @ngdoc method - * @name $sce#parse + * @name $sce#parseAs * * @description - * Converts Angular {@link guide/expression expression} into a function. This is like {@link + * Converts AngularJS {@link guide/expression expression} into a function. This is like {@link * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*, * *result*)} * - * @param {string} type The kind of SCE context in which this result will be used. + * @param {string} type The SCE context in which this result will be used. * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: + * @return {function(context, locals)} A function which represents the compiled expression: * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. + * * `context` – `{object}` – an object against which any expressions embedded in the + * strings are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values + * in `context`. */ sce.parseAs = function sceParseAs(type, expr) { var parsed = $parse(expr); if (parsed.literal && parsed.constant) { return parsed; } else { - return function sceParseAsTrusted(self, locals) { - return sce.getTrusted(type, parsed(self, locals)); - }; + return $parse(expr, function(value) { + return sce.getTrusted(type, value); + }); } }; @@ -13621,18 +20989,18 @@ function $SceProvider() { * @name $sce#trustAs * * @description - * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, - * returns an object that is trusted by angular for use in specified strict contextual - * escaping contexts (such as ng-bind-html, ng-include, any src attribute - * interpolation, any dom event binding attribute interpolation such as for onclick, etc.) - * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual - * escaping. + * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such, returns a + * wrapped object that represents your value, and the trust you have in its safety for the given + * context. AngularJS can then use that value as-is in bindings of the specified secure context. + * This is used in bindings for `ng-bind-html`, `ng-include`, and most `src` attribute + * interpolations. See {@link ng.$sce $sce} for strict contextual escaping. * - * @param {string} type The kind of context in which this value is safe for use. e.g. url, - * resource_url, html, js and css. - * @param {*} value The value that that should be considered trusted/safe. - * @returns {*} A value that can be used to stand in for the provided `value` in places - * where Angular expects a $sce.trustAs() return value. + * @param {string} type The context in which this value is safe for use, e.g. `$sce.URL`, + * `$sce.RESOURCE_URL`, `$sce.HTML`, `$sce.JS` or `$sce.CSS`. + * + * @param {*} value The value that that should be considered trusted. + * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` + * in the context you specified. */ /** @@ -13643,26 +21011,37 @@ function $SceProvider() { * Shorthand method. `$sce.trustAsHtml(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml - * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the - * return value of {@link ng.$sce#trustAs $sce.trustAs}.) + * @param {*} value The value to mark as trusted for `$sce.HTML` context. + * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` + * in `$sce.HTML` context (like `ng-bind-html`). */ /** * @ngdoc method - * @name $sce#trustAsUrl + * @name $sce#trustAsCss + * + * @description + * Shorthand method. `$sce.trustAsCss(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.CSS, value)`} + * + * @param {*} value The value to mark as trusted for `$sce.CSS` context. + * @return {*} A wrapped version of value that can be used as a trusted variant + * of your `value` in `$sce.CSS` context. This context is currently unused, so there are + * almost no reasons to use this function so far. + */ + + /** + * @ngdoc method + * @name $sce#trustAsUrl * * @description * Shorthand method. `$sce.trustAsUrl(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`} * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl - * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the - * return value of {@link ng.$sce#trustAs $sce.trustAs}.) + * @param {*} value The value to mark as trusted for `$sce.URL` context. + * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` + * in `$sce.URL` context. That context is currently unused, so there are almost no reasons + * to use this function so far. */ /** @@ -13673,11 +21052,10 @@ function $SceProvider() { * Shorthand method. `$sce.trustAsResourceUrl(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl - * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the return - * value of {@link ng.$sce#trustAs $sce.trustAs}.) + * @param {*} value The value to mark as trusted for `$sce.RESOURCE_URL` context. + * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` + * in `$sce.RESOURCE_URL` context (template URLs in `ng-include`, most `src` attribute + * bindings, ...) */ /** @@ -13688,11 +21066,10 @@ function $SceProvider() { * Shorthand method. `$sce.trustAsJs(value)` → * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} * - * @param {*} value The value to trustAs. - * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs - * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives - * only accept expressions that are either literal constants or are the - * return value of {@link ng.$sce#trustAs $sce.trustAs}.) + * @param {*} value The value to mark as trusted for `$sce.JS` context. + * @return {*} A wrapped version of value that can be used as a trusted variant of your `value` + * in `$sce.JS` context. That context is currently unused, so there are almost no reasons to + * use this function so far. */ /** @@ -13701,16 +21078,17 @@ function $SceProvider() { * * @description * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, - * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the - * originally supplied value if the queried context type is a supertype of the created type. - * If this condition isn't satisfied, throws an exception. - * - * @param {string} type The kind of context in which this value is to be used. - * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`} - * call. - * @returns {*} The value the was originally provided to - * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context. - * Otherwise, throws an exception. + * takes any input, and either returns a value that's safe to use in the specified context, + * or throws an exception. This function is aware of trusted values created by the `trustAs` + * function and its shorthands, and when contexts are appropriate, returns the unwrapped value + * as-is. Finally, this function can also throw when there is no way to turn `maybeTrusted` in a + * safe value (e.g., no sanitization is available or possible.) + * + * @param {string} type The context in which this value is to be used. + * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs + * `$sce.trustAs`} call, or anything else (which will not be considered trusted.) + * @return {*} A version of the value that's safe to use in the given context, or throws an + * exception if this is impossible. */ /** @@ -13722,7 +21100,7 @@ function $SceProvider() { * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)` + * @return {*} The return value of `$sce.getTrusted($sce.HTML, value)` */ /** @@ -13734,7 +21112,7 @@ function $SceProvider() { * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)` + * @return {*} The return value of `$sce.getTrusted($sce.CSS, value)` */ /** @@ -13746,7 +21124,7 @@ function $SceProvider() { * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)` + * @return {*} The return value of `$sce.getTrusted($sce.URL, value)` */ /** @@ -13758,7 +21136,7 @@ function $SceProvider() { * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} * * @param {*} value The value to pass to `$sceDelegate.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` + * @return {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` */ /** @@ -13770,7 +21148,7 @@ function $SceProvider() { * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} * * @param {*} value The value to pass to `$sce.getTrusted`. - * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)` + * @return {*} The return value of `$sce.getTrusted($sce.JS, value)` */ /** @@ -13779,15 +21157,15 @@ function $SceProvider() { * * @description * Shorthand method. `$sce.parseAsHtml(expression string)` → - * {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`} + * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`} * * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: + * @return {function(context, locals)} A function which represents the compiled expression: * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. + * * `context` – `{object}` – an object against which any expressions embedded in the + * strings are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values + * in `context`. */ /** @@ -13796,15 +21174,15 @@ function $SceProvider() { * * @description * Shorthand method. `$sce.parseAsCss(value)` → - * {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`} + * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`} * * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: + * @return {function(context, locals)} A function which represents the compiled expression: * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. + * * `context` – `{object}` – an object against which any expressions embedded in the + * strings are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values + * in `context`. */ /** @@ -13813,15 +21191,15 @@ function $SceProvider() { * * @description * Shorthand method. `$sce.parseAsUrl(value)` → - * {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`} + * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`} * * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: + * @return {function(context, locals)} A function which represents the compiled expression: * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. + * * `context` – `{object}` – an object against which any expressions embedded in the + * strings are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values + * in `context`. */ /** @@ -13830,15 +21208,15 @@ function $SceProvider() { * * @description * Shorthand method. `$sce.parseAsResourceUrl(value)` → - * {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`} + * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`} * * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: + * @return {function(context, locals)} A function which represents the compiled expression: * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. + * * `context` – `{object}` – an object against which any expressions embedded in the + * strings are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values + * in `context`. */ /** @@ -13847,15 +21225,15 @@ function $SceProvider() { * * @description * Shorthand method. `$sce.parseAsJs(value)` → - * {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`} + * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`} * * @param {string} expression String expression to compile. - * @returns {function(context, locals)} a function which represents the compiled expression: + * @return {function(context, locals)} A function which represents the compiled expression: * - * * `context` – `{object}` – an object against which any expressions embedded in the strings - * are evaluated against (typically a scope object). - * * `locals` – `{object=}` – local variables context object, useful for overriding values in - * `context`. + * * `context` – `{object}` – an object against which any expressions embedded in the + * strings are evaluated against (typically a scope object). + * * `locals` – `{object=}` – local variables context object, useful for overriding values + * in `context`. */ // Shorthand delegations. @@ -13863,15 +21241,15 @@ function $SceProvider() { getTrusted = sce.getTrusted, trustAs = sce.trustAs; - forEach(SCE_CONTEXTS, function (enumValue, name) { + forEach(SCE_CONTEXTS, function(enumValue, name) { var lName = lowercase(name); - sce[camelCase("parse_as_" + lName)] = function (expr) { + sce[snakeToCamel('parse_as_' + lName)] = function(expr) { return parse(enumValue, expr); }; - sce[camelCase("get_trusted_" + lName)] = function (value) { + sce[snakeToCamel('get_trusted_' + lName)] = function(value) { return getTrusted(enumValue, value); }; - sce[camelCase("trust_as_" + lName)] = function (value) { + sce[snakeToCamel('trust_as_' + lName)] = function(value) { return trustAs(enumValue, value); }; }); @@ -13880,15 +21258,17 @@ function $SceProvider() { }]; } +/* exported $SnifferProvider */ + /** * !!! This is an undocumented "private" service !!! * * @name $sniffer * @requires $window * @requires $document + * @this * * @property {boolean} history Does the browser support html5 history api ? - * @property {boolean} hashchange Does the browser support hashchange event ? * @property {boolean} transitions Does the browser support CSS transition events ? * @property {boolean} animations Does the browser support CSS animation events ? * @@ -13898,38 +21278,32 @@ function $SceProvider() { function $SnifferProvider() { this.$get = ['$window', '$document', function($window, $document) { var eventSupport = {}, + // Chrome Packaged Apps are not allowed to access `history.pushState`. + // If not sandboxed, they can be detected by the presence of `chrome.app.runtime` + // (see https://developer.chrome.com/apps/api_index). If sandboxed, they can be detected by + // the presence of an extension runtime ID and the absence of other Chrome runtime APIs + // (see https://developer.chrome.com/apps/manifest/sandbox). + // (NW.js apps have access to Chrome APIs, but do support `history`.) + isNw = $window.nw && $window.nw.process, + isChromePackagedApp = + !isNw && + $window.chrome && + ($window.chrome.app && $window.chrome.app.runtime || + !$window.chrome.app && $window.chrome.runtime && $window.chrome.runtime.id), + hasHistoryPushState = !isChromePackagedApp && $window.history && $window.history.pushState, android = - int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), + toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), boxee = /Boxee/i.test(($window.navigator || {}).userAgent), document = $document[0] || {}, - documentMode = document.documentMode, - vendorPrefix, - vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/, bodyStyle = document.body && document.body.style, transitions = false, - animations = false, - match; + animations = false; if (bodyStyle) { - for(var prop in bodyStyle) { - if(match = vendorRegex.exec(prop)) { - vendorPrefix = match[0]; - vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1); - break; - } - } - - if(!vendorPrefix) { - vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit'; - } - - transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle)); - animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle)); - - if (android && (!transitions||!animations)) { - transitions = isString(document.body.style.webkitTransition); - animations = isString(document.body.style.webkitAnimation); - } + // Support: Android <5, Blackberry Browser 10, default Chrome in Android 4.4.x + // Mentioned browsers need a -webkit- prefix for transitions & animations. + transitions = !!('transition' in bodyStyle || 'webkitTransition' in bodyStyle); + animations = !!('animation' in bodyStyle || 'webkitAnimation' in bodyStyle); } @@ -13942,17 +21316,15 @@ function $SnifferProvider() { // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has // so let's not use the history API also // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined - // jshint -W018 - history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee), - // jshint +W018 - hashchange: 'onhashchange' in $window && - // IE8 compatible mode lies - (!documentMode || documentMode > 7), + history: !!(hasHistoryPushState && !(android < 4) && !boxee), hasEvent: function(event) { + // Support: IE 9-11 only // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have // it. In particular the event is not fired when backspace or delete key are pressed or // when cut operation is performed. - if (event == 'input' && msie == 9) return false; + // IE10+ implements 'input' event but it erroneously fires under various situations, + // e.g. when placeholder changes, or a form is focused. + if (event === 'input' && msie) return false; if (isUndefined(eventSupport[event])) { var divElm = document.createElement('div'); @@ -13962,66 +21334,444 @@ function $SnifferProvider() { return eventSupport[event]; }, csp: csp(), - vendorPrefix: vendorPrefix, - transitions : transitions, - animations : animations, - android: android, - msie : msie, - msieDocumentMode: documentMode + transitions: transitions, + animations: animations, + android: android + }; + }]; +} + +/** + * ! This is a private undocumented service ! + * + * @name $$taskTrackerFactory + * @description + * A function to create `TaskTracker` instances. + * + * A `TaskTracker` can keep track of pending tasks (grouped by type) and can notify interested + * parties when all pending tasks (or tasks of a specific type) have been completed. + * + * @param {$log} log - A logger instance (such as `$log`). Used to log error during callback + * execution. + * + * @this + */ +function $$TaskTrackerFactoryProvider() { + this.$get = valueFn(function(log) { return new TaskTracker(log); }); +} + +function TaskTracker(log) { + var self = this; + var taskCounts = {}; + var taskCallbacks = []; + + var ALL_TASKS_TYPE = self.ALL_TASKS_TYPE = '$$all$$'; + var DEFAULT_TASK_TYPE = self.DEFAULT_TASK_TYPE = '$$default$$'; + + /** + * Execute the specified function and decrement the appropriate `taskCounts` counter. + * If the counter reaches 0, all corresponding `taskCallbacks` are executed. + * + * @param {Function} fn - The function to execute. + * @param {string=} [taskType=DEFAULT_TASK_TYPE] - The type of task that is being completed. + */ + self.completeTask = completeTask; + + /** + * Increase the task count for the specified task type (or the default task type if non is + * specified). + * + * @param {string=} [taskType=DEFAULT_TASK_TYPE] - The type of task whose count will be increased. + */ + self.incTaskCount = incTaskCount; + + /** + * Execute the specified callback when all pending tasks have been completed. + * + * If there are no pending tasks, the callback is executed immediately. You can optionally limit + * the tasks that will be waited for to a specific type, by passing a `taskType`. + * + * @param {function} callback - The function to call when there are no pending tasks. + * @param {string=} [taskType=ALL_TASKS_TYPE] - The type of tasks that will be waited for. + */ + self.notifyWhenNoPendingTasks = notifyWhenNoPendingTasks; + + function completeTask(fn, taskType) { + taskType = taskType || DEFAULT_TASK_TYPE; + + try { + fn(); + } finally { + decTaskCount(taskType); + + var countForType = taskCounts[taskType]; + var countForAll = taskCounts[ALL_TASKS_TYPE]; + + // If at least one of the queues (`ALL_TASKS_TYPE` or `taskType`) is empty, run callbacks. + if (!countForAll || !countForType) { + var getNextCallback = !countForAll ? getLastCallback : getLastCallbackForType; + var nextCb; + + while ((nextCb = getNextCallback(taskType))) { + try { + nextCb(); + } catch (e) { + log.error(e); + } + } + } + } + } + + function decTaskCount(taskType) { + taskType = taskType || DEFAULT_TASK_TYPE; + if (taskCounts[taskType]) { + taskCounts[taskType]--; + taskCounts[ALL_TASKS_TYPE]--; + } + } + + function getLastCallback() { + var cbInfo = taskCallbacks.pop(); + return cbInfo && cbInfo.cb; + } + + function getLastCallbackForType(taskType) { + for (var i = taskCallbacks.length - 1; i >= 0; --i) { + var cbInfo = taskCallbacks[i]; + if (cbInfo.type === taskType) { + taskCallbacks.splice(i, 1); + return cbInfo.cb; + } + } + } + + function incTaskCount(taskType) { + taskType = taskType || DEFAULT_TASK_TYPE; + taskCounts[taskType] = (taskCounts[taskType] || 0) + 1; + taskCounts[ALL_TASKS_TYPE] = (taskCounts[ALL_TASKS_TYPE] || 0) + 1; + } + + function notifyWhenNoPendingTasks(callback, taskType) { + taskType = taskType || ALL_TASKS_TYPE; + if (!taskCounts[taskType]) { + callback(); + } else { + taskCallbacks.push({type: taskType, cb: callback}); + } + } +} + +var $templateRequestMinErr = minErr('$templateRequest'); + +/** + * @ngdoc provider + * @name $templateRequestProvider + * @this + * + * @description + * Used to configure the options passed to the {@link $http} service when making a template request. + * + * For example, it can be used for specifying the "Accept" header that is sent to the server, when + * requesting a template. + */ +function $TemplateRequestProvider() { + + var httpOptions; + + /** + * @ngdoc method + * @name $templateRequestProvider#httpOptions + * @description + * The options to be passed to the {@link $http} service when making the request. + * You can use this to override options such as the "Accept" header for template requests. + * + * The {@link $templateRequest} will set the `cache` and the `transformResponse` properties of the + * options if not overridden here. + * + * @param {string=} value new value for the {@link $http} options. + * @returns {string|self} Returns the {@link $http} options when used as getter and self if used as setter. + */ + this.httpOptions = function(val) { + if (val) { + httpOptions = val; + return this; + } + return httpOptions; + }; + + /** + * @ngdoc service + * @name $templateRequest + * + * @description + * The `$templateRequest` service runs security checks then downloads the provided template using + * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request + * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the + * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the + * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted + * when `tpl` is of type string and `$templateCache` has the matching entry. + * + * If you want to pass custom options to the `$http` service, such as setting the Accept header you + * can configure this via {@link $templateRequestProvider#httpOptions}. + * + * `$templateRequest` is used internally by {@link $compile}, {@link ngRoute.$route}, and directives such + * as {@link ngInclude} to download and cache templates. + * + * 3rd party modules should use `$templateRequest` if their services or directives are loading + * templates. + * + * @param {string|TrustedResourceUrl} tpl The HTTP request template URL + * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty + * + * @return {Promise} a promise for the HTTP response data of the given URL. + * + * @property {number} totalPendingRequests total amount of pending template requests being downloaded. + */ + this.$get = ['$exceptionHandler', '$templateCache', '$http', '$q', '$sce', + function($exceptionHandler, $templateCache, $http, $q, $sce) { + + function handleRequestFn(tpl, ignoreRequestError) { + handleRequestFn.totalPendingRequests++; + + // We consider the template cache holds only trusted templates, so + // there's no need to go through adding the template again to the trusted + // resources for keys that already are included in there. This also makes + // AngularJS accept any script directive, no matter its name. However, we + // still need to unwrap trusted types. + if (!isString(tpl) || isUndefined($templateCache.get(tpl))) { + tpl = $sce.getTrustedResourceUrl(tpl); + } + + var transformResponse = $http.defaults && $http.defaults.transformResponse; + + if (isArray(transformResponse)) { + transformResponse = transformResponse.filter(function(transformer) { + return transformer !== defaultHttpResponseTransform; + }); + } else if (transformResponse === defaultHttpResponseTransform) { + transformResponse = null; + } + + return $http.get(tpl, extend({ + cache: $templateCache, + transformResponse: transformResponse + }, httpOptions)) + .finally(function() { + handleRequestFn.totalPendingRequests--; + }) + .then(function(response) { + return $templateCache.put(tpl, response.data); + }, handleError); + + function handleError(resp) { + if (!ignoreRequestError) { + resp = $templateRequestMinErr('tpload', + 'Failed to load template: {0} (HTTP status: {1} {2})', + tpl, resp.status, resp.statusText); + + $exceptionHandler(resp); + } + + return $q.reject(resp); + } + } + + handleRequestFn.totalPendingRequests = 0; + + return handleRequestFn; + } + ]; +} + +/** @this */ +function $$TestabilityProvider() { + this.$get = ['$rootScope', '$browser', '$location', + function($rootScope, $browser, $location) { + + /** + * @name $testability + * + * @description + * The private $$testability service provides a collection of methods for use when debugging + * or by automated test and debugging tools. + */ + var testability = {}; + + /** + * @name $$testability#findBindings + * + * @description + * Returns an array of elements that are bound (via ng-bind or {{}}) + * to expressions matching the input. + * + * @param {Element} element The element root to search from. + * @param {string} expression The binding expression to match. + * @param {boolean} opt_exactMatch If true, only returns exact matches + * for the expression. Filters and whitespace are ignored. + */ + testability.findBindings = function(element, expression, opt_exactMatch) { + var bindings = element.getElementsByClassName('ng-binding'); + var matches = []; + forEach(bindings, function(binding) { + var dataBinding = angular.element(binding).data('$binding'); + if (dataBinding) { + forEach(dataBinding, function(bindingName) { + if (opt_exactMatch) { + var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)'); + if (matcher.test(bindingName)) { + matches.push(binding); + } + } else { + if (bindingName.indexOf(expression) !== -1) { + matches.push(binding); + } + } + }); + } + }); + return matches; + }; + + /** + * @name $$testability#findModels + * + * @description + * Returns an array of elements that are two-way found via ng-model to + * expressions matching the input. + * + * @param {Element} element The element root to search from. + * @param {string} expression The model expression to match. + * @param {boolean} opt_exactMatch If true, only returns exact matches + * for the expression. + */ + testability.findModels = function(element, expression, opt_exactMatch) { + var prefixes = ['ng-', 'data-ng-', 'ng\\:']; + for (var p = 0; p < prefixes.length; ++p) { + var attributeEquals = opt_exactMatch ? '=' : '*='; + var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]'; + var elements = element.querySelectorAll(selector); + if (elements.length) { + return elements; + } + } + }; + + /** + * @name $$testability#getLocation + * + * @description + * Shortcut for getting the location in a browser agnostic way. Returns + * the path, search, and hash. (e.g. /path?a=b#hash) + */ + testability.getLocation = function() { + return $location.url(); + }; + + /** + * @name $$testability#setLocation + * + * @description + * Shortcut for navigating to a location without doing a full page reload. + * + * @param {string} url The location url (path, search and hash, + * e.g. /path?a=b#hash) to go to. + */ + testability.setLocation = function(url) { + if (url !== $location.url()) { + $location.url(url); + $rootScope.$digest(); + } + }; + + /** + * @name $$testability#whenStable + * + * @description + * Calls the callback when all pending tasks are completed. + * + * Types of tasks waited for include: + * - Pending timeouts (via {@link $timeout}). + * - Pending HTTP requests (via {@link $http}). + * - In-progress route transitions (via {@link $route}). + * - Pending tasks scheduled via {@link $rootScope#$applyAsync}. + * - Pending tasks scheduled via {@link $rootScope#$evalAsync}. + * These include tasks scheduled via `$evalAsync()` indirectly (such as {@link $q} promises). + * + * @param {function} callback + */ + testability.whenStable = function(callback) { + $browser.notifyWhenNoOutstandingRequests(callback); }; + + return testability; }]; } +var $timeoutMinErr = minErr('$timeout'); + +/** @this */ function $TimeoutProvider() { - this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler', - function($rootScope, $browser, $q, $exceptionHandler) { + this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler', + function($rootScope, $browser, $q, $$q, $exceptionHandler) { + var deferreds = {}; - /** - * @ngdoc service - * @name $timeout - * - * @description - * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch - * block and delegates any exceptions to - * {@link ng.$exceptionHandler $exceptionHandler} service. - * - * The return value of registering a timeout function is a promise, which will be resolved when - * the timeout is reached and the timeout function is executed. - * - * To cancel a timeout request, call `$timeout.cancel(promise)`. - * - * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to - * synchronously flush the queue of deferred functions. - * - * @param {function()} fn A function, whose execution should be delayed. - * @param {number=} [delay=0] Delay in milliseconds. - * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise - * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. - * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this - * promise will be resolved with is the return value of the `fn` function. - * - */ + /** + * @ngdoc service + * @name $timeout + * + * @description + * AngularJS's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch + * block and delegates any exceptions to + * {@link ng.$exceptionHandler $exceptionHandler} service. + * + * The return value of calling `$timeout` is a promise, which will be resolved when + * the delay has passed and the timeout function, if provided, is executed. + * + * To cancel a timeout request, call `$timeout.cancel(promise)`. + * + * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to + * synchronously flush the queue of deferred functions. + * + * If you only want a promise that will be resolved after some specified delay + * then you can call `$timeout` without the `fn` function. + * + * @param {function()=} fn A function, whose execution should be delayed. + * @param {number=} [delay=0] Delay in milliseconds. + * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise + * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. + * @param {...*=} Pass additional parameters to the executed function. + * @returns {Promise} Promise that will be resolved when the timeout is reached. The promise + * will be resolved with the return value of the `fn` function. + * + */ function timeout(fn, delay, invokeApply) { - var deferred = $q.defer(), - promise = deferred.promise, + if (!isFunction(fn)) { + invokeApply = delay; + delay = fn; + fn = noop; + } + + var args = sliceArgs(arguments, 3), skipApply = (isDefined(invokeApply) && !invokeApply), + deferred = (skipApply ? $$q : $q).defer(), + promise = deferred.promise, timeoutId; timeoutId = $browser.defer(function() { try { - deferred.resolve(fn()); - } catch(e) { + deferred.resolve(fn.apply(null, args)); + } catch (e) { deferred.reject(e); $exceptionHandler(e); - } - finally { + } finally { delete deferreds[promise.$$timeoutId]; } if (!skipApply) $rootScope.$apply(); - }, delay); + }, delay, '$timeout'); promise.$$timeoutId = timeoutId; deferreds[timeoutId] = deferred; @@ -14030,25 +21780,37 @@ function $TimeoutProvider() { } - /** - * @ngdoc method - * @name $timeout#cancel - * - * @description - * Cancels a task associated with the `promise`. As a result of this, the promise will be - * resolved with a rejection. - * - * @param {Promise=} promise Promise returned by the `$timeout` function. - * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully - * canceled. - */ + /** + * @ngdoc method + * @name $timeout#cancel + * + * @description + * Cancels a task associated with the `promise`. As a result of this, the promise will be + * resolved with a rejection. + * + * @param {Promise=} promise Promise returned by the `$timeout` function. + * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully + * canceled. + */ timeout.cancel = function(promise) { - if (promise && promise.$$timeoutId in deferreds) { - deferreds[promise.$$timeoutId].reject('canceled'); - delete deferreds[promise.$$timeoutId]; - return $browser.defer.cancel(promise.$$timeoutId); + if (!promise) return false; + + if (!promise.hasOwnProperty('$$timeoutId')) { + throw $timeoutMinErr('badprom', + '`$timeout.cancel()` called with a promise that was not generated by `$timeout()`.'); } - return false; + + if (!deferreds.hasOwnProperty(promise.$$timeoutId)) return false; + + var id = promise.$$timeoutId; + var deferred = deferreds[id]; + + // Timeout cancels should not report an unhandled promise. + markQExceptionHandled(deferred.promise); + deferred.reject('canceled'); + delete deferreds[id]; + + return $browser.defer.cancel(id); }; return timeout; @@ -14062,9 +21824,16 @@ function $TimeoutProvider() { // doesn't know about mocked locations and resolves URLs to the real document - which is // exactly the behavior needed here. There is little value is mocking these out for this // service. -var urlParsingNode = document.createElement("a"); -var originUrl = urlResolve(window.location.href, true); +var urlParsingNode = window.document.createElement('a'); +var originUrl = urlResolve(window.location.href); +var baseUrlParsingNode; +urlParsingNode.href = 'http://[::1]'; + +// Support: IE 9-11 only, Edge 16-17 only (fixed in 18 Preview) +// IE/Edge don't wrap IPv6 addresses' hostnames in square brackets +// when parsed out of an anchor element. +var ipv6InBrackets = urlParsingNode.hostname === '[::1]'; /** * @@ -14075,25 +21844,18 @@ var originUrl = urlResolve(window.location.href, true); * URL will be resolved into an absolute URL in the context of the application document. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related * properties are all populated to reflect the normalized URL. This approach has wide - * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See + * compatibility - Safari 1+, Mozilla 1+ etc. See * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html * * Implementation Notes for IE * --------------------------- - * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other + * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other * browsers. However, the parsed components will not be set if the URL assigned did not specify * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We * work around that by performing the parsing in a 2nd step by taking a previously normalized * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the * properties such as protocol, hostname, port, etc. * - * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one - * uses the inner HTML approach to assign the URL as part of an HTML snippet - - * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL. - * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception. - * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that - * method and IE < 8 is unsupported. - * * References: * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html @@ -14101,43 +21863,52 @@ var originUrl = urlResolve(window.location.href, true); * https://github.com/angular/angular.js/pull/2902 * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ * - * @function - * @param {string} url The URL to be parsed. + * @kind function + * @param {string|object} url The URL to be parsed. If `url` is not a string, it will be returned + * unchanged. * @description Normalizes and parses a URL. * @returns {object} Returns the normalized URL as a dictionary. * - * | member name | Description | - * |---------------|----------------| + * | member name | Description | + * |---------------|------------------------------------------------------------------------| * | href | A normalized version of the provided URL if it was not an absolute URL | - * | protocol | The protocol including the trailing colon | + * | protocol | The protocol without the trailing colon | * | host | The host and port (if the port is non-default) of the normalizedUrl | * | search | The search params, minus the question mark | - * | hash | The hash string, minus the hash symbol - * | hostname | The hostname - * | port | The port, without ":" - * | pathname | The pathname, beginning with "/" + * | hash | The hash string, minus the hash symbol | + * | hostname | The hostname | + * | port | The port, without ":" | + * | pathname | The pathname, beginning with "/" | * */ -function urlResolve(url, base) { +function urlResolve(url) { + if (!isString(url)) return url; + var href = url; + // Support: IE 9-11 only if (msie) { // Normalize before parse. Refer Implementation Notes on why this is // done in two steps on IE. - urlParsingNode.setAttribute("href", href); + urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils + var hostname = urlParsingNode.hostname; + + if (!ipv6InBrackets && hostname.indexOf(':') > -1) { + hostname = '[' + hostname + ']'; + } + return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', - hostname: urlParsingNode.hostname, + hostname: hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname @@ -14146,48 +21917,130 @@ function urlResolve(url, base) { } /** - * Parse a request URL and determine whether this is a same-origin request as the application document. + * Parse a request URL and determine whether this is a same-origin request as the application + * document. * * @param {string|object} requestUrl The url of the request as a string that will be resolved * or a parsed URL object. * @returns {boolean} Whether the request is for the same origin as the application document. */ function urlIsSameOrigin(requestUrl) { - var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; - return (parsed.protocol === originUrl.protocol && - parsed.host === originUrl.host); + return urlsAreSameOrigin(requestUrl, originUrl); } /** - * @ngdoc service - * @name $window + * Parse a request URL and determine whether it is same-origin as the current document base URL. * - * @description - * A reference to the browser's `window` object. While `window` - * is globally available in JavaScript, it causes testability problems, because - * it is a global variable. In angular we always refer to it through the - * `$window` service, so it may be overridden, removed or mocked for testing. + * Note: The base URL is usually the same as the document location (`location.href`) but can + * be overriden by using the `` tag. * - * Expressions, like the one defined for the `ngClick` directive in the example - * below, are evaluated with respect to the current scope. Therefore, there is - * no risk of inadvertently coding in a dependency on a global value in such an - * expression. + * @param {string|object} requestUrl The url of the request as a string that will be resolved + * or a parsed URL object. + * @returns {boolean} Whether the URL is same-origin as the document base URL. + */ +function urlIsSameOriginAsBaseUrl(requestUrl) { + return urlsAreSameOrigin(requestUrl, getBaseUrl()); +} + +/** + * Create a function that can check a URL's origin against a list of allowed/trusted origins. + * The current location's origin is implicitly trusted. * - * @example - - - -
- - -
+ * @param {string[]} trustedOriginUrls - A list of URLs (strings), whose origins are trusted. + * + * @returns {Function} - A function that receives a URL (string or parsed URL object) and returns + * whether it is of an allowed origin. + */ +function urlIsAllowedOriginFactory(trustedOriginUrls) { + var parsedAllowedOriginUrls = [originUrl].concat(trustedOriginUrls.map(urlResolve)); + + /** + * Check whether the specified URL (string or parsed URL object) has an origin that is allowed + * based on a list of trusted-origin URLs. The current location's origin is implicitly + * trusted. + * + * @param {string|Object} requestUrl - The URL to be checked (provided as a string that will be + * resolved or a parsed URL object). + * + * @returns {boolean} - Whether the specified URL is of an allowed origin. + */ + return function urlIsAllowedOrigin(requestUrl) { + var parsedUrl = urlResolve(requestUrl); + return parsedAllowedOriginUrls.some(urlsAreSameOrigin.bind(null, parsedUrl)); + }; +} + +/** + * Determine if two URLs share the same origin. + * + * @param {string|Object} url1 - First URL to compare as a string or a normalized URL in the form of + * a dictionary object returned by `urlResolve()`. + * @param {string|object} url2 - Second URL to compare as a string or a normalized URL in the form + * of a dictionary object returned by `urlResolve()`. + * + * @returns {boolean} - True if both URLs have the same origin, and false otherwise. + */ +function urlsAreSameOrigin(url1, url2) { + url1 = urlResolve(url1); + url2 = urlResolve(url2); + + return (url1.protocol === url2.protocol && + url1.host === url2.host); +} + +/** + * Returns the current document base URL. + * @returns {string} + */ +function getBaseUrl() { + if (window.document.baseURI) { + return window.document.baseURI; + } + + // `document.baseURI` is available everywhere except IE + if (!baseUrlParsingNode) { + baseUrlParsingNode = window.document.createElement('a'); + baseUrlParsingNode.href = '.'; + + // Work-around for IE bug described in Implementation Notes. The fix in `urlResolve()` is not + // suitable here because we need to track changes to the base URL. + baseUrlParsingNode = baseUrlParsingNode.cloneNode(false); + } + return baseUrlParsingNode.href; +} + +/** + * @ngdoc service + * @name $window + * @this + * + * @description + * A reference to the browser's `window` object. While `window` + * is globally available in JavaScript, it causes testability problems, because + * it is a global variable. In AngularJS we always refer to it through the + * `$window` service, so it may be overridden, removed or mocked for testing. + * + * Expressions, like the one defined for the `ngClick` directive in the example + * below, are evaluated with respect to the current scope. Therefore, there is + * no risk of inadvertently coding in a dependency on a global value in such an + * expression. + * + * @example + + + +
+ + +
it('should display the greeting in the input box', function() { @@ -14198,10 +22051,85 @@ function urlIsSameOrigin(requestUrl) {
*/ -function $WindowProvider(){ +function $WindowProvider() { this.$get = valueFn(window); } +/** + * @name $$cookieReader + * @requires $document + * + * @description + * This is a private service for reading cookies used by $http and ngCookies + * + * @return {Object} a key/value map of the current cookies + */ +function $$CookieReader($document) { + var rawDocument = $document[0] || {}; + var lastCookies = {}; + var lastCookieString = ''; + + function safeGetCookie(rawDocument) { + try { + return rawDocument.cookie || ''; + } catch (e) { + return ''; + } + } + + function safeDecodeURIComponent(str) { + try { + return decodeURIComponent(str); + } catch (e) { + return str; + } + } + + return function() { + var cookieArray, cookie, i, index, name; + var currentCookieString = safeGetCookie(rawDocument); + + if (currentCookieString !== lastCookieString) { + lastCookieString = currentCookieString; + cookieArray = lastCookieString.split('; '); + lastCookies = {}; + + for (i = 0; i < cookieArray.length; i++) { + cookie = cookieArray[i]; + index = cookie.indexOf('='); + if (index > 0) { //ignore nameless cookies + name = safeDecodeURIComponent(cookie.substring(0, index)); + // the first value that is seen for a cookie is the most + // specific one. values for the same cookie name that + // follow are for less specific paths. + if (isUndefined(lastCookies[name])) { + lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1)); + } + } + } + } + return lastCookies; + }; +} + +$$CookieReader.$inject = ['$document']; + +/** @this */ +function $$CookieReaderProvider() { + this.$get = $$CookieReader; +} + +/* global currencyFilter: true, + dateFilter: true, + filterFilter: true, + jsonFilter: true, + limitToFilter: true, + lowercaseFilter: true, + numberFilter: true, + orderByFilter: true, + uppercaseFilter: true, + */ + /** * @ngdoc provider * @name $filterProvider @@ -14211,6 +22139,13 @@ function $WindowProvider(){ * Dependency Injected. To achieve this a filter definition consists of a factory function which is * annotated with dependencies and is responsible for creating a filter function. * + *
+ * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`. + * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace + * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores + * (`myapp_subsection_filterx`). + *
+ * * ```js * // Filter registration * function MyModule($provide, $filterProvider) { @@ -14248,48 +22183,70 @@ function $WindowProvider(){ * ``` * * - * For more information about how angular filters work, and how to create your own filters, see - * {@link guide/filter Filters} in the Angular Developer Guide. - */ -/** - * @ngdoc method - * @name $filterProvider#register - * @description - * Register filter factory function. - * - * @param {String} name Name of the filter. - * @param {Function} fn The filter factory function which is injectable. + * For more information about how AngularJS filters work, and how to create your own filters, see + * {@link guide/filter Filters} in the AngularJS Developer Guide. */ - /** * @ngdoc service * @name $filter - * @function + * @kind function * @description * Filters are used for formatting data displayed to the user. * + * They can be used in view templates, controllers or services. AngularJS comes + * with a collection of [built-in filters](api/ng/filter), but it is easy to + * define your own as well. + * * The general syntax in templates is as follows: * - * {{ expression [| filter_name[:parameter_value] ... ] }} + * ```html + * {{ expression [| filter_name[:parameter_value] ... ] }} + * ``` * * @param {String} name Name of the filter function to retrieve * @return {Function} the filter function - */ + * @example + + +
+

{{ originalText }}

+

{{ filteredText }}

+
+
+ + + angular.module('filterExample', []) + .controller('MainCtrl', function($scope, $filter) { + $scope.originalText = 'hello'; + $scope.filteredText = $filter('uppercase')($scope.originalText); + }); + +
+ */ $FilterProvider.$inject = ['$provide']; +/** @this */ function $FilterProvider($provide) { var suffix = 'Filter'; /** * @ngdoc method - * @name $controllerProvider#register + * @name $filterProvider#register * @param {string|Object} name Name of the filter function, or an object map of filters where * the keys are the filter names and the values are the filter factories. + * + *
+ * **Note:** Filter names must be valid AngularJS {@link expression} identifiers, such as `uppercase` or `orderBy`. + * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace + * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores + * (`myapp_subsection_filterx`). + *
+ * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map * of the registered filter instances. */ function register(name, factory) { - if(isObject(name)) { + if (isObject(name)) { var filters = {}; forEach(name, function(filter, key) { filters[key] = register(key, filter); @@ -14318,7 +22275,7 @@ function $FilterProvider($provide) { lowercaseFilter: false, numberFilter: false, orderByFilter: false, - uppercaseFilter: false, + uppercaseFilter: false */ register('currency', currencyFilter); @@ -14335,50 +22292,73 @@ function $FilterProvider($provide) { /** * @ngdoc filter * @name filter - * @function + * @kind function * * @description * Selects a subset of items from `array` and returns it as a new array. * * @param {Array} array The source array. + *
+ * **Note**: If the array contains objects that reference themselves, filtering is not possible. + *
* @param {string|Object|function()} expression The predicate to be used for selecting items from * `array`. * * Can be one of: * - * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against - * the contents of the `array`. All strings or objects with string properties in `array` that contain this string - * will be returned. The predicate can be negated by prefixing the string with `!`. + * - `string`: The string is used for matching against the contents of the `array`. All strings or + * objects with string properties in `array` that match this string will be returned. This also + * applies to nested object properties. + * The predicate can be negated by prefixing the string with `!`. * * - `Object`: A pattern object can be used to filter specific properties on objects contained * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items * which have property `name` containing "M" and property `phone` containing "1". A special - * property name `$` can be used (as in `{$:"text"}`) to accept a match against any - * property of the object. That's equivalent to the simple substring match with a `string` - * as described above. + * property name (`$` by default) can be used (e.g. as in `{$: "text"}`) to accept a match + * against any property of the object or its nested object properties. That's equivalent to the + * simple substring match with a `string` as described above. The special property name can be + * overwritten, using the `anyPropertyKey` parameter. + * The predicate can be negated by prefixing the string with `!`. + * For example `{name: "!M"}` predicate will return an array of items which have property `name` + * not containing "M". + * + * Note that a named property will match properties on the same level only, while the special + * `$` property will match properties on the same level or deeper. E.g. an array item like + * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but + * **will** be matched by `{$: 'John'}`. + * + * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters. + * The function is called for each element of the array, with the element, its index, and + * the entire array itself as arguments. + * + * The final result is an array of those elements that the predicate returned true for. + * + * @param {function(actual, expected)|true|false} [comparator] Comparator which is used in + * determining if values retrieved using `expression` (when it is not a function) should be + * considered a match based on the expected value (from the filter expression) and actual + * value (from the object in the array). + * + * Can be one of: * - * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is - * called for each element of `array`. The final result is an array of those elements that - * the predicate returned true for. + * - `function(actual, expected)`: + * The function will be given the object value and the predicate value to compare and + * should return true if both values should be considered equal. * - * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in - * determining if the expected value (from the filter expression) and actual value (from - * the object in the array) should be considered a match. + * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`. + * This is essentially strict comparison of expected and actual. * - * Can be one of: + * - `false`: A short hand for a function which will look for a substring match in a case + * insensitive way. Primitive values are converted to strings. Objects are not compared against + * primitives, unless they have a custom `toString` method (e.g. `Date` objects). * - * - `function(actual, expected)`: - * The function will be given the object value and the predicate value to compare and - * should return true if the item should be included in filtered result. * - * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`. - * this is essentially strict comparison of expected and actual. + * Defaults to `false`. * - * - `false|undefined`: A short hand for a function which will look for a substring match in case - * insensitive way. + * @param {string} [anyPropertyKey] The special property name that matches against any property. + * By default `$`. * * @example - +
- Search: + @@ -14396,10 +22376,10 @@ function $FilterProvider($provide) {
NamePhone

- Any:
- Name only
- Phone only
- Equality
+
+
+
+
@@ -14445,116 +22425,145 @@ function $FilterProvider($provide) { */ -function filterFilter() { - return function(array, expression, comparator) { - if (!isArray(array)) return array; - - var comparatorType = typeof(comparator), - predicates = []; - - predicates.check = function(value) { - for (var j = 0; j < predicates.length; j++) { - if(!predicates[j](value)) { - return false; - } - } - return true; - }; - if (comparatorType !== 'function') { - if (comparatorType === 'boolean' && comparator) { - comparator = function(obj, text) { - return angular.equals(obj, text); - }; +function filterFilter() { + return function(array, expression, comparator, anyPropertyKey) { + if (!isArrayLike(array)) { + if (array == null) { + return array; } else { - comparator = function(obj, text) { - if (obj && text && typeof obj === 'object' && typeof text === 'object') { - for (var objKey in obj) { - if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) && - comparator(obj[objKey], text[objKey])) { - return true; - } - } - return false; - } - text = (''+text).toLowerCase(); - return (''+obj).toLowerCase().indexOf(text) > -1; - }; + throw minErr('filter')('notarray', 'Expected array but received: {0}', array); } } - var search = function(obj, text){ - if (typeof text == 'string' && text.charAt(0) === '!') { - return !search(obj, text.substr(1)); - } - switch (typeof obj) { - case "boolean": - case "number": - case "string": - return comparator(obj, text); - case "object": - switch (typeof text) { - case "object": - return comparator(obj, text); - default: - for ( var objKey in obj) { - if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) { - return true; - } - } - break; - } - return false; - case "array": - for ( var i = 0; i < obj.length; i++) { - if (search(obj[i], text)) { - return true; - } - } - return false; - default: - return false; - } - }; - switch (typeof expression) { - case "boolean": - case "number": - case "string": - // Set up expression object and fall through - expression = {$:expression}; - // jshint -W086 - case "object": - // jshint +W086 - for (var key in expression) { - (function(path) { - if (typeof expression[path] == 'undefined') return; - predicates.push(function(value) { - return search(path == '$' ? value : (value && value[path]), expression[path]); - }); - })(key); - } - break; + anyPropertyKey = anyPropertyKey || '$'; + var expressionType = getTypeForFilter(expression); + var predicateFn; + var matchAgainstAnyProp; + + switch (expressionType) { case 'function': - predicates.push(expression); + predicateFn = expression; + break; + case 'boolean': + case 'null': + case 'number': + case 'string': + matchAgainstAnyProp = true; + // falls through + case 'object': + predicateFn = createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp); break; default: return array; } - var filtered = []; - for ( var j = 0; j < array.length; j++) { - var value = array[j]; - if (predicates.check(value)) { - filtered.push(value); + + return Array.prototype.filter.call(array, predicateFn); + }; +} + +// Helper functions for `filterFilter` +function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) { + var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression); + var predicateFn; + + if (comparator === true) { + comparator = equals; + } else if (!isFunction(comparator)) { + comparator = function(actual, expected) { + if (isUndefined(actual)) { + // No substring matching against `undefined` + return false; + } + if ((actual === null) || (expected === null)) { + // No substring matching against `null`; only match against `null` + return actual === expected; } + if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) { + // Should not compare primitives against objects, unless they have custom `toString` method + return false; + } + + actual = lowercase('' + actual); + expected = lowercase('' + expected); + return actual.indexOf(expected) !== -1; + }; + } + + predicateFn = function(item) { + if (shouldMatchPrimitives && !isObject(item)) { + return deepCompare(item, expression[anyPropertyKey], comparator, anyPropertyKey, false); } - return filtered; + return deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp); }; + + return predicateFn; +} + +function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) { + var actualType = getTypeForFilter(actual); + var expectedType = getTypeForFilter(expected); + + if ((expectedType === 'string') && (expected.charAt(0) === '!')) { + return !deepCompare(actual, expected.substring(1), comparator, anyPropertyKey, matchAgainstAnyProp); + } else if (isArray(actual)) { + // In case `actual` is an array, consider it a match + // if ANY of it's items matches `expected` + return actual.some(function(item) { + return deepCompare(item, expected, comparator, anyPropertyKey, matchAgainstAnyProp); + }); + } + + switch (actualType) { + case 'object': + var key; + if (matchAgainstAnyProp) { + for (key in actual) { + // Under certain, rare, circumstances, key may not be a string and `charAt` will be undefined + // See: https://github.com/angular/angular.js/issues/15644 + if (key.charAt && (key.charAt(0) !== '$') && + deepCompare(actual[key], expected, comparator, anyPropertyKey, true)) { + return true; + } + } + return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, anyPropertyKey, false); + } else if (expectedType === 'object') { + for (key in expected) { + var expectedVal = expected[key]; + if (isFunction(expectedVal) || isUndefined(expectedVal)) { + continue; + } + + var matchAnyProperty = key === anyPropertyKey; + var actualVal = matchAnyProperty ? actual : actual[key]; + if (!deepCompare(actualVal, expectedVal, comparator, anyPropertyKey, matchAnyProperty, matchAnyProperty)) { + return false; + } + } + return true; + } else { + return comparator(actual, expected); + } + case 'function': + return false; + default: + return comparator(actual, expected); + } +} + +// Used for easily differentiating between `null` and actual `object` +function getTypeForFilter(val) { + return (val === null) ? 'null' : typeof val; } +var MAX_DIGITS = 22; +var DECIMAL_SEP = '.'; +var ZERO_CHAR = '0'; + /** * @ngdoc filter * @name currency - * @function + * @kind function * * @description * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default @@ -14562,38 +22571,43 @@ function filterFilter() { * * @param {number} amount Input to filter. * @param {string=} symbol Currency symbol or identifier to be displayed. + * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale * @returns {string} Formatted number. * * * @example - + -
-
+
+
default currency symbol ($): {{amount | currency}}
- custom currency identifier (USD$): {{amount | currency:"USD$"}} + custom currency identifier (USD$): {{amount | currency:"USD$"}}
+ no fractions (0): {{amount | currency:"USD$":0}}
it('should init with 1234.56', function() { expect(element(by.id('currency-default')).getText()).toBe('$1,234.56'); - expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56'); + expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56'); + expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235'); }); it('should update', function() { - if (browser.params.browser == 'safari') { + if (browser.params.browser === 'safari') { // Safari does not understand the minus key. See // https://github.com/angular/protractor/issues/481 return; } element(by.model('amount')).clear(); element(by.model('amount')).sendKeys('-1234'); - expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)'); - expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)'); + expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00'); + expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00'); + expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234'); }); @@ -14601,39 +22615,58 @@ function filterFilter() { currencyFilter.$inject = ['$locale']; function currencyFilter($locale) { var formats = $locale.NUMBER_FORMATS; - return function(amount, currencySymbol){ - if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; - return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). - replace(/\u00A4/g, currencySymbol); + return function(amount, currencySymbol, fractionSize) { + if (isUndefined(currencySymbol)) { + currencySymbol = formats.CURRENCY_SYM; + } + + if (isUndefined(fractionSize)) { + fractionSize = formats.PATTERNS[1].maxFrac; + } + + // If the currency symbol is empty, trim whitespace around the symbol + var currencySymbolRe = !currencySymbol ? /\s*\u00A4\s*/g : /\u00A4/g; + + // if null or undefined pass it through + return (amount == null) + ? amount + : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize). + replace(currencySymbolRe, currencySymbol); }; } /** * @ngdoc filter * @name number - * @function + * @kind function * * @description * Formats a number as text. * + * If the input is null or undefined, it will just be returned. + * If the input is infinite (Infinity or -Infinity), the Infinity symbol '∞' or '-∞' is returned, respectively. * If the input is not a number an empty string is returned. * + * * @param {number|string} number Number to format. * @param {(number|string)=} fractionSize Number of decimal places to round the number to. * If this is not provided then the fraction size is computed from the current locale's number * formatting pattern. In the case of the default locale, it will be 3. - * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit. + * @returns {string} Number rounded to `fractionSize` appropriately formatted based on the current + * locale (e.g., in the en_US locale it will have "." as the decimal separator and + * include "," group separators after each third digit). * * @example - + -
- Enter number:
+
+
Default formatting: {{val | number}}
No fractions: {{val | number:0}}
Negative number: {{-val | number:4}} @@ -14656,129 +22689,272 @@ function currencyFilter($locale) { */ - - numberFilter.$inject = ['$locale']; function numberFilter($locale) { var formats = $locale.NUMBER_FORMATS; return function(number, fractionSize) { - return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, - fractionSize); + + // if null or undefined pass it through + return (number == null) + ? number + : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, + fractionSize); }; } -var DECIMAL_SEP = '.'; -function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { - if (number == null || !isFinite(number) || isObject(number)) return ''; - - var isNegative = number < 0; - number = Math.abs(number); - var numStr = number + '', - formatedText = '', - parts = []; - - var hasExponent = false; - if (numStr.indexOf('e') !== -1) { - var match = numStr.match(/([\d\.]+)e(-?)(\d+)/); - if (match && match[2] == '-' && match[3] > fractionSize + 1) { - numStr = '0'; - } else { - formatedText = numStr; - hasExponent = true; - } +/** + * Parse a number (as a string) into three components that can be used + * for formatting the number. + * + * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/) + * + * @param {string} numStr The number to parse + * @return {object} An object describing this number, containing the following keys: + * - d : an array of digits containing leading zeros as necessary + * - i : the number of the digits in `d` that are to the left of the decimal point + * - e : the exponent for numbers that would need more than `MAX_DIGITS` digits in `d` + * + */ +function parse(numStr) { + var exponent = 0, digits, numberOfIntegerDigits; + var i, j, zeros; + + // Decimal point? + if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) { + numStr = numStr.replace(DECIMAL_SEP, ''); + } + + // Exponential form? + if ((i = numStr.search(/e/i)) > 0) { + // Work out the exponent. + if (numberOfIntegerDigits < 0) numberOfIntegerDigits = i; + numberOfIntegerDigits += +numStr.slice(i + 1); + numStr = numStr.substring(0, i); + } else if (numberOfIntegerDigits < 0) { + // There was no decimal point or exponent so it is an integer. + numberOfIntegerDigits = numStr.length; } - if (!hasExponent) { - var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; + // Count the number of leading zeros. + for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ } - // determine fractionSize if it is not specified - if (isUndefined(fractionSize)) { - fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); + if (i === (zeros = numStr.length)) { + // The digits are all zero. + digits = [0]; + numberOfIntegerDigits = 1; + } else { + // Count the number of trailing zeros + zeros--; + while (numStr.charAt(zeros) === ZERO_CHAR) zeros--; + + // Trailing zeros are insignificant so ignore them + numberOfIntegerDigits -= i; + digits = []; + // Convert string to array of digits without leading/trailing zeros. + for (j = 0; i <= zeros; i++, j++) { + digits[j] = +numStr.charAt(i); } + } + + // If the number overflows the maximum allowed digits then use an exponent. + if (numberOfIntegerDigits > MAX_DIGITS) { + digits = digits.splice(0, MAX_DIGITS - 1); + exponent = numberOfIntegerDigits - 1; + numberOfIntegerDigits = 1; + } - var pow = Math.pow(10, fractionSize); - number = Math.round(number * pow) / pow; - var fraction = ('' + number).split(DECIMAL_SEP); - var whole = fraction[0]; - fraction = fraction[1] || ''; + return { d: digits, e: exponent, i: numberOfIntegerDigits }; +} - var i, pos = 0, - lgroup = pattern.lgSize, - group = pattern.gSize; +/** + * Round the parsed number to the specified number of decimal places + * This function changed the parsedNumber in-place + */ +function roundNumber(parsedNumber, fractionSize, minFrac, maxFrac) { + var digits = parsedNumber.d; + var fractionLen = digits.length - parsedNumber.i; - if (whole.length >= (lgroup + group)) { - pos = whole.length - lgroup; - for (i = 0; i < pos; i++) { - if ((pos - i)%group === 0 && i !== 0) { - formatedText += groupSep; - } - formatedText += whole.charAt(i); + // determine fractionSize if it is not specified; `+fractionSize` converts it to a number + fractionSize = (isUndefined(fractionSize)) ? Math.min(Math.max(minFrac, fractionLen), maxFrac) : +fractionSize; + + // The index of the digit to where rounding is to occur + var roundAt = fractionSize + parsedNumber.i; + var digit = digits[roundAt]; + + if (roundAt > 0) { + // Drop fractional digits beyond `roundAt` + digits.splice(Math.max(parsedNumber.i, roundAt)); + + // Set non-fractional digits beyond `roundAt` to 0 + for (var j = roundAt; j < digits.length; j++) { + digits[j] = 0; } + } else { + // We rounded to zero so reset the parsedNumber + fractionLen = Math.max(0, fractionLen); + parsedNumber.i = 1; + digits.length = Math.max(1, roundAt = fractionSize + 1); + digits[0] = 0; + for (var i = 1; i < roundAt; i++) digits[i] = 0; } - for (i = pos; i < whole.length; i++) { - if ((whole.length - i)%lgroup === 0 && i !== 0) { - formatedText += groupSep; + if (digit >= 5) { + if (roundAt - 1 < 0) { + for (var k = 0; k > roundAt; k--) { + digits.unshift(0); + parsedNumber.i++; + } + digits.unshift(1); + parsedNumber.i++; + } else { + digits[roundAt - 1]++; } - formatedText += whole.charAt(i); } - // format fraction part. - while(fraction.length < fractionSize) { - fraction += '0'; + // Pad out with zeros to get the required fraction length + for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0); + + + // Do any carrying, e.g. a digit was rounded up to 10 + var carry = digits.reduceRight(function(carry, d, i, digits) { + d = d + carry; + digits[i] = d % 10; + return Math.floor(d / 10); + }, 0); + if (carry) { + digits.unshift(carry); + parsedNumber.i++; } +} + +/** + * Format a number into a string + * @param {number} number The number to format + * @param {{ + * minFrac, // the minimum number of digits required in the fraction part of the number + * maxFrac, // the maximum number of digits required in the fraction part of the number + * gSize, // number of digits in each group of separated digits + * lgSize, // number of digits in the last group of digits before the decimal separator + * negPre, // the string to go in front of a negative number (e.g. `-` or `(`)) + * posPre, // the string to go in front of a positive number + * negSuf, // the string to go after a negative number (e.g. `)`) + * posSuf // the string to go after a positive number + * }} pattern + * @param {string} groupSep The string to separate groups of number (e.g. `,`) + * @param {string} decimalSep The string to act as the decimal separator (e.g. `.`) + * @param {[type]} fractionSize The size of the fractional part of the number + * @return {string} The number formatted as a string + */ +function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { + + if (!(isString(number) || isNumber(number)) || isNaN(number)) return ''; - if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); + var isInfinity = !isFinite(number); + var isZero = false; + var numStr = Math.abs(number) + '', + formattedText = '', + parsedNumber; + + if (isInfinity) { + formattedText = '\u221e'; } else { + parsedNumber = parse(numStr); + + roundNumber(parsedNumber, fractionSize, pattern.minFrac, pattern.maxFrac); - if (fractionSize > 0 && number > -1 && number < 1) { - formatedText = number.toFixed(fractionSize); + var digits = parsedNumber.d; + var integerLen = parsedNumber.i; + var exponent = parsedNumber.e; + var decimals = []; + isZero = digits.reduce(function(isZero, d) { return isZero && !d; }, true); + + // pad zeros for small numbers + while (integerLen < 0) { + digits.unshift(0); + integerLen++; + } + + // extract decimals digits + if (integerLen > 0) { + decimals = digits.splice(integerLen, digits.length); + } else { + decimals = digits; + digits = [0]; + } + + // format the integer digits with grouping separators + var groups = []; + if (digits.length >= pattern.lgSize) { + groups.unshift(digits.splice(-pattern.lgSize, digits.length).join('')); + } + while (digits.length > pattern.gSize) { + groups.unshift(digits.splice(-pattern.gSize, digits.length).join('')); + } + if (digits.length) { + groups.unshift(digits.join('')); + } + formattedText = groups.join(groupSep); + + // append the decimal digits + if (decimals.length) { + formattedText += decimalSep + decimals.join(''); } - } - parts.push(isNegative ? pattern.negPre : pattern.posPre); - parts.push(formatedText); - parts.push(isNegative ? pattern.negSuf : pattern.posSuf); - return parts.join(''); + if (exponent) { + formattedText += 'e+' + exponent; + } + } + if (number < 0 && !isZero) { + return pattern.negPre + formattedText + pattern.negSuf; + } else { + return pattern.posPre + formattedText + pattern.posSuf; + } } -function padNumber(num, digits, trim) { +function padNumber(num, digits, trim, negWrap) { var neg = ''; - if (num < 0) { - neg = '-'; - num = -num; + if (num < 0 || (negWrap && num <= 0)) { + if (negWrap) { + num = -num + 1; + } else { + num = -num; + neg = '-'; + } } num = '' + num; - while(num.length < digits) num = '0' + num; - if (trim) + while (num.length < digits) num = ZERO_CHAR + num; + if (trim) { num = num.substr(num.length - digits); + } return neg + num; } -function dateGetter(name, size, offset, trim) { +function dateGetter(name, size, offset, trim, negWrap) { offset = offset || 0; return function(date) { var value = date['get' + name](); - if (offset > 0 || value > -offset) + if (offset > 0 || value > -offset) { value += offset; - if (value === 0 && offset == -12 ) value = 12; - return padNumber(value, size, trim); + } + if (value === 0 && offset === -12) value = 12; + return padNumber(value, size, trim, negWrap); }; } -function dateStrGetter(name, shortForm) { +function dateStrGetter(name, shortForm, standAlone) { return function(date, formats) { var value = date['get' + name](); - var get = uppercase(shortForm ? ('SHORT' + name) : name); + var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : ''); + var get = uppercase(propPrefix + name); return formats[get][value]; }; } -function timeZoneGetter(date) { - var zone = -1 * date.getTimezoneOffset(); - var paddedZone = (zone >= 0) ? "+" : ""; +function timeZoneGetter(date, formats, offset) { + var zone = -1 * offset; + var paddedZone = (zone >= 0) ? '+' : ''; paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + padNumber(Math.abs(zone % 60), 2); @@ -14786,18 +22962,53 @@ function timeZoneGetter(date) { return paddedZone; } +function getFirstThursdayOfYear(year) { + // 0 = index of January + var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay(); + // 4 = index of Thursday (+1 to account for 1st = 5) + // 11 = index of *next* Thursday (+1 account for 1st = 12) + return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst); +} + +function getThursdayThisWeek(datetime) { + return new Date(datetime.getFullYear(), datetime.getMonth(), + // 4 = index of Thursday + datetime.getDate() + (4 - datetime.getDay())); +} + +function weekGetter(size) { + return function(date) { + var firstThurs = getFirstThursdayOfYear(date.getFullYear()), + thisThurs = getThursdayThisWeek(date); + + var diff = +thisThurs - +firstThurs, + result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week + + return padNumber(result, size); + }; +} + function ampmGetter(date, formats) { return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; } -var DATE_FORMATS = { - yyyy: dateGetter('FullYear', 4), - yy: dateGetter('FullYear', 2, 0, true), - y: dateGetter('FullYear', 1), +function eraGetter(date, formats) { + return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1]; +} + +function longEraGetter(date, formats) { + return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1]; +} + +var DATE_FORMATS = { + yyyy: dateGetter('FullYear', 4, 0, false, true), + yy: dateGetter('FullYear', 2, 0, true, true), + y: dateGetter('FullYear', 1, 0, false, true), MMMM: dateStrGetter('Month'), MMM: dateStrGetter('Month', true), MM: dateGetter('Month', 2, 1), M: dateGetter('Month', 1, 1), + LLLL: dateStrGetter('Month', false, true), dd: dateGetter('Date', 2), d: dateGetter('Date', 1), HH: dateGetter('Hours', 2), @@ -14814,16 +23025,22 @@ var DATE_FORMATS = { EEEE: dateStrGetter('Day'), EEE: dateStrGetter('Day', true), a: ampmGetter, - Z: timeZoneGetter + Z: timeZoneGetter, + ww: weekGetter(2), + w: weekGetter(1), + G: eraGetter, + GG: eraGetter, + GGG: eraGetter, + GGGG: longEraGetter }; -var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/, - NUMBER_STRING = /^\-?\d+$/; +var DATE_FORMATS_SPLIT = /((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))([\s\S]*)/, + NUMBER_STRING = /^-?\d+$/; /** * @ngdoc filter * @name date - * @function + * @kind function * * @description * Formats `date` to a string based on the requested `format`. @@ -14837,50 +23054,61 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+ * * `'MMM'`: Month in year (Jan-Dec) * * `'MM'`: Month in year, padded (01-12) * * `'M'`: Month in year (1-12) + * * `'LLLL'`: Stand-alone month in year (January-December) * * `'dd'`: Day in month, padded (01-31) * * `'d'`: Day in month (1-31) * * `'EEEE'`: Day in Week,(Sunday-Saturday) * * `'EEE'`: Day in Week, (Sun-Sat) * * `'HH'`: Hour in day, padded (00-23) * * `'H'`: Hour in day (0-23) - * * `'hh'`: Hour in am/pm, padded (01-12) - * * `'h'`: Hour in am/pm, (1-12) + * * `'hh'`: Hour in AM/PM, padded (01-12) + * * `'h'`: Hour in AM/PM, (1-12) * * `'mm'`: Minute in hour, padded (00-59) * * `'m'`: Minute in hour (0-59) * * `'ss'`: Second in minute, padded (00-59) * * `'s'`: Second in minute (0-59) - * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999) - * * `'a'`: am/pm marker + * * `'sss'`: Millisecond in second, padded (000-999) + * * `'a'`: AM/PM marker * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200) + * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year + * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year + * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD') + * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini') * * `format` string can also be one of the following predefined * {@link guide/i18n localizable formats}: * * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale - * (e.g. Sep 3, 2010 12:05:08 pm) - * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm) - * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale + * (e.g. Sep 3, 2010 12:05:08 PM) + * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM) + * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale * (e.g. Friday, September 3, 2010) * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010) * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010) * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10) - * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm) - * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm) + * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM) + * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM) * - * `format` string can contain literal values. These need to be quoted with single quotes (e.g. - * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence + * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g. + * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence * (e.g. `"h 'o''clock'"`). * + * Any other characters in the `format` string will be output as-is. + * * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or - * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its + * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is * specified in the string input, the time is considered to be in the local timezone. * @param {string=} format Formatting rules (see Description). If not specified, * `mediumDate` is used. + * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the + * continental US time zone abbreviations, but for general use, use a time zone offset, for + * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian) + * If not specified, the timezone of the browser will be used. * @returns {string} Formatted string or the input if input is not recognized as date/millis. * * @example - + {{1288323623006 | date:'medium'}}: {{1288323623006 | date:'medium'}}
@@ -14888,15 +23116,19 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+ {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}
{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}: {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}
+ {{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}: + {{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}
it('should format date', function() { expect(element(by.binding("1288323623006 | date:'medium'")).getText()). toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/); expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()). - toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/); + toMatch(/2010-10-2\d \d{2}:\d{2}:\d{2} (-|\+)?\d{4}/); expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()). toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/); + expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()). + toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/); });
@@ -14909,7 +23141,7 @@ function dateFilter($locale) { // 1 2 3 4 5 6 7 8 9 10 11 function jsonStringToDate(string) { var match; - if (match = string.match(R_ISO8601_STR)) { + if ((match = string.match(R_ISO8601_STR))) { var date = new Date(0), tzHour = 0, tzMin = 0, @@ -14917,14 +23149,14 @@ function dateFilter($locale) { timeSetter = match[8] ? date.setUTCHours : date.setHours; if (match[9]) { - tzHour = int(match[9] + match[10]); - tzMin = int(match[9] + match[11]); - } - dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3])); - var h = int(match[4]||0) - tzHour; - var m = int(match[5]||0) - tzMin; - var s = int(match[6]||0); - var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000); + tzHour = toInt(match[9] + match[10]); + tzMin = toInt(match[9] + match[11]); + } + dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3])); + var h = toInt(match[4] || 0) - tzHour; + var m = toInt(match[5] || 0) - tzMin; + var s = toInt(match[6] || 0); + var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000); timeSetter.call(date, h, m, s, ms); return date; } @@ -14932,7 +23164,7 @@ function dateFilter($locale) { } - return function(date, format) { + return function(date, format, timezone) { var text = '', parts = [], fn, match; @@ -14940,22 +23172,18 @@ function dateFilter($locale) { format = format || 'mediumDate'; format = $locale.DATETIME_FORMATS[format] || format; if (isString(date)) { - if (NUMBER_STRING.test(date)) { - date = int(date); - } else { - date = jsonStringToDate(date); - } + date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date); } if (isNumber(date)) { date = new Date(date); } - if (!isDate(date)) { + if (!isDate(date) || !isFinite(date.getTime())) { return date; } - while(format) { + while (format) { match = DATE_FORMATS_SPLIT.exec(format); if (match) { parts = concat(parts, match, 1); @@ -14966,10 +23194,15 @@ function dateFilter($locale) { } } - forEach(parts, function(value){ + var dateTimezoneOffset = date.getTimezoneOffset(); + if (timezone) { + dateTimezoneOffset = timezoneToOffset(timezone, dateTimezoneOffset); + date = convertTimezoneToLocal(date, timezone, true); + } + forEach(parts, function(value) { fn = DATE_FORMATS[value]; - text += fn ? fn(date, $locale.DATETIME_FORMATS) - : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); + text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset) + : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\''); }); return text; @@ -14980,7 +23213,7 @@ function dateFilter($locale) { /** * @ngdoc filter * @name json - * @function + * @kind function * * @description * Allows you to convert a JavaScript object into JSON string. @@ -14989,25 +23222,31 @@ function dateFilter($locale) { * the binding is automatically converted to JSON. * * @param {*} object Any JavaScript object (including arrays and primitive types) to filter. + * @param {number=} spacing The number of spaces to use per indentation, defaults to 2. * @returns {string} JSON string. * * * @example - + -
{{ {'name':'value'} | json }}
+
{{ {'name':'value'} | json }}
+
{{ {'name':'value'} | json:4 }}
it('should jsonify filtered objects', function() { - expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/); + expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n {2}"name": ?"value"\n}/); + expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n {4}"name": ?"value"\n}/); });
* */ function jsonFilter() { - return function(object) { - return toJson(object, true); + return function(object, spacing) { + if (isUndefined(spacing)) { + spacing = 2; + } + return toJson(object, spacing); }; } @@ -15015,9 +23254,12 @@ function jsonFilter() { /** * @ngdoc filter * @name lowercase - * @function + * @kind function * @description * Converts string to lowercase. + * + * See the {@link ng.uppercase uppercase filter documentation} for a functionally identical example. + * * @see angular.lowercase */ var lowercaseFilter = valueFn(lowercase); @@ -15026,173 +23268,518 @@ var lowercaseFilter = valueFn(lowercase); /** * @ngdoc filter * @name uppercase - * @function + * @kind function * @description * Converts string to uppercase. - * @see angular.uppercase + * @example + + + +
+ +

{{title}}

+ +

{{title | uppercase}}

+
+
+
*/ var uppercaseFilter = valueFn(uppercase); /** * @ngdoc filter * @name limitTo - * @function + * @kind function * * @description - * Creates a new array or string containing only a specified number of elements. The elements - * are taken from either the beginning or the end of the source array or string, as specified by - * the value and sign (positive or negative) of `limit`. - * - * @param {Array|string} input Source array or string to be limited. - * @param {string|number} limit The length of the returned array or string. If the `limit` number + * Creates a new array or string containing only a specified number of elements. The elements are + * taken from either the beginning or the end of the source array, string or number, as specified by + * the value and sign (positive or negative) of `limit`. Other array-like objects are also supported + * (e.g. array subclasses, NodeLists, jqLite/jQuery collections etc). If a number is used as input, + * it is converted to a string. + * + * @param {Array|ArrayLike|string|number} input - Array/array-like, string or number to be limited. + * @param {string|number} limit - The length of the returned array or string. If the `limit` number * is positive, `limit` number of items from the beginning of the source array/string are copied. * If the number is negative, `limit` number of items from the end of the source array/string - * are copied. The `limit` will be trimmed if it exceeds `array.length` - * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array - * had less than `limit` elements. + * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined, + * the input will be returned unchanged. + * @param {(string|number)=} begin - Index at which to begin limitation. As a negative index, + * `begin` indicates an offset from the end of `input`. Defaults to `0`. + * @returns {Array|string} A new sub-array or substring of length `limit` or less if the input had + * less than `limit` elements. * * @example - + -
- Limit {{numbers}} to: +
+

Output numbers: {{ numbers | limitTo:numLimit }}

- Limit {{letters}} to: +

Output letters: {{ letters | limitTo:letterLimit }}

+ +

Output long number: {{ longNumber | limitTo:longNumberLimit }}

var numLimitInput = element(by.model('numLimit')); var letterLimitInput = element(by.model('letterLimit')); + var longNumberLimitInput = element(by.model('longNumberLimit')); var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); + var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit')); it('should limit the number array to first three items', function() { expect(numLimitInput.getAttribute('value')).toBe('3'); expect(letterLimitInput.getAttribute('value')).toBe('3'); + expect(longNumberLimitInput.getAttribute('value')).toBe('3'); expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]'); expect(limitedLetters.getText()).toEqual('Output letters: abc'); + expect(limitedLongNumber.getText()).toEqual('Output long number: 234'); }); - it('should update the output when -3 is entered', function() { - numLimitInput.clear(); - numLimitInput.sendKeys('-3'); - letterLimitInput.clear(); - letterLimitInput.sendKeys('-3'); - expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]'); - expect(limitedLetters.getText()).toEqual('Output letters: ghi'); - }); + // There is a bug in safari and protractor that doesn't like the minus key + // it('should update the output when -3 is entered', function() { + // numLimitInput.clear(); + // numLimitInput.sendKeys('-3'); + // letterLimitInput.clear(); + // letterLimitInput.sendKeys('-3'); + // longNumberLimitInput.clear(); + // longNumberLimitInput.sendKeys('-3'); + // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]'); + // expect(limitedLetters.getText()).toEqual('Output letters: ghi'); + // expect(limitedLongNumber.getText()).toEqual('Output long number: 342'); + // }); it('should not exceed the maximum size of input array', function() { numLimitInput.clear(); numLimitInput.sendKeys('100'); letterLimitInput.clear(); letterLimitInput.sendKeys('100'); + longNumberLimitInput.clear(); + longNumberLimitInput.sendKeys('100'); expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]'); expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi'); + expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342'); }); - */ -function limitToFilter(){ - return function(input, limit) { - if (!isArray(input) && !isString(input)) return input; - - limit = int(limit); - - if (isString(input)) { - //NaN check on limit - if (limit) { - return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); - } else { - return ""; - } +*/ +function limitToFilter() { + return function(input, limit, begin) { + if (Math.abs(Number(limit)) === Infinity) { + limit = Number(limit); + } else { + limit = toInt(limit); } + if (isNumberNaN(limit)) return input; - var out = [], - i, n; + if (isNumber(input)) input = input.toString(); + if (!isArrayLike(input)) return input; - // if abs(limit) exceeds maximum length, trim it - if (limit > input.length) - limit = input.length; - else if (limit < -input.length) - limit = -input.length; + begin = (!begin || isNaN(begin)) ? 0 : toInt(begin); + begin = (begin < 0) ? Math.max(0, input.length + begin) : begin; - if (limit > 0) { - i = 0; - n = limit; + if (limit >= 0) { + return sliceFn(input, begin, begin + limit); } else { - i = input.length + limit; - n = input.length; + if (begin === 0) { + return sliceFn(input, limit, input.length); + } else { + return sliceFn(input, Math.max(0, begin + limit), begin); + } } + }; +} - for (; i} expression A predicate to be - * used by the comparator to determine the order of elements. + * Returns an array containing the items from the specified `collection`, ordered by a `comparator` + * function based on the values computed using the `expression` predicate. + * + * For example, `[{id: 'foo'}, {id: 'bar'}] | orderBy:'id'` would result in + * `[{id: 'bar'}, {id: 'foo'}]`. + * + * The `collection` can be an Array or array-like object (e.g. NodeList, jQuery object, TypedArray, + * String, etc). + * + * The `expression` can be a single predicate, or a list of predicates each serving as a tie-breaker + * for the preceding one. The `expression` is evaluated against each item and the output is used + * for comparing with other items. + * + * You can change the sorting order by setting `reverse` to `true`. By default, items are sorted in + * ascending order. + * + * The comparison is done using the `comparator` function. If none is specified, a default, built-in + * comparator is used (see below for details - in a nutshell, it compares numbers numerically and + * strings alphabetically). + * + * ### Under the hood + * + * Ordering the specified `collection` happens in two phases: + * + * 1. All items are passed through the predicate (or predicates), and the returned values are saved + * along with their type (`string`, `number` etc). For example, an item `{label: 'foo'}`, passed + * through a predicate that extracts the value of the `label` property, would be transformed to: + * ``` + * { + * value: 'foo', + * type: 'string', + * index: ... + * } + * ``` + * **Note:** `null` values use `'null'` as their type. + * 2. The comparator function is used to sort the items, based on the derived values, types and + * indices. + * + * If you use a custom comparator, it will be called with pairs of objects of the form + * `{value: ..., type: '...', index: ...}` and is expected to return `0` if the objects are equal + * (as far as the comparator is concerned), `-1` if the 1st one should be ranked higher than the + * second, or `1` otherwise. + * + * In order to ensure that the sorting will be deterministic across platforms, if none of the + * specified predicates can distinguish between two items, `orderBy` will automatically introduce a + * dummy predicate that returns the item's index as `value`. + * (If you are using a custom comparator, make sure it can handle this predicate as well.) + * + * If a custom comparator still can't distinguish between two items, then they will be sorted based + * on their index using the built-in comparator. + * + * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted + * value for an item, `orderBy` will try to convert that object to a primitive value, before passing + * it to the comparator. The following rules govern the conversion: + * + * 1. If the object has a `valueOf()` method that returns a primitive, its return value will be + * used instead.
+ * (If the object has a `valueOf()` method that returns another object, then the returned object + * will be used in subsequent steps.) + * 2. If the object has a custom `toString()` method (i.e. not the one inherited from `Object`) that + * returns a primitive, its return value will be used instead.
+ * (If the object has a `toString()` method that returns another object, then the returned object + * will be used in subsequent steps.) + * 3. No conversion; the object itself is used. + * + * ### The default comparator + * + * The default, built-in comparator should be sufficient for most usecases. In short, it compares + * numbers numerically, strings alphabetically (and case-insensitively), for objects falls back to + * using their index in the original collection, sorts values of different types by type and puts + * `undefined` and `null` values at the end of the sorted list. + * + * More specifically, it follows these steps to determine the relative order of items: + * + * 1. If the compared values are of different types: + * - If one of the values is undefined, consider it "greater than" the other. + * - Else if one of the values is null, consider it "greater than" the other. + * - Else compare the types themselves alphabetically. + * 2. If both values are of type `string`, compare them alphabetically in a case- and + * locale-insensitive way. + * 3. If both values are objects, compare their indices instead. + * 4. Otherwise, return: + * - `0`, if the values are equal (by strict equality comparison, i.e. using `===`). + * - `-1`, if the 1st value is "less than" the 2nd value (compared using the `<` operator). + * - `1`, otherwise. + * + * **Note:** If you notice numbers not being sorted as expected, make sure they are actually being + * saved as numbers and not strings. + * **Note:** For the purpose of sorting, `null` and `undefined` are considered "greater than" + * any other value (with undefined "greater than" null). This effectively means that `null` + * and `undefined` values end up at the end of a list sorted in ascending order. + * **Note:** `null` values use `'null'` as their type to be able to distinguish them from objects. + * + * @param {Array|ArrayLike} collection - The collection (array or array-like object) to sort. + * @param {(Function|string|Array.)=} expression - A predicate (or list of + * predicates) to be used by the comparator to determine the order of elements. * * Can be one of: * - * - `function`: Getter function. The result of this function will be sorted using the - * `<`, `=`, `>` operator. - * - `string`: An Angular expression which evaluates to an object to order by, such as 'name' - * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control - * ascending or descending sort order (for example, +name or -name). - * - `Array`: An array of function or string predicates. The first predicate in the array - * is used for sorting, but when two items are equivalent, the next predicate is used. + * - `Function`: A getter function. This function will be called with each item as argument and + * the return value will be used for sorting. + * - `string`: An AngularJS expression. This expression will be evaluated against each item and the + * result will be used for sorting. For example, use `'label'` to sort by a property called + * `label` or `'label.substring(0, 3)'` to sort by the first 3 characters of the `label` + * property.
+ * (The result of a constant expression is interpreted as a property name to be used for + * comparison. For example, use `'"special name"'` (note the extra pair of quotes) to sort by a + * property called `special name`.)
+ * An expression can be optionally prefixed with `+` or `-` to control the sorting direction, + * ascending or descending. For example, `'+label'` or `'-label'`. If no property is provided, + * (e.g. `'+'` or `'-'`), the collection element itself is used in comparisons. + * - `Array`: An array of function and/or string predicates. If a predicate cannot determine the + * relative order of two items, the next predicate is used as a tie-breaker. + * + * **Note:** If the predicate is missing or empty then it defaults to `'+'`. + * + * @param {boolean=} reverse - If `true`, reverse the sorting order. + * @param {(Function)=} comparator - The comparator function used to determine the relative order of + * value pairs. If omitted, the built-in comparator will be used. + * + * @returns {Array} - The sorted array. * - * @param {boolean=} reverse Reverse the order of the array. - * @returns {Array} Sorted copy of the source array. * * @example - + * ### Ordering a table with `ngRepeat` + * + * The example below demonstrates a simple {@link ngRepeat ngRepeat}, where the data is sorted by + * age in descending order (expression is set to `'-age'`). The `comparator` is not set, which means + * it defaults to the built-in comparator. + * + - -
-
Sorting predicate = {{predicate}}; reverse = {{reverse}}
+
+
NamePhone
+ + + + + + + + + + +
NamePhone NumberAge
{{friend.name}}{{friend.phone}}{{friend.age}}
+
+ + + angular.module('orderByExample1', []) + .controller('ExampleController', ['$scope', function($scope) { + $scope.friends = [ + {name: 'John', phone: '555-1212', age: 10}, + {name: 'Mary', phone: '555-9876', age: 19}, + {name: 'Mike', phone: '555-4321', age: 21}, + {name: 'Adam', phone: '555-5678', age: 35}, + {name: 'Julie', phone: '555-8765', age: 29} + ]; + }]); + + + .friends { + border-collapse: collapse; + } + + .friends th { + border-bottom: 1px solid; + } + .friends td, .friends th { + border-left: 1px solid; + padding: 5px 10px; + } + .friends td:first-child, .friends th:first-child { + border-left: none; + } + + + // Element locators + var names = element.all(by.repeater('friends').column('friend.name')); + + it('should sort friends by age in reverse order', function() { + expect(names.get(0).getText()).toBe('Adam'); + expect(names.get(1).getText()).toBe('Julie'); + expect(names.get(2).getText()).toBe('Mike'); + expect(names.get(3).getText()).toBe('Mary'); + expect(names.get(4).getText()).toBe('John'); + }); + + + *
+ * + * @example + * ### Changing parameters dynamically + * + * All parameters can be changed dynamically. The next example shows how you can make the columns of + * a table sortable, by binding the `expression` and `reverse` parameters to scope properties. + * + + +
+
Sort by = {{propertyName}}; reverse = {{reverse}}
+
+ +
+ + + + + + + + + + + +
+ + + + + + + + +
{{friend.name}}{{friend.phone}}{{friend.age}}
+
+
+ + angular.module('orderByExample2', []) + .controller('ExampleController', ['$scope', function($scope) { + var friends = [ + {name: 'John', phone: '555-1212', age: 10}, + {name: 'Mary', phone: '555-9876', age: 19}, + {name: 'Mike', phone: '555-4321', age: 21}, + {name: 'Adam', phone: '555-5678', age: 35}, + {name: 'Julie', phone: '555-8765', age: 29} + ]; + + $scope.propertyName = 'age'; + $scope.reverse = true; + $scope.friends = friends; + + $scope.sortBy = function(propertyName) { + $scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false; + $scope.propertyName = propertyName; + }; + }]); + + + .friends { + border-collapse: collapse; + } + + .friends th { + border-bottom: 1px solid; + } + .friends td, .friends th { + border-left: 1px solid; + padding: 5px 10px; + } + .friends td:first-child, .friends th:first-child { + border-left: none; + } + + .sortorder:after { + content: '\25b2'; // BLACK UP-POINTING TRIANGLE + } + .sortorder.reverse:after { + content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE + } + + + // Element locators + var unsortButton = element(by.partialButtonText('unsorted')); + var nameHeader = element(by.partialButtonText('Name')); + var phoneHeader = element(by.partialButtonText('Phone')); + var ageHeader = element(by.partialButtonText('Age')); + var firstName = element(by.repeater('friends').column('friend.name').row(0)); + var lastName = element(by.repeater('friends').column('friend.name').row(4)); + + it('should sort friends by some property, when clicking on the column header', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + + phoneHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Mary'); + + nameHeader.click(); + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('Mike'); + + ageHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Adam'); + }); + + it('should sort friends in reverse order, when clicking on the same column', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + + ageHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Adam'); + + ageHeader.click(); + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + }); + + it('should restore the original order, when clicking "Set to unsorted"', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + + unsortButton.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Julie'); + }); + +
+ *
+ * + * @example + * ### Using `orderBy` inside a controller + * + * It is also possible to call the `orderBy` filter manually, by injecting `orderByFilter`, and + * calling it with the desired parameters. (Alternatively, you could inject the `$filter` factory + * and retrieve the `orderBy` filter with `$filter('orderBy')`.) + * + + +
+
Sort by = {{propertyName}}; reverse = {{reverse}}

- [ unsorted ] - + +
+
- - - + + + - + @@ -15200,64 +23787,346 @@ function limitToFilter(){
Name - (^)Phone NumberAge + + + + + + + + +
{{friend.name}} {{friend.phone}} {{friend.age}}
+ + angular.module('orderByExample3', []) + .controller('ExampleController', ['$scope', 'orderByFilter', function($scope, orderBy) { + var friends = [ + {name: 'John', phone: '555-1212', age: 10}, + {name: 'Mary', phone: '555-9876', age: 19}, + {name: 'Mike', phone: '555-4321', age: 21}, + {name: 'Adam', phone: '555-5678', age: 35}, + {name: 'Julie', phone: '555-8765', age: 29} + ]; + + $scope.propertyName = 'age'; + $scope.reverse = true; + $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse); + + $scope.sortBy = function(propertyName) { + $scope.reverse = (propertyName !== null && $scope.propertyName === propertyName) + ? !$scope.reverse : false; + $scope.propertyName = propertyName; + $scope.friends = orderBy(friends, $scope.propertyName, $scope.reverse); + }; + }]); + + + .friends { + border-collapse: collapse; + } + + .friends th { + border-bottom: 1px solid; + } + .friends td, .friends th { + border-left: 1px solid; + padding: 5px 10px; + } + .friends td:first-child, .friends th:first-child { + border-left: none; + } + + .sortorder:after { + content: '\25b2'; // BLACK UP-POINTING TRIANGLE + } + .sortorder.reverse:after { + content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE + } + + + // Element locators + var unsortButton = element(by.partialButtonText('unsorted')); + var nameHeader = element(by.partialButtonText('Name')); + var phoneHeader = element(by.partialButtonText('Phone')); + var ageHeader = element(by.partialButtonText('Age')); + var firstName = element(by.repeater('friends').column('friend.name').row(0)); + var lastName = element(by.repeater('friends').column('friend.name').row(4)); + + it('should sort friends by some property, when clicking on the column header', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + + phoneHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Mary'); + + nameHeader.click(); + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('Mike'); + + ageHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Adam'); + }); + + it('should sort friends in reverse order, when clicking on the same column', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + + ageHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Adam'); + + ageHeader.click(); + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + }); + + it('should restore the original order, when clicking "Set to unsorted"', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + + unsortButton.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Julie'); + }); + +
+ *
+ * + * @example + * ### Using a custom comparator + * + * If you have very specific requirements about the way items are sorted, you can pass your own + * comparator function. For example, you might need to compare some strings in a locale-sensitive + * way. (When specifying a custom comparator, you also need to pass a value for the `reverse` + * argument - passing `false` retains the default sorting order, i.e. ascending.) + * + + +
+
+

Locale-sensitive Comparator

+ + + + + + + + + +
NameFavorite Letter
{{friend.name}}{{friend.favoriteLetter}}
+
+
+

Default Comparator

+ + + + + + + + + +
NameFavorite Letter
{{friend.name}}{{friend.favoriteLetter}}
+
+
+
+ + angular.module('orderByExample4', []) + .controller('ExampleController', ['$scope', function($scope) { + $scope.friends = [ + {name: 'John', favoriteLetter: 'Ä'}, + {name: 'Mary', favoriteLetter: 'Ü'}, + {name: 'Mike', favoriteLetter: 'Ö'}, + {name: 'Adam', favoriteLetter: 'H'}, + {name: 'Julie', favoriteLetter: 'Z'} + ]; + + $scope.localeSensitiveComparator = function(v1, v2) { + // If we don't get strings, just compare by index + if (v1.type !== 'string' || v2.type !== 'string') { + return (v1.index < v2.index) ? -1 : 1; + } + + // Compare strings alphabetically, taking locale into account + return v1.value.localeCompare(v2.value); + }; + }]); + + + .friends-container { + display: inline-block; + margin: 0 30px; + } + + .friends { + border-collapse: collapse; + } + + .friends th { + border-bottom: 1px solid; + } + .friends td, .friends th { + border-left: 1px solid; + padding: 5px 10px; + } + .friends td:first-child, .friends th:first-child { + border-left: none; + } + + + // Element locators + var container = element(by.css('.custom-comparator')); + var names = container.all(by.repeater('friends').column('friend.name')); + + it('should sort friends by favorite letter (in correct alphabetical order)', function() { + expect(names.get(0).getText()).toBe('John'); + expect(names.get(1).getText()).toBe('Adam'); + expect(names.get(2).getText()).toBe('Mike'); + expect(names.get(3).getText()).toBe('Mary'); + expect(names.get(4).getText()).toBe('Julie'); + }); +
+ * */ orderByFilter.$inject = ['$parse']; -function orderByFilter($parse){ - return function(array, sortPredicate, reverseOrder) { - if (!isArray(array)) return array; - if (!sortPredicate) return array; - sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate]; - sortPredicate = map(sortPredicate, function(predicate){ - var descending = false, get = predicate || identity; - if (isString(predicate)) { - if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { - descending = predicate.charAt(0) == '-'; +function orderByFilter($parse) { + return function(array, sortPredicate, reverseOrder, compareFn) { + + if (array == null) return array; + if (!isArrayLike(array)) { + throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array); + } + + if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; } + if (sortPredicate.length === 0) { sortPredicate = ['+']; } + + var predicates = processPredicates(sortPredicate); + + var descending = reverseOrder ? -1 : 1; + + // Define the `compare()` function. Use a default comparator if none is specified. + var compare = isFunction(compareFn) ? compareFn : defaultCompare; + + // The next three lines are a version of a Swartzian Transform idiom from Perl + // (sometimes called the Decorate-Sort-Undecorate idiom) + // See https://en.wikipedia.org/wiki/Schwartzian_transform + var compareValues = Array.prototype.map.call(array, getComparisonObject); + compareValues.sort(doComparison); + array = compareValues.map(function(item) { return item.value; }); + + return array; + + function getComparisonObject(value, index) { + // NOTE: We are adding an extra `tieBreaker` value based on the element's index. + // This will be used to keep the sort stable when none of the input predicates can + // distinguish between two elements. + return { + value: value, + tieBreaker: {value: index, type: 'number', index: index}, + predicateValues: predicates.map(function(predicate) { + return getPredicateValue(predicate.get(value), index); + }) + }; + } + + function doComparison(v1, v2) { + for (var i = 0, ii = predicates.length; i < ii; i++) { + var result = compare(v1.predicateValues[i], v2.predicateValues[i]); + if (result) { + return result * predicates[i].descending * descending; + } + } + + return (compare(v1.tieBreaker, v2.tieBreaker) || defaultCompare(v1.tieBreaker, v2.tieBreaker)) * descending; + } + }; + + function processPredicates(sortPredicates) { + return sortPredicates.map(function(predicate) { + var descending = 1, get = identity; + + if (isFunction(predicate)) { + get = predicate; + } else if (isString(predicate)) { + if ((predicate.charAt(0) === '+' || predicate.charAt(0) === '-')) { + descending = predicate.charAt(0) === '-' ? -1 : 1; predicate = predicate.substring(1); } - get = $parse(predicate); - if (get.constant) { - var key = get(); - return reverseComparator(function(a,b) { - return compare(a[key], b[key]); - }, descending); + if (predicate !== '') { + get = $parse(predicate); + if (get.constant) { + var key = get(); + get = function(value) { return value[key]; }; + } } } - return reverseComparator(function(a,b){ - return compare(get(a),get(b)); - }, descending); + return {get: get, descending: descending}; }); - var arrayCopy = []; - for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); } - return arrayCopy.sort(reverseComparator(comparator, reverseOrder)); - - function comparator(o1, o2){ - for ( var i = 0; i < sortPredicate.length; i++) { - var comp = sortPredicate[i](o1, o2); - if (comp !== 0) return comp; - } - return 0; - } - function reverseComparator(comp, descending) { - return toBoolean(descending) - ? function(a,b){return comp(b,a);} - : comp; - } - function compare(v1, v2){ - var t1 = typeof v1; - var t2 = typeof v2; - if (t1 == t2) { - if (t1 == "string") { - v1 = v1.toLowerCase(); - v2 = v2.toLowerCase(); - } - if (v1 === v2) return 0; - return v1 < v2 ? -1 : 1; - } else { - return t1 < t2 ? -1 : 1; + } + + function isPrimitive(value) { + switch (typeof value) { + case 'number': /* falls through */ + case 'boolean': /* falls through */ + case 'string': + return true; + default: + return false; + } + } + + function objectValue(value) { + // If `valueOf` is a valid function use that + if (isFunction(value.valueOf)) { + value = value.valueOf(); + if (isPrimitive(value)) return value; + } + // If `toString` is a valid function and not the one from `Object.prototype` use that + if (hasCustomToString(value)) { + value = value.toString(); + if (isPrimitive(value)) return value; + } + + return value; + } + + function getPredicateValue(value, index) { + var type = typeof value; + if (value === null) { + type = 'null'; + } else if (type === 'object') { + value = objectValue(value); + } + return {value: value, type: type, index: index}; + } + + function defaultCompare(v1, v2) { + var result = 0; + var type1 = v1.type; + var type2 = v2.type; + + if (type1 === type2) { + var value1 = v1.value; + var value2 = v2.value; + + if (type1 === 'string') { + // Compare strings case-insensitively + value1 = value1.toLowerCase(); + value2 = value2.toLowerCase(); + } else if (type1 === 'object') { + // For basic objects, use the position of the object + // in the collection instead of the value + if (isObject(value1)) value1 = v1.index; + if (isObject(value2)) value2 = v2.index; + } + + if (value1 !== value2) { + result = value1 < value2 ? -1 : 1; } + } else { + result = (type1 === 'undefined') ? 1 : + (type2 === 'undefined') ? -1 : + (type1 === 'null') ? 1 : + (type2 === 'null') ? -1 : + (type1 < type2) ? -1 : 1; } - }; + + return result; + } } function ngDirective(directive) { @@ -15276,38 +24145,23 @@ function ngDirective(directive) { * @restrict E * * @description - * Modifies the default behavior of the html A tag so that the default action is prevented when + * Modifies the default behavior of the html a tag so that the default action is prevented when * the href attribute is empty. * - * This change permits the easy creation of action links with the `ngClick` directive - * without changing the location or causing page reloads, e.g.: - * `Add Item` + * For dynamically creating `href` attributes for a tags, see the {@link ng.ngHref `ngHref`} directive. */ var htmlAnchorDirective = valueFn({ restrict: 'E', compile: function(element, attr) { - - if (msie <= 8) { - - // turn link into a stylable link in IE - // but only if it doesn't have name attribute, in which case it's an anchor - if (!attr.href && !attr.name) { - attr.$set('href', ''); - } - - // add a comment node to anchors to workaround IE bug that causes element content to be reset - // to new attribute content if attribute is updated with value containing @ and element also - // contains value with @ - // see issue #1949 - element.append(document.createComment('IE fix')); - } - - if (!attr.href && !attr.xlinkHref && !attr.name) { + if (!attr.href && !attr.xlinkHref) { return function(scope, element) { + // If the linked element is not an anchor tag anymore, do nothing + if (element[0].nodeName.toLowerCase() !== 'a') return; + // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ? 'xlink:href' : 'href'; - element.on('click', function(event){ + element.on('click', function(event) { // if we have no href url, then don't navigate anywhere. if (!element.attr(href)) { event.preventDefault(); @@ -15325,22 +24179,21 @@ var htmlAnchorDirective = valueFn({ * @priority 99 * * @description - * Using Angular markup like `{{hash}}` in an href attribute will + * Using AngularJS markup like `{{hash}}` in an href attribute will * make the link go to the wrong URL if the user clicks it before - * Angular has a chance to replace the `{{hash}}` markup with its - * value. Until Angular replaces the markup the link will be broken - * and will most likely return a 404 error. - * - * The `ngHref` directive solves this problem. + * AngularJS has a chance to replace the `{{hash}}` markup with its + * value. Until AngularJS replaces the markup the link will be broken + * and will most likely return a 404 error. The `ngHref` directive + * solves this problem. * * The wrong way to write it: * ```html - * + * link1 * ``` * * The correct way to write it: * ```html - * + * link1 * ``` * * @element A @@ -15349,7 +24202,7 @@ var htmlAnchorDirective = valueFn({ * @example * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes * in links and their different behaviors: - +
link 1 (link, don't reload)
@@ -15377,17 +24230,17 @@ var htmlAnchorDirective = valueFn({ element(by.id('link-3')).click(); - // At this point, we navigate away from an Angular page, so we need + // At this point, we navigate away from an AngularJS page, so we need // to use browser.driver to get the base webdriver. browser.wait(function() { return browser.driver.getCurrentUrl().then(function(url) { return url.match(/\/123$/); }); - }, 1000, 'page should navigate to /123'); + }, 5000, 'page should navigate to /123'); }); - xit('should execute ng-click but not reload when href empty string and name specified', function() { + it('should execute ng-click but not reload when href empty string and name specified', function() { element(by.id('link-4')).click(); expect(element(by.model('value')).getAttribute('value')).toEqual('4'); expect(element(by.id('link-4')).getAttribute('href')).toBe(''); @@ -15406,13 +24259,13 @@ var htmlAnchorDirective = valueFn({ element(by.id('link-6')).click(); - // At this point, we navigate away from an Angular page, so we need + // At this point, we navigate away from an AngularJS page, so we need // to use browser.driver to get the base webdriver. browser.wait(function() { return browser.driver.getCurrentUrl().then(function(url) { return url.match(/\/6$/); }); - }, 1000, 'page should navigate to /6'); + }, 5000, 'page should navigate to /6'); });
@@ -15425,19 +24278,19 @@ var htmlAnchorDirective = valueFn({ * @priority 99 * * @description - * Using Angular markup like `{{hash}}` in a `src` attribute doesn't + * Using AngularJS markup like `{{hash}}` in a `src` attribute doesn't * work right: The browser will fetch from the URL with the literal - * text `{{hash}}` until Angular replaces the expression inside + * text `{{hash}}` until AngularJS replaces the expression inside * `{{hash}}`. The `ngSrc` directive solves this problem. * * The buggy way to write it: * ```html - * + * Description * ``` * * The correct way to write it: * ```html - * + * Description * ``` * * @element IMG @@ -15451,19 +24304,19 @@ var htmlAnchorDirective = valueFn({ * @priority 99 * * @description - * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't + * Using AngularJS markup like `{{hash}}` in a `srcset` attribute doesn't * work right: The browser will fetch from the URL with the literal - * text `{{hash}}` until Angular replaces the expression inside + * text `{{hash}}` until AngularJS replaces the expression inside * `{{hash}}`. The `ngSrcset` directive solves this problem. * * The buggy way to write it: * ```html - * + * Description * ``` * * The correct way to write it: * ```html - * + * Description * ``` * * @element IMG @@ -15478,25 +24331,17 @@ var htmlAnchorDirective = valueFn({ * * @description * - * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs: - * ```html - *
- * - *
- * ``` + * This directive sets the `disabled` attribute on the element (typically a form control, + * e.g. `input`, `button`, `select` etc.) if the + * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy. * - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as disabled. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngDisabled` directive solves this problem for the `disabled` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. + * A special directive is necessary because we cannot use interpolation inside the `disabled` + * attribute. See the {@link guide/interpolation interpolation guide} for more info. * * @example - + - Click me to toggle:
+
@@ -15508,9 +24353,8 @@ var htmlAnchorDirective = valueFn({
* - * @element INPUT * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, - * then special attribute "disabled" will be set on the element + * then the `disabled` attribute will be set on the element */ @@ -15521,31 +24365,32 @@ var htmlAnchorDirective = valueFn({ * @priority 100 * * @description - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as checked. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngChecked` directive solves this problem for the `checked` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. + * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy. + * + * Note that this directive should not be used together with {@link ngModel `ngModel`}, + * as this can lead to unexpected behavior. + * + * A special directive is necessary because we cannot use interpolation inside the `checked` + * attribute. See the {@link guide/interpolation interpolation guide} for more info. + * * @example - + - Check me to check both:
- +
+
it('should check both checkBoxes', function() { - expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy(); - element(by.model('master')).click(); - expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy(); + expect(element(by.id('checkFollower')).getAttribute('checked')).toBeFalsy(); + element(by.model('leader')).click(); + expect(element(by.id('checkFollower')).getAttribute('checked')).toBeTruthy(); });
* * @element INPUT * @param {expression} ngChecked If the {@link guide/expression expression} is truthy, - * then special attribute "checked" will be set on the element + * then the `checked` attribute will be set on the element */ @@ -15556,18 +24401,19 @@ var htmlAnchorDirective = valueFn({ * @priority 100 * * @description - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as readonly. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngReadonly` directive solves this problem for the `readonly` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. + * + * Sets the `readonly` attribute on the element, if the expression inside `ngReadonly` is truthy. + * Note that `readonly` applies only to `input` elements with specific types. [See the input docs on + * MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-readonly) for more information. + * + * A special directive is necessary because we cannot use interpolation inside the `readonly` + * attribute. See the {@link guide/interpolation interpolation guide} for more info. + * * @example - + - Check me to make text readonly:
- +
+
it('should toggle readonly attr', function() { @@ -15591,19 +24437,24 @@ var htmlAnchorDirective = valueFn({ * @priority 100 * * @description - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as selected. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngSelected` directive solves this problem for the `selected` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. + * + * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy. + * + * A special directive is necessary because we cannot use interpolation inside the `selected` + * attribute. See the {@link guide/interpolation interpolation guide} for more info. + * + *
+ * **Note:** `ngSelected` does not interact with the `select` and `ngModel` directives, it only + * sets the `selected` attribute on the element. If you are using `ngModel` on the select, you + * should not use `ngSelected` on the options, as `ngModel` will set the select value and + * selected options. + *
* * @example - + - Check me to select:
-
+ @@ -15629,19 +24480,28 @@ var htmlAnchorDirective = valueFn({ * @priority 100 * * @description - * The HTML specification does not require browsers to preserve the values of boolean attributes - * such as open. (Their presence means true and their absence means false.) - * If we put an Angular interpolation expression into such an attribute then the - * binding information would be lost when the browser removes the attribute. - * The `ngOpen` directive solves this problem for the `open` attribute. - * This complementary directive is not removed by the browser and so provides - * a permanent reliable place to store the binding information. + * + * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy. + * + * A special directive is necessary because we cannot use interpolation inside the `open` + * attribute. See the {@link guide/interpolation interpolation guide} for more info. + * + * ## A note about browser compatibility + * + * Internet Explorer and Edge do not support the `details` element, it is + * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead. + * * @example - + - Check me check multiple:
+
- Show/Hide me + List +
    +
  • Apple
  • +
  • Orange
  • +
  • Durian
  • +
@@ -15660,30 +24520,66 @@ var htmlAnchorDirective = valueFn({ var ngAttributeAliasDirectives = {}; - // boolean attrs are evaluated forEach(BOOLEAN_ATTR, function(propName, attrName) { // binding to multiple is not supported - if (propName == "multiple") return; + if (propName === 'multiple') return; + + function defaultLinkFn(scope, element, attr) { + scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { + attr.$set(attrName, !!value); + }); + } var normalized = directiveNormalize('ng-' + attrName); - ngAttributeAliasDirectives[normalized] = function() { - return { - priority: 100, + var linkFn = defaultLinkFn; + + if (propName === 'checked') { + linkFn = function(scope, element, attr) { + // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input + if (attr.ngModel !== attr[normalized]) { + defaultLinkFn(scope, element, attr); + } + }; + } + + ngAttributeAliasDirectives[normalized] = function() { + return { + restrict: 'A', + priority: 100, + link: linkFn + }; + }; +}); + +// aliased input attrs are evaluated +forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) { + ngAttributeAliasDirectives[ngAttr] = function() { + return { + priority: 100, link: function(scope, element, attr) { - scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { - attr.$set(attrName, !!value); + //special case ngPattern when a literal regular expression value + //is used as the expression (this way we don't have to watch anything). + if (ngAttr === 'ngPattern' && attr.ngPattern.charAt(0) === '/') { + var match = attr.ngPattern.match(REGEX_STRING_REGEXP); + if (match) { + attr.$set('ngPattern', new RegExp(match[1], match[2])); + return; + } + } + + scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) { + attr.$set(ngAttr, value); }); } }; }; }); - // ng-src, ng-srcset, ng-href are interpolated forEach(['src', 'srcset', 'href'], function(attrName) { var normalized = directiveNormalize('ng-' + attrName); - ngAttributeAliasDirectives[normalized] = function() { + ngAttributeAliasDirectives[normalized] = ['$sce', function($sce) { return { priority: 99, // it needs to run after the attributes are interpolated link: function(scope, element, attr) { @@ -15697,31 +24593,51 @@ forEach(['src', 'srcset', 'href'], function(attrName) { propName = null; } + // We need to sanitize the url at least once, in case it is a constant + // non-interpolated attribute. + attr.$set(normalized, $sce.getTrustedMediaUrl(attr[normalized])); + attr.$observe(normalized, function(value) { - if (!value) - return; + if (!value) { + if (attrName === 'href') { + attr.$set(name, null); + } + return; + } attr.$set(name, value); - // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist + // Support: IE 9-11 only + // On IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need // to set the property as well to achieve the desired effect. - // we use attr[attrName] value since $set can sanitize the url. + // We use attr[attrName] value since $set might have sanitized the url. if (msie && propName) element.prop(propName, attr[name]); }); } }; - }; + }]; }); -/* global -nullFormCtrl */ +/* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS + */ var nullFormCtrl = { $addControl: noop, + $getControls: valueFn([]), + $$renameControl: nullFormRenameControl, $removeControl: noop, $setValidity: noop, $setDirty: noop, - $setPristine: noop -}; + $setPristine: noop, + $setSubmitted: noop, + $$setSubmitted: noop +}, +PENDING_CLASS = 'ng-pending', +SUBMITTED_CLASS = 'ng-submitted'; + +function nullFormRenameControl(control, name) { + control.$name = name; +} /** * @ngdoc type @@ -15731,16 +24647,23 @@ var nullFormCtrl = { * @property {boolean} $dirty True if user has already interacted with the form. * @property {boolean} $valid True if all of the containing forms and controls are valid. * @property {boolean} $invalid True if at least one containing control or form is invalid. + * @property {boolean} $submitted True if user has submitted the form even if its invalid. * - * @property {Object} $error Is an object hash, containing references to all invalid controls or - * forms, where: + * @property {Object} $pending An object hash, containing references to controls or forms with + * pending validators, where: * - * - keys are validation tokens (error names), - * - values are arrays of controls or forms that are invalid for given error name. + * - keys are validations tokens (error names). + * - values are arrays of controls or forms that have a pending validator for the given error name. * + * See {@link form.FormController#$error $error} for a list of built-in validation tokens. * - * Built-in validation tokens: + * @property {Object} $error An object hash, containing references to controls or forms with failing + * validators, where: + * + * - keys are validation tokens (error names), + * - values are arrays of controls or forms that have a failing validator for the given error name. * + * Built-in validation tokens: * - `email` * - `max` * - `maxlength` @@ -15750,9 +24673,14 @@ var nullFormCtrl = { * - `pattern` * - `required` * - `url` + * - `date` + * - `datetimelocal` + * - `time` + * - `week` + * - `month` * * @description - * `FormController` keeps track of all its controls and nested forms as well as state of them, + * `FormController` keeps track of all its controls and nested forms as well as the state of them, * such as being valid/invalid or dirty/pristine. * * Each {@link ng.directive:form form} directive creates an instance @@ -15760,120 +24688,168 @@ var nullFormCtrl = { * */ //asks for $scope to fool the BC controller module -FormController.$inject = ['$element', '$attrs', '$scope', '$animate']; -function FormController(element, attrs, $scope, $animate) { - var form = this, - parentForm = element.parent().controller('form') || nullFormCtrl, - invalidCount = 0, // used to easily determine if we are valid - errors = form.$error = {}, - controls = []; +FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate']; +function FormController($element, $attrs, $scope, $animate, $interpolate) { + this.$$controls = []; // init state - form.$name = attrs.name || attrs.ngForm; - form.$dirty = false; - form.$pristine = true; - form.$valid = true; - form.$invalid = false; + this.$error = {}; + this.$$success = {}; + this.$pending = undefined; + this.$name = $interpolate($attrs.name || $attrs.ngForm || '')($scope); + this.$dirty = false; + this.$pristine = true; + this.$valid = true; + this.$invalid = false; + this.$submitted = false; + this.$$parentForm = nullFormCtrl; - parentForm.$addControl(form); + this.$$element = $element; + this.$$animate = $animate; - // Setup initial state of the control - element.addClass(PRISTINE_CLASS); - toggleValidCss(true); + setupValidity(this); +} - // convenience method for easy toggling of classes - function toggleValidCss(isValid, validationErrorKey) { - validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; - $animate.removeClass(element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey); - $animate.addClass(element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); - } +FormController.prototype = { + /** + * @ngdoc method + * @name form.FormController#$rollbackViewValue + * + * @description + * Rollback all form controls pending updates to the `$modelValue`. + * + * Updates may be pending by a debounced event or because the input is waiting for a some future + * event defined in `ng-model-options`. This method is typically needed by the reset button of + * a form that uses `ng-model-options` to pend updates. + */ + $rollbackViewValue: function() { + forEach(this.$$controls, function(control) { + control.$rollbackViewValue(); + }); + }, + + /** + * @ngdoc method + * @name form.FormController#$commitViewValue + * + * @description + * Commit all form controls pending updates to the `$modelValue`. + * + * Updates may be pending by a debounced event or because the input is waiting for a some future + * event defined in `ng-model-options`. This method is rarely needed as `NgModelController` + * usually handles calling this in response to input events. + */ + $commitViewValue: function() { + forEach(this.$$controls, function(control) { + control.$commitViewValue(); + }); + }, /** * @ngdoc method * @name form.FormController#$addControl + * @param {object} control control object, either a {@link form.FormController} or an + * {@link ngModel.NgModelController} * * @description - * Register a control with the form. + * Register a control with the form. Input elements using ngModelController do this automatically + * when they are linked. * - * Input elements using ngModelController do this automatically when they are linked. + * Note that the current state of the control will not be reflected on the new parent form. This + * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine` + * state. + * + * However, if the method is used programmatically, for example by adding dynamically created controls, + * or controls that have been previously removed without destroying their corresponding DOM element, + * it's the developers responsibility to make sure the current state propagates to the parent form. + * + * For example, if an input control is added that is already `$dirty` and has `$error` properties, + * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form. */ - form.$addControl = function(control) { + $addControl: function(control) { // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored // and not added to the scope. Now we throw an error. assertNotHasOwnProperty(control.$name, 'input'); - controls.push(control); + this.$$controls.push(control); if (control.$name) { - form[control.$name] = control; + this[control.$name] = control; } - }; + + control.$$parentForm = this; + }, /** * @ngdoc method - * @name form.FormController#$removeControl + * @name form.FormController#$getControls + * @returns {Array} the controls that are currently part of this form * * @description - * Deregister a control from the form. + * This method returns a **shallow copy** of the controls that are currently part of this form. + * The controls can be instances of {@link form.FormController `FormController`} + * ({@link ngForm "child-forms"}) and of {@link ngModel.NgModelController `NgModelController`}. + * If you need access to the controls of child-forms, you have to call `$getControls()` + * recursively on them. + * This can be used for example to iterate over all controls to validate them. * - * Input elements using ngModelController do this automatically when they are destroyed. + * The controls can be accessed normally, but adding to, or removing controls from the array has + * no effect on the form. Instead, use {@link form.FormController#$addControl `$addControl()`} and + * {@link form.FormController#$removeControl `$removeControl()`} for this use-case. + * Likewise, adding a control to, or removing a control from the form is not reflected + * in the shallow copy. That means you should get a fresh copy from `$getControls()` every time + * you need access to the controls. */ - form.$removeControl = function(control) { - if (control.$name && form[control.$name] === control) { - delete form[control.$name]; - } - forEach(errors, function(queue, validationToken) { - form.$setValidity(validationToken, true, control); - }); + $getControls: function() { + return shallowCopy(this.$$controls); + }, - arrayRemove(controls, control); - }; + // Private API: rename a form control + $$renameControl: function(control, newName) { + var oldName = control.$name; + + if (this[oldName] === control) { + delete this[oldName]; + } + this[newName] = control; + control.$name = newName; + }, /** * @ngdoc method - * @name form.FormController#$setValidity + * @name form.FormController#$removeControl + * @param {object} control control object, either a {@link form.FormController} or an + * {@link ngModel.NgModelController} * * @description - * Sets the validity of a form control. + * Deregister a control from the form. + * + * Input elements using ngModelController do this automatically when they are destroyed. * - * This method will also propagate to parent forms. + * Note that only the removed control's validation state (`$errors`etc.) will be removed from the + * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be + * different from case to case. For example, removing the only `$dirty` control from a form may or + * may not mean that the form is still `$dirty`. */ - form.$setValidity = function(validationToken, isValid, control) { - var queue = errors[validationToken]; - - if (isValid) { - if (queue) { - arrayRemove(queue, control); - if (!queue.length) { - invalidCount--; - if (!invalidCount) { - toggleValidCss(isValid); - form.$valid = true; - form.$invalid = false; - } - errors[validationToken] = false; - toggleValidCss(true, validationToken); - parentForm.$setValidity(validationToken, true, form); - } - } - - } else { - if (!invalidCount) { - toggleValidCss(isValid); - } - if (queue) { - if (includes(queue, control)) return; - } else { - errors[validationToken] = queue = []; - invalidCount++; - toggleValidCss(false, validationToken); - parentForm.$setValidity(validationToken, false, form); - } - queue.push(control); - - form.$valid = false; - form.$invalid = true; + $removeControl: function(control) { + if (control.$name && this[control.$name] === control) { + delete this[control.$name]; } - }; + forEach(this.$pending, function(value, name) { + // eslint-disable-next-line no-invalid-this + this.$setValidity(name, null, control); + }, this); + forEach(this.$error, function(value, name) { + // eslint-disable-next-line no-invalid-this + this.$setValidity(name, null, control); + }, this); + forEach(this.$$success, function(value, name) { + // eslint-disable-next-line no-invalid-this + this.$setValidity(name, null, control); + }, this); + + arrayRemove(this.$$controls, control); + control.$$parentForm = nullFormCtrl; + }, /** * @ngdoc method @@ -15885,13 +24861,13 @@ function FormController(element, attrs, $scope, $animate) { * This method can be called to add the 'ng-dirty' class and set the form to a dirty * state (ng-dirty class). This method will also propagate to parent forms. */ - form.$setDirty = function() { - $animate.removeClass(element, PRISTINE_CLASS); - $animate.addClass(element, DIRTY_CLASS); - form.$dirty = true; - form.$pristine = false; - parentForm.$setDirty(); - }; + $setDirty: function() { + this.$$animate.removeClass(this.$$element, PRISTINE_CLASS); + this.$$animate.addClass(this.$$element, DIRTY_CLASS); + this.$dirty = true; + this.$pristine = false; + this.$$parentForm.$setDirty(); + }, /** * @ngdoc method @@ -15900,24 +24876,119 @@ function FormController(element, attrs, $scope, $animate) { * @description * Sets the form to its pristine state. * - * This method can be called to remove the 'ng-dirty' class and set the form to its pristine - * state (ng-pristine class). This method will also propagate to all the controls contained - * in this form. + * This method sets the form's `$pristine` state to true, the `$dirty` state to false, removes + * the `ng-dirty` class and adds the `ng-pristine` class. Additionally, it sets the `$submitted` + * state to false. + * + * This method will also propagate to all the controls contained in this form. * * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after * saving or resetting it. */ - form.$setPristine = function () { - $animate.removeClass(element, DIRTY_CLASS); - $animate.addClass(element, PRISTINE_CLASS); - form.$dirty = false; - form.$pristine = true; - forEach(controls, function(control) { + $setPristine: function() { + this.$$animate.setClass(this.$$element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS); + this.$dirty = false; + this.$pristine = true; + this.$submitted = false; + forEach(this.$$controls, function(control) { control.$setPristine(); }); - }; -} + }, + + /** + * @ngdoc method + * @name form.FormController#$setUntouched + * + * @description + * Sets the form to its untouched state. + * + * This method can be called to remove the 'ng-touched' class and set the form controls to their + * untouched state (ng-untouched class). + * + * Setting a form controls back to their untouched state is often useful when setting the form + * back to its pristine state. + */ + $setUntouched: function() { + forEach(this.$$controls, function(control) { + control.$setUntouched(); + }); + }, + + /** + * @ngdoc method + * @name form.FormController#$setSubmitted + * + * @description + * Sets the form to its `$submitted` state. This will also set `$submitted` on all child and + * parent forms of the form. + */ + $setSubmitted: function() { + var rootForm = this; + while (rootForm.$$parentForm && (rootForm.$$parentForm !== nullFormCtrl)) { + rootForm = rootForm.$$parentForm; + } + rootForm.$$setSubmitted(); + }, + $$setSubmitted: function() { + this.$$animate.addClass(this.$$element, SUBMITTED_CLASS); + this.$submitted = true; + forEach(this.$$controls, function(control) { + if (control.$$setSubmitted) { + control.$$setSubmitted(); + } + }); + } +}; + +/** + * @ngdoc method + * @name form.FormController#$setValidity + * + * @description + * Change the validity state of the form, and notify the parent form (if any). + * + * Application developers will rarely need to call this method directly. It is used internally, by + * {@link ngModel.NgModelController#$setValidity NgModelController.$setValidity()}, to propagate a + * control's validity state to the parent `FormController`. + * + * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be + * assigned to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` (for + * unfulfilled `$asyncValidators`), so that it is available for data-binding. The + * `validationErrorKey` should be in camelCase and will get converted into dash-case for + * class name. Example: `myError` will result in `ng-valid-my-error` and + * `ng-invalid-my-error` classes and can be bound to as `{{ someForm.$error.myError }}`. + * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending + * (undefined), or skipped (null). Pending is used for unfulfilled `$asyncValidators`. + * Skipped is used by AngularJS when validators do not run because of parse errors and when + * `$asyncValidators` do not run because any of the `$validators` failed. + * @param {NgModelController | FormController} controller - The controller whose validity state is + * triggering the change. + */ +addSetValidityMethod({ + clazz: FormController, + set: function(object, property, controller) { + var list = object[property]; + if (!list) { + object[property] = [controller]; + } else { + var index = list.indexOf(controller); + if (index === -1) { + list.push(controller); + } + } + }, + unset: function(object, property, controller) { + var list = object[property]; + if (!list) { + return; + } + arrayRemove(list, controller); + if (list.length === 0) { + delete object[property]; + } + } +}); /** * @ngdoc directive @@ -15925,16 +24996,21 @@ function FormController(element, attrs, $scope, $animate) { * @restrict EAC * * @description - * Nestable alias of {@link ng.directive:form `form`} directive. HTML - * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a - * sub-group of controls needs to be determined. - * - * Note: the purpose of `ngForm` is to group controls, - * but not to be a replacement for the `
` tag with all of its capabilities - * (e.g. posting to the server, ...). + * Helper directive that makes it possible to create control groups inside a + * {@link ng.directive:form `form`} directive. + * These "child forms" can be used, for example, to determine the validity of a sub-group of + * controls. + * + *
+ * **Note**: `ngForm` cannot be used as a replacement for ``, because it lacks its + * [built-in HTML functionality](https://html.spec.whatwg.org/#the-form-element). + * Specifically, you cannot submit `ngForm` like a `` tag. That means, + * you cannot send data to the server with `ngForm`, or integrate it with + * {@link ng.directive:ngSubmit `ngSubmit`}. + *
* - * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into - * related scope, under this name. + * @param {string=} ngForm|name Name of the form. If specified, the form controller will + * be published into the related scope, under this name. * */ @@ -15950,35 +25026,33 @@ function FormController(element, attrs, $scope, $animate) { * If the `name` attribute is specified, the form controller is published onto the current scope under * this name. * - * # Alias: {@link ng.directive:ngForm `ngForm`} + * ## Alias: {@link ng.directive:ngForm `ngForm`} * - * In Angular forms can be nested. This means that the outer form is valid when all of the child + * In AngularJS, forms can be nested. This means that the outer form is valid when all of the child * forms are valid as well. However, browsers do not allow nesting of `` elements, so - * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to - * `` but can be nested. This allows you to have nested forms, which is very useful when - * using Angular validation directives in forms that are dynamically generated using the - * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name` - * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an - * `ngForm` directive and nest these in an outer `form` element. + * AngularJS provides the {@link ng.directive:ngForm `ngForm`} directive, which behaves identically to + * `form` but can be nested. Nested forms can be useful, for example, if the validity of a sub-group + * of controls needs to be determined. * - * - * # CSS classes + * ## CSS classes * - `ng-valid` is set if the form is valid. * - `ng-invalid` is set if the form is invalid. + * - `ng-pending` is set if the form is pending. * - `ng-pristine` is set if the form is pristine. * - `ng-dirty` is set if the form is dirty. + * - `ng-submitted` is set if the form was submitted. * * Keep in mind that ngAnimate can detect each of these classes when added and removed. * * - * # Submitting a form and preventing the default action + * ## Submitting a form and preventing the default action * - * Since the role of forms in client-side Angular applications is different than in classical + * Since the role of forms in client-side AngularJS applications is different than in classical * roundtrip apps, it is desirable for the browser not to translate the form submission into a full * page reload that sends the data to the server. Instead some javascript logic should be triggered * to handle the form submission in an application-specific way. * - * For this reason, Angular prevents the default action (form submission to the server) unless the + * For this reason, AngularJS prevents the default action (form submission to the server) unless the * `` element has an `action` attribute specified. * * You can use one of the following two ways to specify what javascript method should be called when @@ -16000,11 +25074,11 @@ function FormController(element, attrs, $scope, $animate) { * hitting enter in any of the input fields will trigger the click handler on the *first* button or * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`) * - * @param {string=} name Name of the form. If specified, the form controller will be published into - * related scope, under this name. - * - * ## Animation Hooks + * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is + * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` + * to have access to the updated model. * + * @animations * Animations in ngForm are triggered when any of the associated CSS classes are added and removed. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any * other validations that are performed within the form. Animations in ngForm are similar to how @@ -16028,16 +25102,16 @@ function FormController(element, attrs, $scope, $animate) { * * * @example - + - + userType: Required!
- userType = {{userType}}
- myForm.input.$valid = {{myForm.input.$valid}}
- myForm.input.$error = {{myForm.input.$error}}
- myForm.$valid = {{myForm.$valid}}
- myForm.$error.required = {{!!myForm.$error.required}}
+ userType = {{userType}}
+ myForm.input.$valid = {{myForm.input.$valid}}
+ myForm.input.$error = {{myForm.input.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
@@ -16078,78 +25152,236 @@ function FormController(element, attrs, $scope, $animate) {
* + * @param {string=} name Name of the form. If specified, the form controller will be published into + * related scope, under this name. */ var formDirectiveFactory = function(isNgForm) { - return ['$timeout', function($timeout) { + return ['$timeout', '$parse', function($timeout, $parse) { var formDirective = { name: 'form', restrict: isNgForm ? 'EAC' : 'E', + require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form controller: FormController, - compile: function() { + compile: function ngFormCompile(formElement, attr) { + // Setup initial state of the control + formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS); + + var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false); + return { - pre: function(scope, formElement, attr, controller) { - if (!attr.action) { + pre: function ngFormPreLink(scope, formElement, attr, ctrls) { + var controller = ctrls[0]; + + // if `action` attr is not present on the form, prevent the default action (submission) + if (!('action' in attr)) { // we can't use jq events because if a form is destroyed during submission the default // action is not prevented. see #1238 // // IE 9 is not affected because it doesn't fire a submit event and try to do a full // page reload if the form was destroyed by submission of the form via a click handler // on a button in the form. Looks like an IE9 specific bug. - var preventDefaultListener = function(event) { - event.preventDefault - ? event.preventDefault() - : event.returnValue = false; // IE + var handleFormSubmission = function(event) { + scope.$apply(function() { + controller.$commitViewValue(); + controller.$setSubmitted(); + }); + + event.preventDefault(); }; - addEventListenerFn(formElement[0], 'submit', preventDefaultListener); + formElement[0].addEventListener('submit', handleFormSubmission); // unregister the preventDefault listener so that we don't not leak memory but in a // way that will achieve the prevention of the default action. formElement.on('$destroy', function() { $timeout(function() { - removeEventListenerFn(formElement[0], 'submit', preventDefaultListener); + formElement[0].removeEventListener('submit', handleFormSubmission); }, 0, false); }); } - var parentFormCtrl = formElement.parent().controller('form'), - alias = attr.name || attr.ngForm; + var parentFormCtrl = ctrls[1] || controller.$$parentForm; + parentFormCtrl.$addControl(controller); - if (alias) { - setter(scope, alias, controller, alias); - } - if (parentFormCtrl) { - formElement.on('$destroy', function() { - parentFormCtrl.$removeControl(controller); - if (alias) { - setter(scope, alias, undefined, alias); - } - extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards + var setter = nameAttr ? getSetter(controller.$name) : noop; + + if (nameAttr) { + setter(scope, controller); + attr.$observe(nameAttr, function(newValue) { + if (controller.$name === newValue) return; + setter(scope, undefined); + controller.$$parentForm.$$renameControl(controller, newValue); + setter = getSetter(controller.$name); + setter(scope, controller); }); } + formElement.on('$destroy', function() { + controller.$$parentForm.$removeControl(controller); + setter(scope, undefined); + extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards + }); } }; } }; return formDirective; + + function getSetter(expression) { + if (expression === '') { + //create an assignable expression, so forms with an empty name can be renamed later + return $parse('this[""]').assign; + } + return $parse(expression).assign || noop; + } }]; }; var formDirective = formDirectiveFactory(); var ngFormDirective = formDirectiveFactory(true); -/* global - -VALID_CLASS, - -INVALID_CLASS, - -PRISTINE_CLASS, - -DIRTY_CLASS + +// helper methods +function setupValidity(instance) { + instance.$$classCache = {}; + instance.$$classCache[INVALID_CLASS] = !(instance.$$classCache[VALID_CLASS] = instance.$$element.hasClass(VALID_CLASS)); +} +function addSetValidityMethod(context) { + var clazz = context.clazz, + set = context.set, + unset = context.unset; + + clazz.prototype.$setValidity = function(validationErrorKey, state, controller) { + if (isUndefined(state)) { + createAndSet(this, '$pending', validationErrorKey, controller); + } else { + unsetAndCleanup(this, '$pending', validationErrorKey, controller); + } + if (!isBoolean(state)) { + unset(this.$error, validationErrorKey, controller); + unset(this.$$success, validationErrorKey, controller); + } else { + if (state) { + unset(this.$error, validationErrorKey, controller); + set(this.$$success, validationErrorKey, controller); + } else { + set(this.$error, validationErrorKey, controller); + unset(this.$$success, validationErrorKey, controller); + } + } + if (this.$pending) { + cachedToggleClass(this, PENDING_CLASS, true); + this.$valid = this.$invalid = undefined; + toggleValidationCss(this, '', null); + } else { + cachedToggleClass(this, PENDING_CLASS, false); + this.$valid = isObjectEmpty(this.$error); + this.$invalid = !this.$valid; + toggleValidationCss(this, '', this.$valid); + } + + // re-read the state as the set/unset methods could have + // combined state in this.$error[validationError] (used for forms), + // where setting/unsetting only increments/decrements the value, + // and does not replace it. + var combinedState; + if (this.$pending && this.$pending[validationErrorKey]) { + combinedState = undefined; + } else if (this.$error[validationErrorKey]) { + combinedState = false; + } else if (this.$$success[validationErrorKey]) { + combinedState = true; + } else { + combinedState = null; + } + + toggleValidationCss(this, validationErrorKey, combinedState); + this.$$parentForm.$setValidity(validationErrorKey, combinedState, this); + }; + + function createAndSet(ctrl, name, value, controller) { + if (!ctrl[name]) { + ctrl[name] = {}; + } + set(ctrl[name], value, controller); + } + + function unsetAndCleanup(ctrl, name, value, controller) { + if (ctrl[name]) { + unset(ctrl[name], value, controller); + } + if (isObjectEmpty(ctrl[name])) { + ctrl[name] = undefined; + } + } + + function cachedToggleClass(ctrl, className, switchValue) { + if (switchValue && !ctrl.$$classCache[className]) { + ctrl.$$animate.addClass(ctrl.$$element, className); + ctrl.$$classCache[className] = true; + } else if (!switchValue && ctrl.$$classCache[className]) { + ctrl.$$animate.removeClass(ctrl.$$element, className); + ctrl.$$classCache[className] = false; + } + } + + function toggleValidationCss(ctrl, validationErrorKey, isValid) { + validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; + + cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true); + cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false); + } +} + +function isObjectEmpty(obj) { + if (obj) { + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + return false; + } + } + } + return true; +} + +/* global + VALID_CLASS: false, + INVALID_CLASS: false, + PRISTINE_CLASS: false, + DIRTY_CLASS: false, + ngModelMinErr: false */ -var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; -var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*$/i; -var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; +// Regex code was initially obtained from SO prior to modification: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231 +var ISO_DATE_REGEXP = /^\d{4,}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+(?:[+-][0-2]\d:[0-5]\d|Z)$/; +// See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987) +// Note: We are being more lenient, because browsers are too. +// 1. Scheme +// 2. Slashes +// 3. Username +// 4. Password +// 5. Hostname +// 6. Port +// 7. Path +// 8. Query +// 9. Fragment +// 1111111111111111 222 333333 44444 55555555555555555555555 666 77777777 8888888 999 +var URL_REGEXP = /^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i; +// eslint-disable-next-line max-len +var EMAIL_REGEXP = /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/; +var NUMBER_REGEXP = /^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/; +var DATE_REGEXP = /^(\d{4,})-(\d{2})-(\d{2})$/; +var DATETIMELOCAL_REGEXP = /^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; +var WEEK_REGEXP = /^(\d{4,})-W(\d\d)$/; +var MONTH_REGEXP = /^(\d{4,})-(\d\d)$/; +var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/; + +var PARTIAL_VALIDATION_EVENTS = 'keydown wheel mousedown'; +var PARTIAL_VALIDATION_TYPES = createMap(); +forEach('date,datetime-local,month,time,week'.split(','), function(type) { + PARTIAL_VALIDATION_TYPES[type] = true; +}); var inputType = { @@ -16158,9 +25390,10 @@ var inputType = { * @name input[text] * * @description - * Standard HTML text input with angular data binding. + * Standard HTML text input with AngularJS data binding, inherited by most of the `input` elements. + * * - * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string} ngModel Assignable AngularJS expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Adds `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to @@ -16169,42 +25402,60 @@ var inputType = { * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user + * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of + * any length. + * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string + * that contains the regular expression body that will be converted to a regular expression + * as in the ngPattern directive. + * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} + * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. + * If the expression evaluates to a RegExp object, then this is used directly. + * If the expression evaluates to a string, then it will be converted to a RegExp + * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to + * `new RegExp('^abc$')`.
+ * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to + * start at the index of the last search's match, thus not taking the whole input value into + * account. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user * interaction with the input element. - * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input. + * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input. + * This parameter is ignored for input[type=password] controls, which will never trim the + * input. * * @example - + -
- Single word: - - Required! - - Single word only! - - text = {{text}}
- myForm.input.$valid = {{myForm.input.$valid}}
- myForm.input.$error = {{myForm.input.$error}}
- myForm.$valid = {{myForm.$valid}}
- myForm.$error.required = {{!!myForm.$error.required}}
+ + +
+ + Required! + + Single word only! +
+ text = {{example.text}}
+ myForm.input.$valid = {{myForm.input.$valid}}
+ myForm.input.$error = {{myForm.input.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
- var text = element(by.binding('text')); + var text = element(by.binding('example.text')); var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('text')); + var input = element(by.model('example.text')); it('should initialize to model', function() { expect(text.getText()).toContain('guest'); @@ -16230,66 +25481,652 @@ var inputType = { */ 'text': textInputType, - - /** - * @ngdoc input - * @name input[number] - * - * @description - * Text input with number validation and transformation. Sets the `number` validation - * error if not a valid number. - * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string=} name Property name of the form under which the control is published. - * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. - * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. - * @param {string=} required Sets `required` validation error key if the value is not entered. - * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to - * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of - * `required` when you want to data-bind to the `required` attribute. - * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than - * minlength. - * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
- Number: - - Required! - - Not valid number! - value = {{value}}
+ /** + * @ngdoc input + * @name input[date] + * + * @description + * Input with date validation and transformation. In browsers that do not yet support + * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601 + * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many + * modern browsers do not yet support this input type, it is important to provide cues to users on the + * expected input format via a placeholder or label. + * + * The model must always be a Date object, otherwise AngularJS will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. + * + * The timezone to be used to read/write the `Date` instance in the model can be defined using + * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a + * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute + * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5 + * constraint validation. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be + * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute + * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5 + * constraint validation. + * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string + * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. + * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string + * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + + + + +
+ + Required! + + Not a valid date! +
+ value = {{example.value | date: "yyyy-MM-dd"}}
myForm.input.$valid = {{myForm.input.$valid}}
myForm.input.$error = {{myForm.input.$error}}
myForm.$valid = {{myForm.$valid}}
myForm.$error.required = {{!!myForm.$error.required}}
- -
- - var value = element(by.binding('value')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('value')); + + + + var value = element(by.binding('example.value | date: "yyyy-MM-dd"')); + var valid = element(by.binding('myForm.input.$valid')); + + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (see https://github.com/angular/protractor/issues/562). + function setInput(val) { + // set the value of the element and force validation. + var scr = "var ipt = document.getElementById('exampleInput'); " + + "ipt.value = '" + val + "';" + + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; + browser.executeScript(scr); + } - it('should initialize to model', function() { - expect(value.getText()).toContain('12'); - expect(valid.getText()).toContain('true'); - }); + it('should initialize to model', function() { + expect(value.getText()).toContain('2013-10-22'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); - it('should be invalid if empty', function() { + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + + it('should be invalid if over max', function() { + setInput('2015-01-01'); + expect(value.getText()).toContain(''); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + +
+ */ + 'date': createDateInputType('date', DATE_REGEXP, + createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']), + 'yyyy-MM-dd'), + + /** + * @ngdoc input + * @name input[datetime-local] + * + * @description + * Input with datetime validation and transformation. In browsers that do not yet support + * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 + * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`. + * + * The model must always be a Date object, otherwise AngularJS will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. + * + * The timezone to be used to read/write the `Date` instance in the model can be defined using + * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. + * + * The format of the displayed time can be adjusted with the + * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions} `timeSecondsFormat` + * and `timeStripZeroSeconds`. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. + * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation + * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`). + * Note that `min` will also add native HTML5 constraint validation. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. + * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation + * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`). + * Note that `max` will also add native HTML5 constraint validation. + * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string + * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. + * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string + * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
+ + +
+ + Required! + + Not a valid date! +
+ value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}
+ myForm.input.$valid = {{myForm.input.$valid}}
+ myForm.input.$error = {{myForm.input.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
+
+
+ + var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"')); + var valid = element(by.binding('myForm.input.$valid')); + + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (https://github.com/angular/protractor/issues/562). + function setInput(val) { + // set the value of the element and force validation. + var scr = "var ipt = document.getElementById('exampleInput'); " + + "ipt.value = '" + val + "';" + + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; + browser.executeScript(scr); + } + + it('should initialize to model', function() { + expect(value.getText()).toContain('2010-12-28T14:57:00'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); + + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + + it('should be invalid if over max', function() { + setInput('2015-01-01T23:59:00'); + expect(value.getText()).toContain(''); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + +
+ */ + 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP, + createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']), + 'yyyy-MM-ddTHH:mm:ss.sss'), + + /** + * @ngdoc input + * @name input[time] + * + * @description + * Input with time validation and transformation. In browsers that do not yet support + * the HTML5 time input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 + * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a + * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`. + * + * The model must always be a Date object, otherwise AngularJS will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. + * + * The timezone to be used to read/write the `Date` instance in the model can be defined using + * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions}. By default, + * this is the timezone of the browser. + * + * The format of the displayed time can be adjusted with the + * {@link ng.directive:ngModelOptions#ngModelOptions-arguments ngModelOptions} `timeSecondsFormat` + * and `timeStripZeroSeconds`. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. + * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this + * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add + * native HTML5 constraint validation. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. + * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this + * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add + * native HTML5 constraint validation. + * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the + * `ngMin` expression evaluates to. Note that it does not set the `min` attribute. + * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the + * `ngMax` expression evaluates to. Note that it does not set the `max` attribute. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
+ + +
+ + Required! + + Not a valid date! +
+ value = {{example.value | date: "HH:mm:ss"}}
+ myForm.input.$valid = {{myForm.input.$valid}}
+ myForm.input.$error = {{myForm.input.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
+
+
+ + var value = element(by.binding('example.value | date: "HH:mm:ss"')); + var valid = element(by.binding('myForm.input.$valid')); + + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (https://github.com/angular/protractor/issues/562). + function setInput(val) { + // set the value of the element and force validation. + var scr = "var ipt = document.getElementById('exampleInput'); " + + "ipt.value = '" + val + "';" + + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; + browser.executeScript(scr); + } + + it('should initialize to model', function() { + expect(value.getText()).toContain('14:57:00'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); + + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + + it('should be invalid if over max', function() { + setInput('23:59:00'); + expect(value.getText()).toContain(''); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + +
+ */ + 'time': createDateInputType('time', TIME_REGEXP, + createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']), + 'HH:mm:ss.sss'), + + /** + * @ngdoc input + * @name input[week] + * + * @description + * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support + * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 + * week format (yyyy-W##), for example: `2013-W02`. + * + * The model must always be a Date object, otherwise AngularJS will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. + * + * The value of the resulting Date object will be set to Thursday at 00:00:00 of the requested week, + * due to ISO-8601 week numbering standards. Information on ISO's system for numbering the weeks of the + * year can be found at: https://en.wikipedia.org/wiki/ISO_8601#Week_dates + * + * The timezone to be used to read/write the `Date` instance in the model can be defined using + * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. + * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this + * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add + * native HTML5 constraint validation. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. + * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this + * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add + * native HTML5 constraint validation. + * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string + * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. + * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string + * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
+ +
+ + Required! + + Not a valid date! +
+ value = {{example.value | date: "yyyy-Www"}}
+ myForm.input.$valid = {{myForm.input.$valid}}
+ myForm.input.$error = {{myForm.input.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
+
+
+ + var value = element(by.binding('example.value | date: "yyyy-Www"')); + var valid = element(by.binding('myForm.input.$valid')); + + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (https://github.com/angular/protractor/issues/562). + function setInput(val) { + // set the value of the element and force validation. + var scr = "var ipt = document.getElementById('exampleInput'); " + + "ipt.value = '" + val + "';" + + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; + browser.executeScript(scr); + } + + it('should initialize to model', function() { + expect(value.getText()).toContain('2013-W01'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); + + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + + it('should be invalid if over max', function() { + setInput('2015-W01'); + expect(value.getText()).toContain(''); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + +
+ */ + 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'), + + /** + * @ngdoc input + * @name input[month] + * + * @description + * Input with month validation and transformation. In browsers that do not yet support + * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601 + * month format (yyyy-MM), for example: `2009-01`. + * + * The model must always be a Date object, otherwise AngularJS will throw an error. + * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string. + * If the model is not set to the first of the month, the next view to model update will set it + * to the first of the month. + * + * The timezone to be used to read/write the `Date` instance in the model can be defined using + * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. + * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this + * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add + * native HTML5 constraint validation. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. + * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this + * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add + * native HTML5 constraint validation. + * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string + * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute. + * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string + * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute. + + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
+ + +
+ + Required! + + Not a valid month! +
+ value = {{example.value | date: "yyyy-MM"}}
+ myForm.input.$valid = {{myForm.input.$valid}}
+ myForm.input.$error = {{myForm.input.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
+
+
+ + var value = element(by.binding('example.value | date: "yyyy-MM"')); + var valid = element(by.binding('myForm.input.$valid')); + + // currently protractor/webdriver does not support + // sending keys to all known HTML5 input controls + // for various browsers (https://github.com/angular/protractor/issues/562). + function setInput(val) { + // set the value of the element and force validation. + var scr = "var ipt = document.getElementById('exampleInput'); " + + "ipt.value = '" + val + "';" + + "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });"; + browser.executeScript(scr); + } + + it('should initialize to model', function() { + expect(value.getText()).toContain('2013-10'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); + + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + + it('should be invalid if over max', function() { + setInput('2015-01'); + expect(value.getText()).toContain(''); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); + +
+ */ + 'month': createDateInputType('month', MONTH_REGEXP, + createDateParser(MONTH_REGEXP, ['yyyy', 'MM']), + 'yyyy-MM'), + + /** + * @ngdoc input + * @name input[number] + * + * @description + * Text input with number validation and transformation. Sets the `number` validation + * error if not a valid number. + * + *
+ * The model must always be of type `number` otherwise AngularJS will throw an error. + * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt} + * error docs for more information and an example of how to convert your model if necessary. + *
+ * + * + * + * @knownIssue + * + * ### HTML5 constraint validation and `allowInvalid` + * + * In browsers that follow the + * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29), + * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}. + * If a non-number is entered in the input, the browser will report the value as an empty string, + * which means the view / model values in `ngModel` and subsequently the scope value + * will also be an empty string. + * + * @knownIssue + * + * ### Large numbers and `step` validation + * + * The `step` validation will not work correctly for very large numbers (e.g. 9999999999) due to + * Javascript's arithmetic limitations. If you need to handle large numbers, purpose-built + * libraries (e.g. https://github.com/MikeMcl/big.js/), can be included into AngularJS by + * {@link guide/forms#modifying-built-in-validators overwriting the validators} + * for `number` and / or `step`, or by {@link guide/forms#custom-validation applying custom validators} + * to an `input[text]` element. The source for `input[number]` type can be used as a starting + * point for both implementations. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. + * Can be interpolated. + * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. + * Can be interpolated. + * @param {string=} ngMin Like `min`, sets the `min` validation error key if the value entered is less than `ngMin`, + * but does not trigger HTML5 native validation. Takes an expression. + * @param {string=} ngMax Like `max`, sets the `max` validation error key if the value entered is greater than `ngMax`, + * but does not trigger HTML5 native validation. Takes an expression. + * @param {string=} step Sets the `step` validation error key if the value entered does not fit the `step` constraint. + * Can be interpolated. + * @param {string=} ngStep Like `step`, sets the `step` validation error key if the value entered does not fit the `ngStep` constraint, + * but does not trigger HTML5 native validation. Takes an expression. + * @param {string=} required Sets `required` validation error key if the value is not entered. + * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to + * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of + * `required` when you want to data-bind to the `required` attribute. + * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than + * minlength. + * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than + * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of + * any length. + * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string + * that contains the regular expression body that will be converted to a regular expression + * as in the ngPattern directive. + * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} + * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. + * If the expression evaluates to a RegExp object, then this is used directly. + * If the expression evaluates to a string, then it will be converted to a RegExp + * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to + * `new RegExp('^abc$')`.
+ * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to + * start at the index of the last search's match, thus not taking the whole input value into + * account. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * + * @example + + + +
+ +
+ + Required! + + Not valid number! +
+ value = {{example.value}}
+ myForm.input.$valid = {{myForm.input.$valid}}
+ myForm.input.$error = {{myForm.input.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
+
+
+ + var value = element(by.binding('example.value')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('example.value')); + + it('should initialize to model', function() { + expect(value.getText()).toContain('12'); + expect(valid.getText()).toContain('true'); + }); + + it('should be invalid if empty', function() { input.clear(); input.sendKeys(''); expect(value.getText()).toEqual('value ='); @@ -16316,7 +26153,13 @@ var inputType = { * Text input with URL validation. Sets the `url` validation error key if the content is not a * valid URL. * - * @param {string} ngModel Assignable angular expression to data-bind to. + *
+ * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex + * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify + * the built-in validators (see the {@link guide/forms Forms guide}) + *
+ * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to @@ -16325,28 +26168,45 @@ var inputType = { * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user + * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of + * any length. + * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string + * that contains the regular expression body that will be converted to a regular expression + * as in the ngPattern directive. + * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} + * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. + * If the expression evaluates to a RegExp object, then this is used directly. + * If the expression evaluates to a string, then it will be converted to a RegExp + * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to + * `new RegExp('^abc$')`.
+ * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to + * start at the index of the last search's match, thus not taking the whole input value into + * account. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user * interaction with the input element. * * @example - + -
- URL: - - Required! - - Not valid url! - text = {{text}}
+ +
- var text = element(by.binding('text')); + var text = element(by.binding('url.text')); var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('text')); + var input = element(by.model('url.text')); it('should initialize to model', function() { expect(text.getText()).toContain('http://google.com'); @@ -16392,7 +26252,15 @@ var inputType = { * Text input with email validation. Sets the `email` validation error key if not a valid email * address. * - * @param {string} ngModel Assignable angular expression to data-bind to. + *
+ * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex + * used in Chromium, which may not fulfill your app's requirements. + * If you need stricter (e.g. requiring a top-level domain), or more relaxed validation + * (e.g. allowing IPv6 address literals) you can use `ng-pattern` or + * modify the built-in validators (see the {@link guide/forms Forms guide}). + *
+ * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to @@ -16401,28 +26269,45 @@ var inputType = { * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user + * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of + * any length. + * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string + * that contains the regular expression body that will be converted to a regular expression + * as in the ngPattern directive. + * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} + * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. + * If the expression evaluates to a RegExp object, then this is used directly. + * If the expression evaluates to a string, then it will be converted to a RegExp + * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to + * `new RegExp('^abc$')`.
+ * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to + * start at the index of the last search's match, thus not taking the whole input value into + * account. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user * interaction with the input element. * * @example - + -
- Email: - - Required! - - Not valid email! - text = {{text}}
+ + +
+ + Required! + + Not valid email! +
+ text = {{email.text}}
myForm.input.$valid = {{myForm.input.$valid}}
myForm.input.$error = {{myForm.input.$error}}
myForm.$valid = {{myForm.$valid}}
@@ -16431,9 +26316,9 @@ var inputType = {
- var text = element(by.binding('text')); + var text = element(by.binding('email.text')); var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('text')); + var input = element(by.model('email.text')); it('should initialize to model', function() { expect(text.getText()).toContain('me@example.com'); @@ -16466,49 +26351,212 @@ var inputType = { * @description * HTML radio button. * - * @param {string} ngModel Assignable angular expression to data-bind to. - * @param {string} value The value to which the expression should be set when selected. + * **Note:**
+ * All inputs controlled by {@link ngModel ngModel} (including those of type `radio`) will use the + * value of their `name` attribute to determine the property under which their + * {@link ngModel.NgModelController NgModelController} will be published on the parent + * {@link form.FormController FormController}. Thus, if you use the same `name` for multiple + * inputs of a form (e.g. a group of radio inputs), only _one_ `NgModelController` will be + * published on the parent `FormController` under that name. The rest of the controllers will + * continue to work as expected, but you won't be able to access them as properties on the parent + * `FormController`. + * + *
+ *

+ * In plain HTML forms, the `name` attribute is used to identify groups of radio inputs, so + * that the browser can manage their state (checked/unchecked) based on the state of other + * inputs in the same group. + *

+ *

+ * In AngularJS forms, this is not necessary. The input's state will be updated based on the + * value of the underlying model data. + *

+ *
+ * + *
+ * If you omit the `name` attribute on a radio input, `ngModel` will automatically assign it a + * unique name. + *
+ * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string} value The value to which the `ngModel` expression should be set when selected. + * Note that `value` only supports `string` values, i.e. the scope model needs to be a string, + * too. Use `ngValue` if you need complex models (`number`, `object`, ...). * @param {string=} name Property name of the form under which the control is published. - * @param {string=} ngChange Angular expression to be executed when input changes due to user + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user * interaction with the input element. - * @param {string} ngValue Angular expression which sets the value to which the expression should - * be set when selected. + * @param {string} ngValue AngularJS expression to which `ngModel` will be be set when the radio + * is selected. Should be used instead of the `value` attribute if you need + * a non-string `ngModel` (`boolean`, `array`, ...). * * @example - + -
- Red
- Green
- Blue
- color = {{color | json}}
+ +
+
+
+ color = {{color.name | json}}
Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
it('should change state', function() { - var color = element(by.binding('color')); + var inputs = element.all(by.model('color.name')); + var color = element(by.binding('color.name')); expect(color.getText()).toContain('blue'); - element.all(by.model('color')).get(0).click(); - + inputs.get(0).click(); expect(color.getText()).toContain('red'); + + inputs.get(1).click(); + expect(color.getText()).toContain('green'); });
*/ 'radio': radioInputType, + /** + * @ngdoc input + * @name input[range] + * + * @description + * Native range input with validation and transformation. + * + * The model for the range input must always be a `Number`. + * + * IE9 and other browsers that do not support the `range` type fall back + * to a text input without any default values for `min`, `max` and `step`. Model binding, + * validation and number parsing are nevertheless supported. + * + * Browsers that support range (latest Chrome, Safari, Firefox, Edge) treat `input[range]` + * in a way that never allows the input to hold an invalid value. That means: + * - any non-numerical value is set to `(max + min) / 2`. + * - any numerical value that is less than the current min val, or greater than the current max val + * is set to the min / max val respectively. + * - additionally, the current `step` is respected, so the nearest value that satisfies a step + * is used. + * + * See the [HTML Spec on input[type=range]](https://www.w3.org/TR/html5/forms.html#range-state-(type=range)) + * for more info. + * + * This has the following consequences for AngularJS: + * + * Since the element value should always reflect the current model value, a range input + * will set the bound ngModel expression to the value that the browser has set for the + * input element. For example, in the following input ``, + * if the application sets `model.value = null`, the browser will set the input to `'50'`. + * AngularJS will then set the model to `50`, to prevent input and model value being out of sync. + * + * That means the model for range will immediately be set to `50` after `ngModel` has been + * initialized. It also means a range input can never have the required error. + * + * This does not only affect changes to the model value, but also to the values of the `min`, + * `max`, and `step` attributes. When these change in a way that will cause the browser to modify + * the input value, AngularJS will also update the model value. + * + * Automatic value adjustment also means that a range input element can never have the `required`, + * `min`, or `max` errors. + * + * However, `step` is currently only fully implemented by Firefox. Other browsers have problems + * when the step value changes dynamically - they do not adjust the element value correctly, but + * instead may set the `stepMismatch` error. If that's the case, the AngularJS will set the `step` + * error on the input, and set the model to `undefined`. + * + * Note that `input[range]` is not compatible with`ngMax`, `ngMin`, and `ngStep`, because they do + * not set the `min` and `max` attributes, which means that the browser won't automatically adjust + * the input value based on their values, and will always assume min = 0, max = 100, and step = 1. + * + * @param {string} ngModel Assignable AngularJS expression to data-bind to. + * @param {string=} name Property name of the form under which the control is published. + * @param {string=} min Sets the `min` validation to ensure that the value entered is greater + * than `min`. Can be interpolated. + * @param {string=} max Sets the `max` validation to ensure that the value entered is less than `max`. + * Can be interpolated. + * @param {string=} step Sets the `step` validation to ensure that the value entered matches the `step` + * Can be interpolated. + * @param {expression=} ngChange AngularJS expression to be executed when the ngModel value changes due + * to user interaction with the input element. + * @param {expression=} ngChecked If the expression is truthy, then the `checked` attribute will be set on the + * element. **Note** : `ngChecked` should not be used alongside `ngModel`. + * Checkout {@link ng.directive:ngChecked ngChecked} for usage. + * + * @example + + + +
+ + Model as range: +
+ Model as number:
+ Min:
+ Max:
+ value = {{value}}
+ myForm.range.$valid = {{myForm.range.$valid}}
+ myForm.range.$error = {{myForm.range.$error}} +
+
+
+ + * ## Range Input with ngMin & ngMax attributes + + * @example + + + +
+ Model as range: +
+ Model as number:
+ Min:
+ Max:
+ value = {{value}}
+ myForm.range.$valid = {{myForm.range.$valid}}
+ myForm.range.$error = {{myForm.range.$error}} +
+
+
+ + */ + 'range': rangeInputType, /** * @ngdoc input @@ -16517,40 +26565,47 @@ var inputType = { * @description * HTML checkbox. * - * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string} ngModel Assignable AngularJS expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. - * @param {string=} ngTrueValue The value to which the expression should be set when selected. - * @param {string=} ngFalseValue The value to which the expression should be set when not selected. - * @param {string=} ngChange Angular expression to be executed when input changes due to user + * @param {expression=} ngTrueValue The value to which the expression should be set when selected. + * @param {expression=} ngFalseValue The value to which the expression should be set when not selected. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user * interaction with the input element. * * @example - + -
- Value1:
- Value2:
- value1 = {{value1}}
- value2 = {{value2}}
+ +
+
+ value1 = {{checkboxModel.value1}}
+ value2 = {{checkboxModel.value2}}
it('should change state', function() { - var value1 = element(by.binding('value1')); - var value2 = element(by.binding('value2')); + var value1 = element(by.binding('checkboxModel.value1')); + var value2 = element(by.binding('checkboxModel.value2')); expect(value1.getText()).toContain('true'); expect(value2.getText()).toContain('YES'); - element(by.model('value1')).click(); - element(by.model('value2')).click(); + element(by.model('checkboxModel.value1')).click(); + element(by.model('checkboxModel.value2')).click(); expect(value1.getText()).toContain('false'); expect(value2.getText()).toContain('NO'); @@ -16567,72 +26622,69 @@ var inputType = { 'file': noop }; -// A helper function to call $setValidity and return the value / undefined, -// a pattern that is repeated a lot in the input validation logic. -function validate(ctrl, validatorName, validity, value){ - ctrl.$setValidity(validatorName, validity); - return validity ? value : undefined; +function stringBasedInputType(ctrl) { + ctrl.$formatters.push(function(value) { + return ctrl.$isEmpty(value) ? value : value.toString(); + }); } - -function addNativeHtml5Validators(ctrl, validatorName, element) { - var validity = element.prop('validity'); - if (isObject(validity)) { - var validator = function(value) { - // Don't overwrite previous validation, don't consider valueMissing to apply (ng-required can - // perform the required validation) - if (!ctrl.$error[validatorName] && (validity.badInput || validity.customError || - validity.typeMismatch) && !validity.valueMissing) { - ctrl.$setValidity(validatorName, false); - return; - } - return value; - }; - ctrl.$parsers.push(validator); - } +function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + stringBasedInputType(ctrl); } -function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { - var validity = element.prop('validity'); - // In composition mode, users are still inputing intermediate text buffer, +function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) { + var type = lowercase(element[0].type); + + // In composition mode, users are still inputting intermediate text buffer, // hold the listener until composition is done. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent if (!$sniffer.android) { var composing = false; - element.on('compositionstart', function(data) { + element.on('compositionstart', function() { composing = true; }); + // Support: IE9+ + element.on('compositionupdate', function(ev) { + // End composition when ev.data is empty string on 'compositionupdate' event. + // When the input de-focusses (e.g. by clicking away), IE triggers 'compositionupdate' + // instead of 'compositionend'. + if (isUndefined(ev.data) || ev.data === '') { + composing = false; + } + }); + element.on('compositionend', function() { composing = false; listener(); }); } - var listener = function() { + var timeout; + + var listener = function(ev) { + if (timeout) { + $browser.defer.cancel(timeout); + timeout = null; + } if (composing) return; - var value = element.val(); + var value = element.val(), + event = ev && ev.type; // By default we will trim the value // If the attribute ng-trim exists we will avoid trimming - // e.g. - if (toBoolean(attr.ngTrim || 'T')) { + // If input type is 'password', the value is never trimmed + if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) { value = trim(value); } - if (ctrl.$viewValue !== value || - // If the value is still empty/falsy, and there is no `required` error, run validators - // again. This enables HTML5 constraint validation errors to affect Angular validation - // even when the first character entered causes an error. - (validity && value === '' && !validity.valueMissing)) { - if (scope.$$phase) { - ctrl.$setViewValue(value); - } else { - scope.$apply(function() { - ctrl.$setViewValue(value); - }); - } + // If a control is suffering from bad input (due to native validators), browsers discard its + // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the + // control's value is the same empty value twice in a row. + if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) { + ctrl.$setViewValue(value, event); } }; @@ -16641,30 +26693,30 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { if ($sniffer.hasEvent('input')) { element.on('input', listener); } else { - var timeout; - - var deferListener = function() { + var deferListener = function(ev, input, origValue) { if (!timeout) { timeout = $browser.defer(function() { - listener(); timeout = null; + if (!input || input.value !== origValue) { + listener(ev); + } }); } }; - element.on('keydown', function(event) { + element.on('keydown', /** @this */ function(event) { var key = event.keyCode; // ignore // command modifiers arrows if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; - deferListener(); + deferListener(event, this, this.value); }); - // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it + // if user modifies input value using context menu in IE, we need "paste", "cut" and "drop" events to catch it if ($sniffer.hasEvent('paste')) { - element.on('paste cut', deferListener); + element.on('paste cut drop', deferListener); } } @@ -16672,178 +26724,650 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { // or form autocomplete on newer browser, we need "change" event to catch it element.on('change', listener); + // Some native input types (date-family) have the ability to change validity without + // firing any input/change events. + // For these event types, when native validators are present and the browser supports the type, + // check for validity changes on various DOM events. + if (PARTIAL_VALIDATION_TYPES[type] && ctrl.$$hasNativeValidators && type === attr.type) { + element.on(PARTIAL_VALIDATION_EVENTS, /** @this */ function(ev) { + if (!timeout) { + var validity = this[VALIDITY_STATE_PROPERTY]; + var origBadInput = validity.badInput; + var origTypeMismatch = validity.typeMismatch; + timeout = $browser.defer(function() { + timeout = null; + if (validity.badInput !== origBadInput || validity.typeMismatch !== origTypeMismatch) { + listener(ev); + } + }); + } + }); + } + ctrl.$render = function() { - element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue); + // Workaround for Firefox validation #12102. + var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue; + if (element.val() !== value) { + element.val(value); + } }; +} - // pattern validator - var pattern = attr.ngPattern, - patternValidator, - match; +function weekParser(isoWeek, existingDate) { + if (isDate(isoWeek)) { + return isoWeek; + } - if (pattern) { - var validateRegex = function(regexp, value) { - return validate(ctrl, 'pattern', ctrl.$isEmpty(value) || regexp.test(value), value); - }; - match = pattern.match(/^\/(.*)\/([gim]*)$/); - if (match) { - pattern = new RegExp(match[1], match[2]); - patternValidator = function(value) { - return validateRegex(pattern, value); - }; - } else { - patternValidator = function(value) { - var patternObj = scope.$eval(pattern); + if (isString(isoWeek)) { + WEEK_REGEXP.lastIndex = 0; + var parts = WEEK_REGEXP.exec(isoWeek); + if (parts) { + var year = +parts[1], + week = +parts[2], + hours = 0, + minutes = 0, + seconds = 0, + milliseconds = 0, + firstThurs = getFirstThursdayOfYear(year), + addDays = (week - 1) * 7; + + if (existingDate) { + hours = existingDate.getHours(); + minutes = existingDate.getMinutes(); + seconds = existingDate.getSeconds(); + milliseconds = existingDate.getMilliseconds(); + } - if (!patternObj || !patternObj.test) { - throw minErr('ngPattern')('noregexp', - 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern, - patternObj, startingTag(element)); - } - return validateRegex(patternObj, value); - }; + return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds); } - - ctrl.$formatters.push(patternValidator); - ctrl.$parsers.push(patternValidator); } - // min length validator - if (attr.ngMinlength) { - var minlength = int(attr.ngMinlength); - var minLengthValidator = function(value) { - return validate(ctrl, 'minlength', ctrl.$isEmpty(value) || value.length >= minlength, value); - }; + return NaN; +} - ctrl.$parsers.push(minLengthValidator); - ctrl.$formatters.push(minLengthValidator); - } +function createDateParser(regexp, mapping) { + return function(iso, previousDate) { + var parts, map; - // max length validator - if (attr.ngMaxlength) { - var maxlength = int(attr.ngMaxlength); - var maxLengthValidator = function(value) { - return validate(ctrl, 'maxlength', ctrl.$isEmpty(value) || value.length <= maxlength, value); - }; + if (isDate(iso)) { + return iso; + } - ctrl.$parsers.push(maxLengthValidator); - ctrl.$formatters.push(maxLengthValidator); - } + if (isString(iso)) { + // When a date is JSON'ified to wraps itself inside of an extra + // set of double quotes. This makes the date parsing code unable + // to match the date string and parse it as a date. + if (iso.charAt(0) === '"' && iso.charAt(iso.length - 1) === '"') { + iso = iso.substring(1, iso.length - 1); + } + if (ISO_DATE_REGEXP.test(iso)) { + return new Date(iso); + } + regexp.lastIndex = 0; + parts = regexp.exec(iso); + + if (parts) { + parts.shift(); + if (previousDate) { + map = { + yyyy: previousDate.getFullYear(), + MM: previousDate.getMonth() + 1, + dd: previousDate.getDate(), + HH: previousDate.getHours(), + mm: previousDate.getMinutes(), + ss: previousDate.getSeconds(), + sss: previousDate.getMilliseconds() / 1000 + }; + } else { + map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 }; + } + + forEach(parts, function(part, index) { + if (index < mapping.length) { + map[mapping[index]] = +part; + } + }); + + var date = new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0); + if (map.yyyy < 100) { + // In the constructor, 2-digit years map to 1900-1999. + // Use `setFullYear()` to set the correct year. + date.setFullYear(map.yyyy); + } + + return date; + } + } + + return NaN; + }; } -function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { - textInputType(scope, element, attr, ctrl, $sniffer, $browser); +function createDateInputType(type, regexp, parseDate, format) { + return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) { + badInputChecker(scope, element, attr, ctrl, type); + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); - ctrl.$parsers.push(function(value) { - var empty = ctrl.$isEmpty(value); - if (empty || NUMBER_REGEXP.test(value)) { - ctrl.$setValidity('number', true); - return value === '' ? null : (empty ? value : parseFloat(value)); - } else { - ctrl.$setValidity('number', false); + var isTimeType = type === 'time' || type === 'datetimelocal'; + var previousDate; + var previousTimezone; + + ctrl.$parsers.push(function(value) { + if (ctrl.$isEmpty(value)) return null; + + if (regexp.test(value)) { + // Note: We cannot read ctrl.$modelValue, as there might be a different + // parser/formatter in the processing chain so that the model + // contains some different data format! + return parseDateAndConvertTimeZoneToLocal(value, previousDate); + } + ctrl.$$parserName = type; return undefined; + }); + + ctrl.$formatters.push(function(value) { + if (value && !isDate(value)) { + throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value); + } + if (isValidDate(value)) { + previousDate = value; + var timezone = ctrl.$options.getOption('timezone'); + + if (timezone) { + previousTimezone = timezone; + previousDate = convertTimezoneToLocal(previousDate, timezone, true); + } + + return formatter(value, timezone); + } else { + previousDate = null; + previousTimezone = null; + return ''; + } + }); + + if (isDefined(attr.min) || attr.ngMin) { + var minVal = attr.min || $parse(attr.ngMin)(scope); + var parsedMinVal = parseObservedDateValue(minVal); + + ctrl.$validators.min = function(value) { + return !isValidDate(value) || isUndefined(parsedMinVal) || parseDate(value) >= parsedMinVal; + }; + attr.$observe('min', function(val) { + if (val !== minVal) { + parsedMinVal = parseObservedDateValue(val); + minVal = val; + ctrl.$validate(); + } + }); } - }); - addNativeHtml5Validators(ctrl, 'number', element); + if (isDefined(attr.max) || attr.ngMax) { + var maxVal = attr.max || $parse(attr.ngMax)(scope); + var parsedMaxVal = parseObservedDateValue(maxVal); + + ctrl.$validators.max = function(value) { + return !isValidDate(value) || isUndefined(parsedMaxVal) || parseDate(value) <= parsedMaxVal; + }; + attr.$observe('max', function(val) { + if (val !== maxVal) { + parsedMaxVal = parseObservedDateValue(val); + maxVal = val; + ctrl.$validate(); + } + }); + } + + function isValidDate(value) { + // Invalid Date: getTime() returns NaN + return value && !(value.getTime && value.getTime() !== value.getTime()); + } + + function parseObservedDateValue(val) { + return isDefined(val) && !isDate(val) ? parseDateAndConvertTimeZoneToLocal(val) || undefined : val; + } + + function parseDateAndConvertTimeZoneToLocal(value, previousDate) { + var timezone = ctrl.$options.getOption('timezone'); + + if (previousTimezone && previousTimezone !== timezone) { + // If the timezone has changed, adjust the previousDate to the default timezone + // so that the new date is converted with the correct timezone offset + previousDate = addDateMinutes(previousDate, timezoneToOffset(previousTimezone)); + } + + var parsedDate = parseDate(value, previousDate); + + if (!isNaN(parsedDate) && timezone) { + parsedDate = convertTimezoneToLocal(parsedDate, timezone); + } + return parsedDate; + } + + function formatter(value, timezone) { + var targetFormat = format; + + if (isTimeType && isString(ctrl.$options.getOption('timeSecondsFormat'))) { + targetFormat = format + .replace('ss.sss', ctrl.$options.getOption('timeSecondsFormat')) + .replace(/:$/, ''); + } + + var formatted = $filter('date')(value, targetFormat, timezone); + + if (isTimeType && ctrl.$options.getOption('timeStripZeroSeconds')) { + formatted = formatted.replace(/(?::00)?(?:\.000)?$/, ''); + } + + return formatted; + } + }; +} + +function badInputChecker(scope, element, attr, ctrl, parserName) { + var node = element[0]; + var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity); + if (nativeValidation) { + ctrl.$parsers.push(function(value) { + var validity = element.prop(VALIDITY_STATE_PROPERTY) || {}; + if (validity.badInput || validity.typeMismatch) { + ctrl.$$parserName = parserName; + return undefined; + } + + return value; + }); + } +} + +function numberFormatterParser(ctrl) { + ctrl.$parsers.push(function(value) { + if (ctrl.$isEmpty(value)) return null; + if (NUMBER_REGEXP.test(value)) return parseFloat(value); + + ctrl.$$parserName = 'number'; + return undefined; + }); ctrl.$formatters.push(function(value) { - return ctrl.$isEmpty(value) ? '' : '' + value; + if (!ctrl.$isEmpty(value)) { + if (!isNumber(value)) { + throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value); + } + value = value.toString(); + } + return value; }); +} + +function parseNumberAttrVal(val) { + if (isDefined(val) && !isNumber(val)) { + val = parseFloat(val); + } + return !isNumberNaN(val) ? val : undefined; +} + +function isNumberInteger(num) { + // See http://stackoverflow.com/questions/14636536/how-to-check-if-a-variable-is-an-integer-in-javascript#14794066 + // (minus the assumption that `num` is a number) + + // eslint-disable-next-line no-bitwise + return (num | 0) === num; +} + +function countDecimals(num) { + var numString = num.toString(); + var decimalSymbolIndex = numString.indexOf('.'); + + if (decimalSymbolIndex === -1) { + if (-1 < num && num < 1) { + // It may be in the exponential notation format (`1e-X`) + var match = /e-(\d+)$/.exec(numString); + + if (match) { + return Number(match[1]); + } + } + + return 0; + } + + return numString.length - decimalSymbolIndex - 1; +} + +function isValidForStep(viewValue, stepBase, step) { + // At this point `stepBase` and `step` are expected to be non-NaN values + // and `viewValue` is expected to be a valid stringified number. + var value = Number(viewValue); + + var isNonIntegerValue = !isNumberInteger(value); + var isNonIntegerStepBase = !isNumberInteger(stepBase); + var isNonIntegerStep = !isNumberInteger(step); - if (attr.min) { - var minValidator = function(value) { - var min = parseFloat(attr.min); - return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value); + // Due to limitations in Floating Point Arithmetic (e.g. `0.3 - 0.2 !== 0.1` or + // `0.5 % 0.1 !== 0`), we need to convert all numbers to integers. + if (isNonIntegerValue || isNonIntegerStepBase || isNonIntegerStep) { + var valueDecimals = isNonIntegerValue ? countDecimals(value) : 0; + var stepBaseDecimals = isNonIntegerStepBase ? countDecimals(stepBase) : 0; + var stepDecimals = isNonIntegerStep ? countDecimals(step) : 0; + + var decimalCount = Math.max(valueDecimals, stepBaseDecimals, stepDecimals); + var multiplier = Math.pow(10, decimalCount); + + value = value * multiplier; + stepBase = stepBase * multiplier; + step = step * multiplier; + + if (isNonIntegerValue) value = Math.round(value); + if (isNonIntegerStepBase) stepBase = Math.round(stepBase); + if (isNonIntegerStep) step = Math.round(step); + } + + return (value - stepBase) % step === 0; +} + +function numberInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) { + badInputChecker(scope, element, attr, ctrl, 'number'); + numberFormatterParser(ctrl); + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + + var parsedMinVal; + + if (isDefined(attr.min) || attr.ngMin) { + var minVal = attr.min || $parse(attr.ngMin)(scope); + parsedMinVal = parseNumberAttrVal(minVal); + + ctrl.$validators.min = function(modelValue, viewValue) { + return ctrl.$isEmpty(viewValue) || isUndefined(parsedMinVal) || viewValue >= parsedMinVal; }; - ctrl.$parsers.push(minValidator); - ctrl.$formatters.push(minValidator); + attr.$observe('min', function(val) { + if (val !== minVal) { + parsedMinVal = parseNumberAttrVal(val); + minVal = val; + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); + } + }); } - if (attr.max) { - var maxValidator = function(value) { - var max = parseFloat(attr.max); - return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value); + if (isDefined(attr.max) || attr.ngMax) { + var maxVal = attr.max || $parse(attr.ngMax)(scope); + var parsedMaxVal = parseNumberAttrVal(maxVal); + + ctrl.$validators.max = function(modelValue, viewValue) { + return ctrl.$isEmpty(viewValue) || isUndefined(parsedMaxVal) || viewValue <= parsedMaxVal; }; - ctrl.$parsers.push(maxValidator); - ctrl.$formatters.push(maxValidator); + attr.$observe('max', function(val) { + if (val !== maxVal) { + parsedMaxVal = parseNumberAttrVal(val); + maxVal = val; + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); + } + }); } - ctrl.$formatters.push(function(value) { - return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value); - }); -} + if (isDefined(attr.step) || attr.ngStep) { + var stepVal = attr.step || $parse(attr.ngStep)(scope); + var parsedStepVal = parseNumberAttrVal(stepVal); -function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { - textInputType(scope, element, attr, ctrl, $sniffer, $browser); + ctrl.$validators.step = function(modelValue, viewValue) { + return ctrl.$isEmpty(viewValue) || isUndefined(parsedStepVal) || + isValidForStep(viewValue, parsedMinVal || 0, parsedStepVal); + }; - var urlValidator = function(value) { - return validate(ctrl, 'url', ctrl.$isEmpty(value) || URL_REGEXP.test(value), value); - }; + attr.$observe('step', function(val) { + // TODO(matsko): implement validateLater to reduce number of validations + if (val !== stepVal) { + parsedStepVal = parseNumberAttrVal(val); + stepVal = val; + ctrl.$validate(); + } + + }); - ctrl.$formatters.push(urlValidator); - ctrl.$parsers.push(urlValidator); + } } -function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { - textInputType(scope, element, attr, ctrl, $sniffer, $browser); +function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) { + badInputChecker(scope, element, attr, ctrl, 'range'); + numberFormatterParser(ctrl); + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + + var supportsRange = ctrl.$$hasNativeValidators && element[0].type === 'range', + minVal = supportsRange ? 0 : undefined, + maxVal = supportsRange ? 100 : undefined, + stepVal = supportsRange ? 1 : undefined, + validity = element[0].validity, + hasMinAttr = isDefined(attr.min), + hasMaxAttr = isDefined(attr.max), + hasStepAttr = isDefined(attr.step); + + var originalRender = ctrl.$render; + + ctrl.$render = supportsRange && isDefined(validity.rangeUnderflow) && isDefined(validity.rangeOverflow) ? + //Browsers that implement range will set these values automatically, but reading the adjusted values after + //$render would cause the min / max validators to be applied with the wrong value + function rangeRender() { + originalRender(); + ctrl.$setViewValue(element.val()); + } : + originalRender; + + if (hasMinAttr) { + minVal = parseNumberAttrVal(attr.min); + + ctrl.$validators.min = supportsRange ? + // Since all browsers set the input to a valid value, we don't need to check validity + function noopMinValidator() { return true; } : + // non-support browsers validate the min val + function minValidator(modelValue, viewValue) { + return ctrl.$isEmpty(viewValue) || isUndefined(minVal) || viewValue >= minVal; + }; + + setInitialValueAndObserver('min', minChange); + } + + if (hasMaxAttr) { + maxVal = parseNumberAttrVal(attr.max); + + ctrl.$validators.max = supportsRange ? + // Since all browsers set the input to a valid value, we don't need to check validity + function noopMaxValidator() { return true; } : + // non-support browsers validate the max val + function maxValidator(modelValue, viewValue) { + return ctrl.$isEmpty(viewValue) || isUndefined(maxVal) || viewValue <= maxVal; + }; - var emailValidator = function(value) { - return validate(ctrl, 'email', ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value), value); + setInitialValueAndObserver('max', maxChange); + } + + if (hasStepAttr) { + stepVal = parseNumberAttrVal(attr.step); + + ctrl.$validators.step = supportsRange ? + function nativeStepValidator() { + // Currently, only FF implements the spec on step change correctly (i.e. adjusting the + // input element value to a valid value). It's possible that other browsers set the stepMismatch + // validity error instead, so we can at least report an error in that case. + return !validity.stepMismatch; + } : + // ngStep doesn't set the setp attr, so the browser doesn't adjust the input value as setting step would + function stepValidator(modelValue, viewValue) { + return ctrl.$isEmpty(viewValue) || isUndefined(stepVal) || + isValidForStep(viewValue, minVal || 0, stepVal); + }; + + setInitialValueAndObserver('step', stepChange); + } + + function setInitialValueAndObserver(htmlAttrName, changeFn) { + // interpolated attributes set the attribute value only after a digest, but we need the + // attribute value when the input is first rendered, so that the browser can adjust the + // input value based on the min/max value + element.attr(htmlAttrName, attr[htmlAttrName]); + var oldVal = attr[htmlAttrName]; + attr.$observe(htmlAttrName, function wrappedObserver(val) { + if (val !== oldVal) { + oldVal = val; + changeFn(val); + } + }); + } + + function minChange(val) { + minVal = parseNumberAttrVal(val); + // ignore changes before model is initialized + if (isNumberNaN(ctrl.$modelValue)) { + return; + } + + if (supportsRange) { + var elVal = element.val(); + // IE11 doesn't set the el val correctly if the minVal is greater than the element value + if (minVal > elVal) { + elVal = minVal; + element.val(elVal); + } + ctrl.$setViewValue(elVal); + } else { + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); + } + } + + function maxChange(val) { + maxVal = parseNumberAttrVal(val); + // ignore changes before model is initialized + if (isNumberNaN(ctrl.$modelValue)) { + return; + } + + if (supportsRange) { + var elVal = element.val(); + // IE11 doesn't set the el val correctly if the maxVal is less than the element value + if (maxVal < elVal) { + element.val(maxVal); + // IE11 and Chrome don't set the value to the minVal when max < min + elVal = maxVal < minVal ? minVal : maxVal; + } + ctrl.$setViewValue(elVal); + } else { + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); + } + } + + function stepChange(val) { + stepVal = parseNumberAttrVal(val); + // ignore changes before model is initialized + if (isNumberNaN(ctrl.$modelValue)) { + return; + } + + // Some browsers don't adjust the input value correctly, but set the stepMismatch error + if (!supportsRange) { + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); + } else if (ctrl.$viewValue !== element.val()) { + ctrl.$setViewValue(element.val()); + } + } +} + +function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { + // Note: no badInputChecker here by purpose as `url` is only a validation + // in browsers, i.e. we can always read out input.value even if it is not valid! + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + stringBasedInputType(ctrl); + + ctrl.$validators.url = function(modelValue, viewValue) { + var value = modelValue || viewValue; + return ctrl.$isEmpty(value) || URL_REGEXP.test(value); }; +} - ctrl.$formatters.push(emailValidator); - ctrl.$parsers.push(emailValidator); +function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { + // Note: no badInputChecker here by purpose as `url` is only a validation + // in browsers, i.e. we can always read out input.value even if it is not valid! + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + stringBasedInputType(ctrl); + + ctrl.$validators.email = function(modelValue, viewValue) { + var value = modelValue || viewValue; + return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value); + }; } function radioInputType(scope, element, attr, ctrl) { + var doTrim = !attr.ngTrim || trim(attr.ngTrim) !== 'false'; // make the name unique, if not defined if (isUndefined(attr.name)) { element.attr('name', nextUid()); } - element.on('click', function() { + var listener = function(ev) { + var value; if (element[0].checked) { - scope.$apply(function() { - ctrl.$setViewValue(attr.value); - }); + value = attr.value; + if (doTrim) { + value = trim(value); + } + ctrl.$setViewValue(value, ev && ev.type); } - }); + }; + + element.on('change', listener); ctrl.$render = function() { var value = attr.value; - element[0].checked = (value == ctrl.$viewValue); + if (doTrim) { + value = trim(value); + } + element[0].checked = (value === ctrl.$viewValue); }; attr.$observe('value', ctrl.$render); } -function checkboxInputType(scope, element, attr, ctrl) { - var trueValue = attr.ngTrueValue, - falseValue = attr.ngFalseValue; +function parseConstantExpr($parse, context, name, expression, fallback) { + var parseFn; + if (isDefined(expression)) { + parseFn = $parse(expression); + if (!parseFn.constant) { + throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' + + '`{1}`.', name, expression); + } + return parseFn(context); + } + return fallback; +} + +function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) { + var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true); + var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false); - if (!isString(trueValue)) trueValue = true; - if (!isString(falseValue)) falseValue = false; + var listener = function(ev) { + ctrl.$setViewValue(element[0].checked, ev && ev.type); + }; - element.on('click', function() { - scope.$apply(function() { - ctrl.$setViewValue(element[0].checked); - }); - }); + element.on('change', listener); ctrl.$render = function() { element[0].checked = ctrl.$viewValue; }; - // Override the standard `$isEmpty` because a value of `false` means empty in a checkbox. + // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false` + // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert + // it to a boolean. ctrl.$isEmpty = function(value) { - return value !== trueValue; + return value === false; }; ctrl.$formatters.push(function(value) { - return value === trueValue; + return equals(value, trueValue); }); ctrl.$parsers.push(function(value) { @@ -16858,11 +27382,11 @@ function checkboxInputType(scope, element, attr, ctrl) { * @restrict E * * @description - * HTML textarea element control with angular data-binding. The data-binding and validation + * HTML textarea element control with AngularJS data-binding. The data-binding and validation * properties of this element are exactly the same as those of the * {@link ng.directive:input input element}. * - * @param {string} ngModel Assignable angular expression to data-bind to. + * @param {string} ngModel Assignable AngularJS expression to data-bind to. * @param {string=} name Property name of the form under which the control is published. * @param {string=} required Sets `required` validation error key if the value is not entered. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to @@ -16871,12 +27395,34 @@ function checkboxInputType(scope, element, attr, ctrl) { * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than * minlength. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than - * maxlength. - * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the - * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for - * patterns defined as scope expressions. - * @param {string=} ngChange Angular expression to be executed when input changes due to user + * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any + * length. + * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel {@link ngModel.NgModelController#$viewValue $viewValue} + * does not match a RegExp found by evaluating the AngularJS expression given in the attribute value. + * If the expression evaluates to a RegExp object, then this is used directly. + * If the expression evaluates to a string, then it will be converted to a RegExp + * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to + * `new RegExp('^abc$')`.
+ * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to + * start at the index of the last search's match, thus not taking the whole input value into + * account. + * @param {string=} ngChange AngularJS expression to be executed when input changes due to user * interaction with the input element. + * @param {boolean=} [ngTrim=true] If set to false AngularJS will not automatically trim the input. + * + * @knownIssue + * + * When specifying the `placeholder` attribute of ` - -
- - it('should data-bind and become invalid', function() { - if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') { - // SafariDriver can't handle contenteditable - // and Firefox driver can't clear contenteditables very well - return; - } - var contentEditable = element(by.css('[contenteditable]')); - var content = 'Change me!'; - - expect(contentEditable.getText()).toEqual(content); - - contentEditable.clear(); - contentEditable.sendKeys(protractor.Key.BACK_SPACE); - expect(contentEditable.getText()).toEqual(''); - expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/); - }); - - *
- * - * + it('should bind the values to the inputs', function() { + element.all(by.model('my.favorite')).get(0).click(); + expect(favorite.getText()).toContain('pizza'); + }); +
+
*/ -var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', - function($scope, $exceptionHandler, $attr, $element, $parse, $animate) { - this.$viewValue = Number.NaN; - this.$modelValue = Number.NaN; - this.$parsers = []; - this.$formatters = []; - this.$viewChangeListeners = []; - this.$pristine = true; - this.$dirty = false; - this.$valid = true; - this.$invalid = false; - this.$name = $attr.name; - - var ngModelGet = $parse($attr.ngModel), - ngModelSet = ngModelGet.assign; - - if (!ngModelSet) { - throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}", - $attr.ngModel, startingTag($element)); - } - - /** - * @ngdoc method - * @name ngModel.NgModelController#$render - * - * @description - * Called when the view needs to be updated. It is expected that the user of the ng-model - * directive will implement this method. - */ - this.$render = noop; - +var ngValueDirective = function() { /** - * @ngdoc method - * @name ngModel.NgModelController#$isEmpty - * - * @description - * This is called when we need to determine if the value of the input is empty. - * - * For instance, the required directive does this to work out if the input has data or not. - * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. - * - * You can override this for input directives whose concept of being empty is different to the - * default. The `checkboxInputType` directive does this because in its case a value of `false` - * implies empty. - * - * @param {*} value Reference to check. - * @returns {boolean} True if `value` is empty. + * inputs use the value attribute as their default value if the value property is not set. + * Once the value property has been set (by adding input), it will not react to changes to + * the value attribute anymore. Setting both attribute and property fixes this behavior, and + * makes it possible to use ngValue as a sort of one-way bind. */ - this.$isEmpty = function(value) { - return isUndefined(value) || value === '' || value === null || value !== value; - }; - - var parentForm = $element.inheritedData('$formController') || nullFormCtrl, - invalidCount = 0, // used to easily determine if we are valid - $error = this.$error = {}; // keep invalid keys here - - - // Setup initial state of the control - $element.addClass(PRISTINE_CLASS); - toggleValidCss(true); - - // convenience method for easy toggling of classes - function toggleValidCss(isValid, validationErrorKey) { - validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; - $animate.removeClass($element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey); - $animate.addClass($element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey); + function updateElementValue(element, attr, value) { + // Support: IE9 only + // In IE9 values are converted to string (e.g. `input.value = null` results in `input.value === 'null'`). + var propValue = isDefined(value) ? value : (msie === 9) ? '' : null; + element.prop('value', propValue); + attr.$set('value', value); } - /** - * @ngdoc method - * @name ngModel.NgModelController#$setValidity - * - * @description - * Change the validity state, and notifies the form when the control changes validity. (i.e. it - * does not notify form if given validator is already marked as invalid). - * - * This method should be called by validators - i.e. the parser or formatter functions. - * - * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign - * to `$error[validationErrorKey]=isValid` so that it is available for data-binding. - * The `validationErrorKey` should be in camelCase and will get converted into dash-case - * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` - * class and can be bound to as `{{someForm.someControl.$error.myError}}` . - * @param {boolean} isValid Whether the current state is valid (true) or invalid (false). - */ - this.$setValidity = function(validationErrorKey, isValid) { - // Purposeful use of ! here to cast isValid to boolean in case it is undefined - // jshint -W018 - if ($error[validationErrorKey] === !isValid) return; - // jshint +W018 - - if (isValid) { - if ($error[validationErrorKey]) invalidCount--; - if (!invalidCount) { - toggleValidCss(true); - this.$valid = true; - this.$invalid = false; + return { + restrict: 'A', + priority: 100, + compile: function(tpl, tplAttr) { + if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { + return function ngValueConstantLink(scope, elm, attr) { + var value = scope.$eval(attr.ngValue); + updateElementValue(elm, attr, value); + }; + } else { + return function ngValueLink(scope, elm, attr) { + scope.$watch(attr.ngValue, function valueWatchAction(value) { + updateElementValue(elm, attr, value); + }); + }; } - } else { - toggleValidCss(false); - this.$invalid = true; - this.$valid = false; - invalidCount++; } - - $error[validationErrorKey] = !isValid; - toggleValidCss(isValid, validationErrorKey); - - parentForm.$setValidity(validationErrorKey, isValid, this); - }; - - /** - * @ngdoc method - * @name ngModel.NgModelController#$setPristine - * - * @description - * Sets the control to its pristine state. - * - * This method can be called to remove the 'ng-dirty' class and set the control to its pristine - * state (ng-pristine class). - */ - this.$setPristine = function () { - this.$dirty = false; - this.$pristine = true; - $animate.removeClass($element, DIRTY_CLASS); - $animate.addClass($element, PRISTINE_CLASS); }; +}; - /** - * @ngdoc method - * @name ngModel.NgModelController#$setViewValue - * - * @description - * Update the view value. - * - * This method should be called when the view value changes, typically from within a DOM event handler. - * For example {@link ng.directive:input input} and - * {@link ng.directive:select select} directives call it. - * - * It will update the $viewValue, then pass this value through each of the functions in `$parsers`, - * which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to - * `$modelValue` and the **expression** specified in the `ng-model` attribute. - * - * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called. - * - * Note that calling this function does not trigger a `$digest`. - * - * @param {string} value Value from the view. - */ - this.$setViewValue = function(value) { - this.$viewValue = value; - - // change to dirty - if (this.$pristine) { - this.$dirty = true; - this.$pristine = false; - $animate.removeClass($element, PRISTINE_CLASS); - $animate.addClass($element, DIRTY_CLASS); - parentForm.$setDirty(); - } - - forEach(this.$parsers, function(fn) { - value = fn(value); - }); +/** + * @ngdoc directive + * @name ngBind + * @restrict AC + * + * @description + * The `ngBind` attribute tells AngularJS to replace the text content of the specified HTML element + * with the value of a given expression, and to update the text content when the value of that + * expression changes. + * + * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like + * `{{ expression }}` which is similar but less verbose. + * + * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily + * displayed by the browser in its raw state before AngularJS compiles it. Since `ngBind` is an + * element attribute, it makes the bindings invisible to the user while the page is loading. + * + * An alternative solution to this problem would be using the + * {@link ng.directive:ngCloak ngCloak} directive. + * + * + * @element ANY + * @param {expression} ngBind {@link guide/expression Expression} to evaluate. + * + * @example + * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. + + + +
+
+ Hello ! +
+
+ + it('should check ng-bind', function() { + var nameInput = element(by.model('name')); - if (this.$modelValue !== value) { - this.$modelValue = value; - ngModelSet($scope, value); - forEach(this.$viewChangeListeners, function(listener) { - try { - listener(); - } catch(e) { - $exceptionHandler(e); - } - }); + expect(element(by.binding('name')).getText()).toBe('Whirled'); + nameInput.clear(); + nameInput.sendKeys('world'); + expect(element(by.binding('name')).getText()).toBe('world'); + }); + +
+ */ +var ngBindDirective = ['$compile', function($compile) { + return { + restrict: 'AC', + compile: function ngBindCompile(templateElement) { + $compile.$$addBindingClass(templateElement); + return function ngBindLink(scope, element, attr) { + $compile.$$addBindingInfo(element, attr.ngBind); + element = element[0]; + scope.$watch(attr.ngBind, function ngBindWatchAction(value) { + element.textContent = stringify(value); + }); + }; } }; - - // model -> value - var ctrl = this; - - $scope.$watch(function ngModelWatch() { - var value = ngModelGet($scope); - - // if scope model value and ngModel value are out of sync - if (ctrl.$modelValue !== value) { - - var formatters = ctrl.$formatters, - idx = formatters.length; - - ctrl.$modelValue = value; - while(idx--) { - value = formatters[idx](value); - } - - if (ctrl.$viewValue !== value) { - ctrl.$viewValue = value; - ctrl.$render(); - } - } - - return value; - }); }]; /** * @ngdoc directive - * @name ngModel - * - * @element input + * @name ngBindTemplate * * @description - * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a - * property on the scope using {@link ngModel.NgModelController NgModelController}, - * which is created and exposed by this directive. + * The `ngBindTemplate` directive specifies that the element + * text content should be replaced with the interpolation of the template + * in the `ngBindTemplate` attribute. + * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` + * expressions. This directive is needed since some HTML elements + * (such as TITLE and OPTION) cannot contain SPAN elements. * - * `ngModel` is responsible for: + * @element ANY + * @param {string} ngBindTemplate template of form + * {{ expression }} to eval. * - * - Binding the view into the model, which other directives such as `input`, `textarea` or `select` - * require. - * - Providing validation behavior (i.e. required, number, email, url). - * - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors). - * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`) including animations. - * - Registering the control with its parent {@link ng.directive:form form}. - * - * Note: `ngModel` will try to bind to the property given by evaluating the expression on the - * current scope. If the property doesn't already exist on this scope, it will be created - * implicitly and added to the scope. - * - * For best practices on using `ngModel`, see: - * - * - [https://github.com/angular/angular.js/wiki/Understanding-Scopes] - * - * For basic examples, how to use `ngModel`, see: - * - * - {@link ng.directive:input input} - * - {@link input[text] text} - * - {@link input[checkbox] checkbox} - * - {@link input[radio] radio} - * - {@link input[number] number} - * - {@link input[email] email} - * - {@link input[url] url} - * - {@link ng.directive:select select} - * - {@link ng.directive:textarea textarea} - * - * # CSS classes - * The following CSS classes are added and removed on the associated input/select/textarea element - * depending on the validity of the model. - * - * - `ng-valid` is set if the model is valid. - * - `ng-invalid` is set if the model is invalid. - * - `ng-pristine` is set if the model is pristine. - * - `ng-dirty` is set if the model is dirty. - * - * Keep in mind that ngAnimate can detect each of these classes when added and removed. + * @example + * Try it here: enter text in text box and watch the greeting change. + + + +
+
+
+

+       
+
+ + it('should check ng-bind', function() { + var salutationElem = element(by.binding('salutation')); + var salutationInput = element(by.model('salutation')); + var nameInput = element(by.model('name')); + + expect(salutationElem.getText()).toBe('Hello World!'); + + salutationInput.clear(); + salutationInput.sendKeys('Greetings'); + nameInput.clear(); + nameInput.sendKeys('user'); + + expect(salutationElem.getText()).toBe('Greetings user!'); + }); + +
+ */ +var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) { + return { + compile: function ngBindTemplateCompile(templateElement) { + $compile.$$addBindingClass(templateElement); + return function ngBindTemplateLink(scope, element, attr) { + var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); + $compile.$$addBindingInfo(element, interpolateFn.expressions); + element = element[0]; + attr.$observe('ngBindTemplate', function(value) { + element.textContent = isUndefined(value) ? '' : value; + }); + }; + } + }; +}]; + + +/** + * @ngdoc directive + * @name ngBindHtml * - * ## Animation Hooks + * @description + * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default, + * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service. + * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link + * ngSanitize} in your module's dependencies (not in core AngularJS). In order to use {@link ngSanitize} + * in your module's dependencies, you need to include "angular-sanitize.js" in your application. * - * Animations within models are triggered when any of the associated CSS classes are added and removed - * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`, - * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself. - * The animations that are triggered within ngModel are similar to how they work in ngClass and - * animations can be hooked into using CSS transitions, keyframes as well as JS animations. + * You may also bypass sanitization for values you know are safe. To do so, bind to + * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example + * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}. * - * The following example shows a simple way to utilize CSS transitions to style an input element - * that has been rendered as invalid after it has been validated: + * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you + * will have an exception (instead of an exploit.) * - *
- * //be sure to include ngAnimate as a module to hook into more
- * //advanced animations
- * .my-input {
- *   transition:0.5s linear all;
- *   background: white;
- * }
- * .my-input.ng-invalid {
- *   background: red;
- *   color:white;
- * }
- * 
+ * @element ANY + * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. * * @example - * + + - - - Update input to see transitions when valid/invalid. - Integer is a valid value. -
- -
+
+

+
- *
+ + + angular.module('bindHtmlExample', ['ngSanitize']) + .controller('ExampleController', ['$scope', function($scope) { + $scope.myHTML = + 'I am an HTMLstring with ' + + 'links! and other stuff'; + }]); + + + + it('should check ng-bind-html', function() { + expect(element(by.binding('myHTML')).getText()).toBe( + 'I am an HTMLstring with links! and other stuff'); + }); + +
*/ -var ngModelDirective = function() { +var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) { return { - require: ['ngModel', '^?form'], - controller: NgModelController, - link: function(scope, element, attr, ctrls) { - // notify others, especially parent forms - - var modelCtrl = ctrls[0], - formCtrl = ctrls[1] || nullFormCtrl; + restrict: 'A', + compile: function ngBindHtmlCompile(tElement, tAttrs) { + var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml); + var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function sceValueOf(val) { + // Unwrap the value to compare the actual inner safe value, not the wrapper object. + return $sce.valueOf(val); + }); + $compile.$$addBindingClass(tElement); - formCtrl.$addControl(modelCtrl); + return function ngBindHtmlLink(scope, element, attr) { + $compile.$$addBindingInfo(element, attr.ngBindHtml); - scope.$on('$destroy', function() { - formCtrl.$removeControl(modelCtrl); - }); + scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() { + // The watched value is the unwrapped value. To avoid re-escaping, use the direct getter. + var value = ngBindHtmlGetter(scope); + element.html($sce.getTrustedHtml(value) || ''); + }); + }; } }; -}; - +}]; /** * @ngdoc directive * @name ngChange + * @restrict A * * @description * Evaluate the given expression when the user changes the input. * The expression is evaluated immediately, unlike the JavaScript onchange event * which only triggers at the end of a change (usually, when the user leaves the * form element or presses the return key). - * The expression is not evaluated when the value change is coming from the model. + * + * The `ngChange` expression is only evaluated when a change in the input value causes + * a new value to be committed to the model. + * + * It will not be evaluated: + * * if the value returned from the `$parsers` transformation pipeline has not changed + * * if the input has continued to be invalid since the model will stay `null` + * * if the model is changed programmatically and not by a change to the input value + * * * Note, this directive requires `ngModel` to be present. * - * @element input + * @element ANY * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change * in input value. * * @example - * + * * * - *
+ *
* * *
@@ -17529,6 +27992,7 @@ var ngModelDirective = function() { * */ var ngChangeDirective = valueFn({ + restrict: 'A', require: 'ngModel', link: function(scope, element, attr, ctrl) { ctrl.$viewChangeListeners.push(function() { @@ -17537,1966 +28001,4913 @@ var ngChangeDirective = valueFn({ } }); +/* exported + ngClassDirective, + ngClassEvenDirective, + ngClassOddDirective +*/ -var requiredDirective = function() { - return { - require: '?ngModel', - link: function(scope, elm, attr, ctrl) { - if (!ctrl) return; - attr.required = true; // force truthy in case we are on non input element +function classDirective(name, selector) { + name = 'ngClass' + name; + var indexWatchExpression; - var validator = function(value) { - if (attr.required && ctrl.$isEmpty(value)) { - ctrl.$setValidity('required', false); - return; - } else { - ctrl.$setValidity('required', true); - return value; + return ['$parse', function($parse) { + return { + restrict: 'AC', + link: function(scope, element, attr) { + var classCounts = element.data('$classCounts'); + var oldModulo = true; + var oldClassString; + + if (!classCounts) { + // Use createMap() to prevent class assumptions involving property + // names in Object.prototype + classCounts = createMap(); + element.data('$classCounts', classCounts); } - }; - ctrl.$formatters.push(validator); - ctrl.$parsers.unshift(validator); + if (name !== 'ngClass') { + if (!indexWatchExpression) { + indexWatchExpression = $parse('$index', function moduloTwo($index) { + // eslint-disable-next-line no-bitwise + return $index & 1; + }); + } - attr.$observe('required', function() { - validator(ctrl.$viewValue); - }); - } - }; -}; + scope.$watch(indexWatchExpression, ngClassIndexWatchAction); + } + scope.$watch($parse(attr[name], toClassString), ngClassWatchAction); -/** - * @ngdoc directive - * @name ngList - * - * @description - * Text input that converts between a delimited string and an array of strings. The delimiter - * can be a fixed string (by default a comma) or a regular expression. - * - * @element input - * @param {string=} ngList optional delimiter that should be used to split the value. If - * specified in form `/something/` then the value will be converted into a regular expression. - * - * @example - - - -
- List: - - Required! -
- names = {{names}}
- myForm.namesInput.$valid = {{myForm.namesInput.$valid}}
- myForm.namesInput.$error = {{myForm.namesInput.$error}}
- myForm.$valid = {{myForm.$valid}}
- myForm.$error.required = {{!!myForm.$error.required}}
-
-
- - var listInput = element(by.model('names')); - var names = element(by.binding('{{names}}')); - var valid = element(by.binding('myForm.namesInput.$valid')); - var error = element(by.css('span.error')); + function addClasses(classString) { + classString = digestClassCounts(split(classString), 1); + attr.$addClass(classString); + } - it('should initialize to model', function() { - expect(names.getText()).toContain('["igor","misko","vojta"]'); - expect(valid.getText()).toContain('true'); - expect(error.getCssValue('display')).toBe('none'); - }); + function removeClasses(classString) { + classString = digestClassCounts(split(classString), -1); + attr.$removeClass(classString); + } - it('should be invalid if empty', function() { - listInput.clear(); - listInput.sendKeys(''); + function updateClasses(oldClassString, newClassString) { + var oldClassArray = split(oldClassString); + var newClassArray = split(newClassString); - expect(names.getText()).toContain(''); - expect(valid.getText()).toContain('false'); - expect(error.getCssValue('display')).not.toBe('none'); }); - -
- */ -var ngListDirective = function() { - return { - require: 'ngModel', - link: function(scope, element, attr, ctrl) { - var match = /\/(.*)\//.exec(attr.ngList), - separator = match && new RegExp(match[1]) || attr.ngList || ','; + var toRemoveArray = arrayDifference(oldClassArray, newClassArray); + var toAddArray = arrayDifference(newClassArray, oldClassArray); - var parse = function(viewValue) { - // If the viewValue is invalid (say required but empty) it will be `undefined` - if (isUndefined(viewValue)) return; + var toRemoveString = digestClassCounts(toRemoveArray, -1); + var toAddString = digestClassCounts(toAddArray, 1); - var list = []; + attr.$addClass(toAddString); + attr.$removeClass(toRemoveString); + } - if (viewValue) { - forEach(viewValue.split(separator), function(value) { - if (value) list.push(trim(value)); + function digestClassCounts(classArray, count) { + var classesToUpdate = []; + + forEach(classArray, function(className) { + if (count > 0 || classCounts[className]) { + classCounts[className] = (classCounts[className] || 0) + count; + if (classCounts[className] === +(count > 0)) { + classesToUpdate.push(className); + } + } }); + + return classesToUpdate.join(' '); } - return list; - }; + function ngClassIndexWatchAction(newModulo) { + // This watch-action should run before the `ngClassWatchAction()`, thus it + // adds/removes `oldClassString`. If the `ngClass` expression has changed as well, the + // `ngClassWatchAction()` will update the classes. + if (newModulo === selector) { + addClasses(oldClassString); + } else { + removeClasses(oldClassString); + } - ctrl.$parsers.push(parse); - ctrl.$formatters.push(function(value) { - if (isArray(value)) { - return value.join(', '); + oldModulo = newModulo; } - return undefined; - }); + function ngClassWatchAction(newClassString) { + if (oldModulo === selector) { + updateClasses(oldClassString, newClassString); + } - // Override the standard $isEmpty because an empty array means the input is empty. - ctrl.$isEmpty = function(value) { - return !value || !value.length; - }; + oldClassString = newClassString; + } + } + }; + }]; + + // Helpers + function arrayDifference(tokens1, tokens2) { + if (!tokens1 || !tokens1.length) return []; + if (!tokens2 || !tokens2.length) return tokens1; + + var values = []; + + outer: + for (var i = 0; i < tokens1.length; i++) { + var token = tokens1[i]; + for (var j = 0; j < tokens2.length; j++) { + if (token === tokens2[j]) continue outer; + } + values.push(token); } - }; -}; + return values; + } + + function split(classString) { + return classString && classString.split(' '); + } + + function toClassString(classValue) { + if (!classValue) return classValue; + + var classString = classValue; + + if (isArray(classValue)) { + classString = classValue.map(toClassString).join(' '); + } else if (isObject(classValue)) { + classString = Object.keys(classValue). + filter(function(key) { return classValue[key]; }). + join(' '); + } else if (!isString(classValue)) { + classString = classValue + ''; + } + + return classString; + } +} -var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/; /** * @ngdoc directive - * @name ngValue + * @name ngClass + * @restrict AC + * @element ANY * * @description - * Binds the given expression to the value of `input[select]` or `input[radio]`, so - * that when the element is selected, the `ngModel` of that element is set to the - * bound value. + * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding + * an expression that represents all classes to be added. * - * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as - * shown below. + * The directive operates in three different ways, depending on which of three types the expression + * evaluates to: * - * @element input - * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute - * of the `input` element + * 1. If the expression evaluates to a string, the string should be one or more space-delimited class + * names. * - * @example - - - -
-

Which is your favorite?

- -
You chose {{my.favorite}}
-
-
- - var favorite = element(by.binding('my.favorite')); - - it('should initialize to model', function() { - expect(favorite.getText()).toContain('unicorns'); - }); - it('should bind the values to the inputs', function() { - element.all(by.model('my.favorite')).get(0).click(); - expect(favorite.getText()).toContain('pizza'); - }); - -
- */ -var ngValueDirective = function() { - return { - priority: 100, - compile: function(tpl, tplAttr) { - if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) { - return function ngValueConstantLink(scope, elm, attr) { - attr.$set('value', scope.$eval(attr.ngValue)); - }; - } else { - return function ngValueLink(scope, elm, attr) { - scope.$watch(attr.ngValue, function valueWatchAction(value) { - attr.$set('value', value); - }); - }; - } - } - }; -}; - -/** - * @ngdoc directive - * @name ngBind - * @restrict AC + * 2. If the expression evaluates to an object, then for each key-value pair of the + * object with a truthy value the corresponding key is used as a class name. * - * @description - * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element - * with the value of a given expression, and to update the text content when the value of that - * expression changes. + * 3. If the expression evaluates to an array, each element of the array should either be a string as in + * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array + * to give you more control over what CSS classes appear. See the code below for an example of this. * - * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like - * `{{ expression }}` which is similar but less verbose. * - * It is preferable to use `ngBind` instead of `{{ expression }}` when a template is momentarily - * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an - * element attribute, it makes the bindings invisible to the user while the page is loading. + * The directive won't add duplicate classes if a particular class was already set. * - * An alternative solution to this problem would be using the - * {@link ng.directive:ngCloak ngCloak} directive. + * When the expression changes, the previously added classes are removed and only then are the + * new classes added. * + * @knownIssue + * You should not use {@link guide/interpolation interpolation} in the value of the `class` + * attribute, when using the `ngClass` directive on the same element. + * See {@link guide/interpolation#known-issues here} for more info. * - * @element ANY - * @param {expression} ngBind {@link guide/expression Expression} to evaluate. + * @animations + * | Animation | Occurs | + * |----------------------------------|-------------------------------------| + * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element | + * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element | + * | {@link ng.$animate#setClass setClass} | just before classes are added and classes are removed from the element at the same time | + * + * ### ngClass and pre-existing CSS3 Transitions/Animations + The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. + Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder + any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure + to view the step by step details of {@link $animate#addClass $animate.addClass} and + {@link $animate#removeClass $animate.removeClass}. + * + * @param {expression} ngClass {@link guide/expression Expression} to eval. The result + * of the evaluation can be a string representing space delimited class + * names, an array, or a map of class names to boolean values. In the case of a map, the + * names of the properties whose values are truthy will be added as css classes to the + * element. * * @example - * Enter a name in the Live Preview text box; the greeting below the text box changes instantly. - + * ### Basic + - -
- Enter name:
- Hello ! -
+

Map Syntax Example

+
+
+ +
+

Using String Syntax

+ +
+

Using Array Syntax

+
+
+
+
+

Using Array and Map Syntax

+
+ +
+ + .strike { + text-decoration: line-through; + } + .bold { + font-weight: bold; + } + .red { + color: red; + } + .has-error { + color: red; + background-color: yellow; + } + .orange { + color: orange; + } - it('should check ng-bind', function() { - var nameInput = element(by.model('name')); + var ps = element.all(by.css('p')); - expect(element(by.binding('name')).getText()).toBe('Whirled'); - nameInput.clear(); - nameInput.sendKeys('world'); - expect(element(by.binding('name')).getText()).toBe('world'); + it('should let you toggle the class', function() { + + expect(ps.first().getAttribute('class')).not.toMatch(/bold/); + expect(ps.first().getAttribute('class')).not.toMatch(/has-error/); + + element(by.model('important')).click(); + expect(ps.first().getAttribute('class')).toMatch(/bold/); + + element(by.model('error')).click(); + expect(ps.first().getAttribute('class')).toMatch(/has-error/); + }); + + it('should let you toggle string example', function() { + expect(ps.get(1).getAttribute('class')).toBe(''); + element(by.model('style')).clear(); + element(by.model('style')).sendKeys('red'); + expect(ps.get(1).getAttribute('class')).toBe('red'); + }); + + it('array example should have 3 classes', function() { + expect(ps.get(2).getAttribute('class')).toBe(''); + element(by.model('style1')).sendKeys('bold'); + element(by.model('style2')).sendKeys('strike'); + element(by.model('style3')).sendKeys('red'); + expect(ps.get(2).getAttribute('class')).toBe('bold strike red'); + }); + + it('array with map example should have 2 classes', function() { + expect(ps.last().getAttribute('class')).toBe(''); + element(by.model('style4')).sendKeys('bold'); + element(by.model('warning')).click(); + expect(ps.last().getAttribute('class')).toBe('bold orange'); });
- */ -var ngBindDirective = ngDirective(function(scope, element, attr) { - element.addClass('ng-binding').data('$binding', attr.ngBind); - scope.$watch(attr.ngBind, function ngBindWatchAction(value) { - // We are purposefully using == here rather than === because we want to - // catch when value is "null or undefined" - // jshint -W041 - element.text(value == undefined ? '' : value); - }); -}); + @example + ### Animations -/** - * @ngdoc directive - * @name ngBindTemplate - * - * @description - * The `ngBindTemplate` directive specifies that the element - * text content should be replaced with the interpolation of the template - * in the `ngBindTemplate` attribute. - * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}` - * expressions. This directive is needed since some HTML elements - * (such as TITLE and OPTION) cannot contain SPAN elements. - * - * @element ANY - * @param {string} ngBindTemplate template of form - * {{ expression }} to eval. - * - * @example - * Try it here: enter text in text box and watch the greeting change. - + The example below demonstrates how to perform animations using ngClass. + + - -
- Salutation:
- Name:
-

-       
+ + +
+ Sample Text +
+ + .base-class { + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + } + + .base-class.my-class { + color: red; + font-size:3em; + } - it('should check ng-bind', function() { - var salutationElem = element(by.binding('salutation')); - var salutationInput = element(by.model('salutation')); - var nameInput = element(by.model('name')); + it('should check ng-class', function() { + expect(element(by.css('.base-class')).getAttribute('class')).not. + toMatch(/my-class/); - expect(salutationElem.getText()).toBe('Hello World!'); + element(by.id('setbtn')).click(); - salutationInput.clear(); - salutationInput.sendKeys('Greetings'); - nameInput.clear(); - nameInput.sendKeys('user'); + expect(element(by.css('.base-class')).getAttribute('class')). + toMatch(/my-class/); - expect(salutationElem.getText()).toBe('Greetings user!'); + element(by.id('clearbtn')).click(); + + expect(element(by.css('.base-class')).getAttribute('class')).not. + toMatch(/my-class/); });
*/ -var ngBindTemplateDirective = ['$interpolate', function($interpolate) { - return function(scope, element, attr) { - // TODO: move this to scenario runner - var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate)); - element.addClass('ng-binding').data('$binding', interpolateFn); - attr.$observe('ngBindTemplate', function(value) { - element.text(value); - }); - }; -}]; - +var ngClassDirective = classDirective('', true); /** * @ngdoc directive - * @name ngBindHtml + * @name ngClassOdd + * @restrict AC * * @description - * Creates a binding that will innerHTML the result of evaluating the `expression` into the current - * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link - * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize` - * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in - * core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to - * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example - * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}. + * The `ngClassOdd` and `ngClassEven` directives work exactly as + * {@link ng.directive:ngClass ngClass}, except they work in + * conjunction with `ngRepeat` and take effect only on odd (even) rows. * - * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you - * will have an exception (instead of an exploit.) + * This directive can be applied only within the scope of an + * {@link ng.directive:ngRepeat ngRepeat}. + * + * @animations + * | Animation | Occurs | + * |----------------------------------|-------------------------------------| + * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element | + * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element | * * @element ANY - * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate. + * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result + * of the evaluation can be a string representing space delimited class names or an array. * * @example - Try it here: enter text in text box and watch the greeting change. - - + -
-

-
+
    +
  1. + + {{name}} + +
  2. +
- - - angular.module('ngBindHtmlExample', ['ngSanitize']) - - .controller('ngBindHtmlCtrl', ['$scope', function ngBindHtmlCtrl($scope) { - $scope.myHTML = - 'I am an HTMLstring with links! and other stuff'; - }]); + + .odd { + color: red; + } + .even { + color: blue; + } - - it('should check ng-bind-html', function() { - expect(element(by.binding('myHTML')).getText()).toBe( - 'I am an HTMLstring with links! and other stuff'); + it('should check ng-class-odd and ng-class-even', function() { + expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). + toMatch(/odd/); + expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). + toMatch(/even/); });
- */ -var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) { - return function(scope, element, attr) { - element.addClass('ng-binding').data('$binding', attr.ngBindHtml); + * + *
+ * @example + * An example on how to implement animations using `ngClassOdd`: + * + + +
+ +
+ + + + +
{{ item }}
+
+
+ + .odd { + background: rgba(255, 255, 0, 0.25); + } - var parsed = $parse(attr.ngBindHtml); - function getStringValue() { return (parsed(scope) || '').toString(); } + .odd-add, .odd-remove { + transition: 1.5s; + } + + + it('should add new entries to the beginning of the list', function() { + var button = element(by.buttonText('Add item')); + var rows = element.all(by.repeater('item in items')); - scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) { - element.html($sce.getTrustedHtml(parsed(scope)) || ''); - }); - }; + expect(rows.count()).toBe(4); + expect(rows.get(0).getText()).toBe('Item 3'); + expect(rows.get(1).getText()).toBe('Item 2'); + + button.click(); + + expect(rows.count()).toBe(5); + expect(rows.get(0).getText()).toBe('Item 4'); + expect(rows.get(1).getText()).toBe('Item 3'); + }); + + it('should add odd class to odd entries', function() { + var button = element(by.buttonText('Add item')); + var rows = element.all(by.repeater('item in items')); + + expect(rows.get(0).getAttribute('class')).toMatch(/odd/); + expect(rows.get(1).getAttribute('class')).not.toMatch(/odd/); + + button.click(); + + expect(rows.get(0).getAttribute('class')).toMatch(/odd/); + expect(rows.get(1).getAttribute('class')).not.toMatch(/odd/); + }); + +
+ */ +var ngClassOddDirective = classDirective('Odd', 0); + +/** + * @ngdoc directive + * @name ngClassEven + * @restrict AC + * + * @description + * The `ngClassOdd` and `ngClassEven` directives work exactly as + * {@link ng.directive:ngClass ngClass}, except they work in + * conjunction with `ngRepeat` and take effect only on odd (even) rows. + * + * This directive can be applied only within the scope of an + * {@link ng.directive:ngRepeat ngRepeat}. + * + * @animations + * | Animation | Occurs | + * |----------------------------------|-------------------------------------| + * | {@link ng.$animate#addClass addClass} | just before the class is applied to the element | + * | {@link ng.$animate#removeClass removeClass} | just before the class is removed from the element | + * + * @element ANY + * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The + * result of the evaluation can be a string representing space delimited class names or an array. + * + * @example + + +
    +
  1. + + {{name}}       + +
  2. +
+
+ + .odd { + color: red; + } + .even { + color: blue; + } + + + it('should check ng-class-odd and ng-class-even', function() { + expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). + toMatch(/odd/); + expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). + toMatch(/even/); + }); + +
+ * + *
+ * @example + * An example on how to implement animations using `ngClassEven`: + * + + +
+ +
+ + + + +
{{ item }}
+
+
+ + .even { + background: rgba(255, 255, 0, 0.25); + } + + .even-add, .even-remove { + transition: 1.5s; + } + + + it('should add new entries to the beginning of the list', function() { + var button = element(by.buttonText('Add item')); + var rows = element.all(by.repeater('item in items')); + + expect(rows.count()).toBe(4); + expect(rows.get(0).getText()).toBe('Item 3'); + expect(rows.get(1).getText()).toBe('Item 2'); + + button.click(); + + expect(rows.count()).toBe(5); + expect(rows.get(0).getText()).toBe('Item 4'); + expect(rows.get(1).getText()).toBe('Item 3'); + }); + + it('should add even class to even entries', function() { + var button = element(by.buttonText('Add item')); + var rows = element.all(by.repeater('item in items')); + + expect(rows.get(0).getAttribute('class')).not.toMatch(/even/); + expect(rows.get(1).getAttribute('class')).toMatch(/even/); + + button.click(); + + expect(rows.get(0).getAttribute('class')).not.toMatch(/even/); + expect(rows.get(1).getAttribute('class')).toMatch(/even/); + }); + +
+ */ +var ngClassEvenDirective = classDirective('Even', 1); + +/** + * @ngdoc directive + * @name ngCloak + * @restrict AC + * + * @description + * The `ngCloak` directive is used to prevent the AngularJS html template from being briefly + * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this + * directive to avoid the undesirable flicker effect caused by the html template display. + * + * The directive can be applied to the `` element, but the preferred usage is to apply + * multiple `ngCloak` directives to small portions of the page to permit progressive rendering + * of the browser view. + * + * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and + * `angular.min.js`. + * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). + * + * ```css + * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { + * display: none !important; + * } + * ``` + * + * When this css rule is loaded by the browser, all html elements (including their children) that + * are tagged with the `ngCloak` directive are hidden. When AngularJS encounters this directive + * during the compilation of the template it deletes the `ngCloak` element attribute, making + * the compiled element visible. + * + * For the best result, the `angular.js` script must be loaded in the head section of the html + * document; alternatively, the css rule above must be included in the external stylesheet of the + * application. + * + * @element ANY + * + * @example + + +
{{ 'hello' }}
+
{{ 'world' }}
+
+ + it('should remove the template directive and css class', function() { + expect($('#template1').getAttribute('ng-cloak')). + toBeNull(); + expect($('#template2').getAttribute('ng-cloak')). + toBeNull(); + }); + +
+ * + */ +var ngCloakDirective = ngDirective({ + compile: function(element, attr) { + attr.$set('ngCloak', undefined); + element.removeClass('ng-cloak'); + } +}); + +/** + * @ngdoc directive + * @name ngController + * + * @description + * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular + * supports the principles behind the Model-View-Controller design pattern. + * + * MVC components in angular: + * + * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties + * are accessed through bindings. + * * View — The template (HTML with data bindings) that is rendered into the View. + * * Controller — The `ngController` directive specifies a Controller class; the class contains business + * logic behind the application to decorate the scope with functions and values + * + * Note that you can also attach controllers to the DOM by declaring it in a route definition + * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller + * again using `ng-controller` in the template itself. This will cause the controller to be attached + * and executed twice. + * + * @element ANY + * @scope + * @priority 500 + * @param {expression} ngController Name of a constructor function registered with the current + * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression} + * that on the current scope evaluates to a constructor function. + * + * The controller instance can be published into a scope property by specifying + * `ng-controller="as propertyName"`. + * + * @example + * Here is a simple form for editing user contact information. Adding, removing, clearing, and + * greeting are methods declared on the controller (see source tab). These methods can + * easily be called from the AngularJS markup. Any changes to the data are automatically reflected + * in the View without the need for a manual update. + * + * Two different declaration styles are included below: + * + * * one binds methods and properties directly onto the controller using `this`: + * `ng-controller="SettingsController1 as settings"` + * * one injects `$scope` into the controller: + * `ng-controller="SettingsController2"` + * + * The second option is more common in the AngularJS community, and is generally used in boilerplates + * and in this guide. However, there are advantages to binding properties directly to the controller + * and avoiding scope. + * + * * Using `controller as` makes it obvious which controller you are accessing in the template when + * multiple controllers apply to an element. + * * If you are writing your controllers as classes you have easier access to the properties and + * methods, which will appear on the scope, from inside the controller code. + * * Since there is always a `.` in the bindings, you don't have to worry about prototypal + * inheritance masking primitives. + * + * This example demonstrates the `controller as` syntax. + * + * + * + *
+ * + *
+ * Contact: + *
    + *
  • + * + * + * + * + *
  • + *
  • + *
+ *
+ *
+ * + * angular.module('controllerAsExample', []) + * .controller('SettingsController1', SettingsController1); + * + * function SettingsController1() { + * this.name = 'John Smith'; + * this.contacts = [ + * {type: 'phone', value: '408 555 1212'}, + * {type: 'email', value: 'john.smith@example.org'} + * ]; + * } + * + * SettingsController1.prototype.greet = function() { + * alert(this.name); + * }; + * + * SettingsController1.prototype.addContact = function() { + * this.contacts.push({type: 'email', value: 'yourname@example.org'}); + * }; + * + * SettingsController1.prototype.removeContact = function(contactToRemove) { + * var index = this.contacts.indexOf(contactToRemove); + * this.contacts.splice(index, 1); + * }; + * + * SettingsController1.prototype.clearContact = function(contact) { + * contact.type = 'phone'; + * contact.value = ''; + * }; + * + * + * it('should check controller as', function() { + * var container = element(by.id('ctrl-as-exmpl')); + * expect(container.element(by.model('settings.name')) + * .getAttribute('value')).toBe('John Smith'); + * + * var firstRepeat = + * container.element(by.repeater('contact in settings.contacts').row(0)); + * var secondRepeat = + * container.element(by.repeater('contact in settings.contacts').row(1)); + * + * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) + * .toBe('408 555 1212'); + * + * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value')) + * .toBe('john.smith@example.org'); + * + * firstRepeat.element(by.buttonText('clear')).click(); + * + * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) + * .toBe(''); + * + * container.element(by.buttonText('add')).click(); + * + * expect(container.element(by.repeater('contact in settings.contacts').row(2)) + * .element(by.model('contact.value')) + * .getAttribute('value')) + * .toBe('yourname@example.org'); + * }); + * + *
+ * + * This example demonstrates the "attach to `$scope`" style of controller. + * + * + * + *
+ * + *
+ * Contact: + *
    + *
  • + * + * + * + * + *
  • + *
  • [ ]
  • + *
+ *
+ *
+ * + * angular.module('controllerExample', []) + * .controller('SettingsController2', ['$scope', SettingsController2]); + * + * function SettingsController2($scope) { + * $scope.name = 'John Smith'; + * $scope.contacts = [ + * {type:'phone', value:'408 555 1212'}, + * {type:'email', value:'john.smith@example.org'} + * ]; + * + * $scope.greet = function() { + * alert($scope.name); + * }; + * + * $scope.addContact = function() { + * $scope.contacts.push({type:'email', value:'yourname@example.org'}); + * }; + * + * $scope.removeContact = function(contactToRemove) { + * var index = $scope.contacts.indexOf(contactToRemove); + * $scope.contacts.splice(index, 1); + * }; + * + * $scope.clearContact = function(contact) { + * contact.type = 'phone'; + * contact.value = ''; + * }; + * } + * + * + * it('should check controller', function() { + * var container = element(by.id('ctrl-exmpl')); + * + * expect(container.element(by.model('name')) + * .getAttribute('value')).toBe('John Smith'); + * + * var firstRepeat = + * container.element(by.repeater('contact in contacts').row(0)); + * var secondRepeat = + * container.element(by.repeater('contact in contacts').row(1)); + * + * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) + * .toBe('408 555 1212'); + * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value')) + * .toBe('john.smith@example.org'); + * + * firstRepeat.element(by.buttonText('clear')).click(); + * + * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value')) + * .toBe(''); + * + * container.element(by.buttonText('add')).click(); + * + * expect(container.element(by.repeater('contact in contacts').row(2)) + * .element(by.model('contact.value')) + * .getAttribute('value')) + * .toBe('yourname@example.org'); + * }); + * + *
+ + */ +var ngControllerDirective = [function() { + return { + restrict: 'A', + scope: true, + controller: '@', + priority: 500 + }; }]; -function classDirective(name, selector) { - name = 'ngClass' + name; - return ['$animate', function($animate) { - return { - restrict: 'AC', - link: function(scope, element, attr) { - var oldVal; +/** + * @ngdoc directive + * @name ngCsp + * + * @restrict A + * @element ANY + * @description + * + * AngularJS has some features that can conflict with certain restrictions that are applied when using + * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules. + * + * If you intend to implement CSP with these rules then you must tell AngularJS not to use these + * features. + * + * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps. + * + * + * The following default rules in CSP affect AngularJS: + * + * * The use of `eval()`, `Function(string)` and similar functions to dynamically create and execute + * code from strings is forbidden. AngularJS makes use of this in the {@link $parse} service to + * provide a 30% increase in the speed of evaluating AngularJS expressions. (This CSP rule can be + * disabled with the CSP keyword `unsafe-eval`, but it is generally not recommended as it would + * weaken the protections offered by CSP.) + * + * * The use of inline resources, such as inline ` +
+ Enter text and hit enter: + + +
list={{list}}
+
+ + + it('should check ng-submit', function() { + expect(element(by.binding('list')).getText()).toBe('list=[]'); + element(by.css('#submit')).click(); + expect(element(by.binding('list')).getText()).toContain('hello'); + expect(element(by.model('text')).getAttribute('value')).toBe(''); + }); + it('should ignore empty strings', function() { + expect(element(by.binding('list')).getText()).toBe('list=[]'); + element(by.css('#submit')).click(); + element(by.css('#submit')).click(); + expect(element(by.binding('list')).getText()).toContain('hello'); + }); + +
+ */ + +/** + * @ngdoc directive + * @name ngFocus + * @restrict A + * @element window, input, select, textarea, a + * @priority 0 + * + * @description + * Specify custom behavior on focus event. + * + * Note: As the `focus` event is executed synchronously when calling `input.focus()` + * AngularJS executes the expression using `scope.$evalAsync` if the event is fired + * during an `$apply` to ensure a consistent state. + * + * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon + * focus. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + +/** + * @ngdoc directive + * @name ngBlur + * @restrict A + * @element window, input, select, textarea, a + * @priority 0 + * + * @description + * Specify custom behavior on blur event. + * + * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when + * an element has lost focus. + * + * Note: As the `blur` event is executed synchronously also during DOM manipulations + * (e.g. removing a focussed input), + * AngularJS executes the expression using `scope.$evalAsync` if the event is fired + * during an `$apply` to ensure a consistent state. + * + * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon + * blur. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + * See {@link ng.directive:ngClick ngClick} + */ + +/** + * @ngdoc directive + * @name ngCopy + * @restrict A + * @element window, input, select, textarea, a + * @priority 0 + * + * @description + * Specify custom behavior on copy event. + * + * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon + * copy. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + copied: {{copied}} + + + */ + +/** + * @ngdoc directive + * @name ngCut + * @restrict A + * @element window, input, select, textarea, a + * @priority 0 + * + * @description + * Specify custom behavior on cut event. + * + * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon + * cut. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + cut: {{cut}} + + + */ + +/** + * @ngdoc directive + * @name ngPaste + * @restrict A + * @element window, input, select, textarea, a + * @priority 0 + * + * @description + * Specify custom behavior on paste event. + * + * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon + * paste. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * @example + + + + pasted: {{paste}} + + + */ + +/** + * @ngdoc directive + * @name ngIf + * @restrict A + * @multiElement + * + * @description + * The `ngIf` directive removes or recreates a portion of the DOM tree based on an + * {expression}. If the expression assigned to `ngIf` evaluates to a false + * value then the element is removed from the DOM, otherwise a clone of the + * element is reinserted into the DOM. + * + * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the + * element in the DOM rather than changing its visibility via the `display` css property. A common + * case when this difference is significant is when using css selectors that rely on an element's + * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes. + * + * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope + * is created when the element is restored. The scope created within `ngIf` inherits from + * its parent scope using + * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance). + * An important implication of this is if `ngModel` is used within `ngIf` to bind to + * a javascript primitive defined in the parent scope. In this case any modifications made to the + * variable within the child scope will override (hide) the value in the parent scope. + * + * Also, `ngIf` recreates elements using their compiled state. An example of this behavior + * is if an element's class attribute is directly modified after it's compiled, using something like + * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element + * the added class will be lost because the original compiled state is used to regenerate the element. + * + * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter` + * and `leave` effects. + * + * @animations + * | Animation | Occurs | + * |----------------------------------|-------------------------------------| + * | {@link ng.$animate#enter enter} | just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container | + * | {@link ng.$animate#leave leave} | just before the `ngIf` contents are removed from the DOM | + * + * @element ANY + * @scope + * @priority 600 + * @param {expression} ngIf If the {@link guide/expression expression} is falsy then + * the element is removed from the DOM tree. If it is truthy a copy of the compiled + * element is added to the DOM tree. + * + * @example + + +
+ Show when checked: + + This is removed when the checkbox is unchecked. + +
+ + .animate-if { + background:white; + border:1px solid black; + padding:10px; + } + + .animate-if.ng-enter, .animate-if.ng-leave { + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + } + + .animate-if.ng-enter, + .animate-if.ng-leave.ng-leave-active { + opacity:0; + } + + .animate-if.ng-leave, + .animate-if.ng-enter.ng-enter-active { + opacity:1; + } + +
+ */ +var ngIfDirective = ['$animate', '$compile', function($animate, $compile) { + return { + multiElement: true, + transclude: 'element', + priority: 600, + terminal: true, + restrict: 'A', + $$tlb: true, + link: function($scope, $element, $attr, ctrl, $transclude) { + var block, childScope, previousElements; + $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { + + if (value) { + if (!childScope) { + $transclude(function(clone, newScope) { + childScope = newScope; + clone[clone.length++] = $compile.$$createComment('end ngIf', $attr.ngIf); + // Note: We only need the first/last node of the cloned nodes. + // However, we need to keep the reference to the jqlite wrapper as it might be changed later + // by a directive with templateUrl when its template arrives. + block = { + clone: clone + }; + $animate.enter(clone, $element.parent(), $element); + }); + } + } else { + if (previousElements) { + previousElements.remove(); + previousElements = null; + } + if (childScope) { + childScope.$destroy(); + childScope = null; + } + if (block) { + previousElements = getBlockNodes(block.clone); + $animate.leave(previousElements).done(function(response) { + if (response !== false) previousElements = null; + }); + block = null; + } + } + }); + } + }; +}]; + +/** + * @ngdoc directive + * @name ngInclude + * @restrict ECA + * @scope + * @priority -400 + * + * @description + * Fetches, compiles and includes an external HTML fragment. + * + * By default, the template URL is restricted to the same domain and protocol as the + * application document. This is done by calling {@link $sce#getTrustedResourceUrl + * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols + * you may either add them to your {@link ng.$sceDelegateProvider#trustedResourceUrlList trusted + * resource URL list} or {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to + * AngularJS's {@link ng.$sce Strict Contextual Escaping}. + * + * In addition, the browser's + * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest) + * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/) + * policy may further restrict whether the template is successfully loaded. + * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://` + * access on some browsers. + * + * @animations + * | Animation | Occurs | + * |----------------------------------|-------------------------------------| + * | {@link ng.$animate#enter enter} | when the expression changes, on the new include | + * | {@link ng.$animate#leave leave} | when the expression changes, on the old include | + * + * The enter and leave animation occur concurrently. + * + * @param {string} ngInclude|src AngularJS expression evaluating to URL. If the source is a string constant, + * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`. + * @param {string=} onload Expression to evaluate when a new partial is loaded. + *
+ * **Note:** When using onload on SVG elements in IE11, the browser will try to call + * a function with the name on the window element, which will usually throw a + * "function is undefined" error. To fix this, you can instead use `data-onload` or a + * different form that {@link guide/directive#normalization matches} `onload`. + *
+ * + * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll + * $anchorScroll} to scroll the viewport after the content is loaded. + * + * - If the attribute is not set, disable scrolling. + * - If the attribute is set without value, enable scrolling. + * - Otherwise enable scrolling only if the expression evaluates to truthy value. + * + * @example + + +
+ + url of the template: {{template.url}} +
+
+
+
+
+
+ + angular.module('includeExample', ['ngAnimate']) + .controller('ExampleController', ['$scope', function($scope) { + $scope.templates = + [{ name: 'template1.html', url: 'template1.html'}, + { name: 'template2.html', url: 'template2.html'}]; + $scope.template = $scope.templates[0]; + }]); + + + Content of template1.html + + + Content of template2.html + + + .slide-animate-container { + position:relative; + background:white; + border:1px solid black; + height:40px; + overflow:hidden; + } + + .slide-animate { + padding:10px; + } + + .slide-animate.ng-enter, .slide-animate.ng-leave { + transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; + + position:absolute; + top:0; + left:0; + right:0; + bottom:0; + display:block; + padding:10px; + } + + .slide-animate.ng-enter { + top:-50px; + } + .slide-animate.ng-enter.ng-enter-active { + top:0; + } + + .slide-animate.ng-leave { + top:0; + } + .slide-animate.ng-leave.ng-leave-active { + top:50px; + } + + + var templateSelect = element(by.model('template')); + var includeElem = element(by.css('[ng-include]')); + + it('should load template1.html', function() { + expect(includeElem.getText()).toMatch(/Content of template1.html/); + }); + + it('should load template2.html', function() { + if (browser.params.browser === 'firefox') { + // Firefox can't handle using selects + // See https://github.com/angular/protractor/issues/480 + return; + } + templateSelect.click(); + templateSelect.all(by.css('option')).get(2).click(); + expect(includeElem.getText()).toMatch(/Content of template2.html/); + }); + + it('should change to blank', function() { + if (browser.params.browser === 'firefox') { + // Firefox can't handle using selects + return; + } + templateSelect.click(); + templateSelect.all(by.css('option')).get(0).click(); + expect(includeElem.isPresent()).toBe(false); + }); + +
+ */ + + +/** + * @ngdoc event + * @name ngInclude#$includeContentRequested + * @eventType emit on the scope ngInclude was declared in + * @description + * Emitted every time the ngInclude content is requested. + * + * @param {Object} angularEvent Synthetic event object. + * @param {String} src URL of content to load. + */ + + +/** + * @ngdoc event + * @name ngInclude#$includeContentLoaded + * @eventType emit on the current ngInclude scope + * @description + * Emitted every time the ngInclude content is reloaded. + * + * @param {Object} angularEvent Synthetic event object. + * @param {String} src URL of content to load. + */ + + +/** + * @ngdoc event + * @name ngInclude#$includeContentError + * @eventType emit on the scope ngInclude was declared in + * @description + * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299) + * + * @param {Object} angularEvent Synthetic event object. + * @param {String} src URL of content to load. + */ +var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', + function($templateRequest, $anchorScroll, $animate) { + return { + restrict: 'ECA', + priority: 400, + terminal: true, + transclude: 'element', + controller: angular.noop, + compile: function(element, attr) { + var srcExp = attr.ngInclude || attr.src, + onloadExp = attr.onload || '', + autoScrollExp = attr.autoscroll; + + return function(scope, $element, $attr, ctrl, $transclude) { + var changeCounter = 0, + currentScope, + previousElement, + currentElement; + + var cleanupLastIncludeContent = function() { + if (previousElement) { + previousElement.remove(); + previousElement = null; + } + if (currentScope) { + currentScope.$destroy(); + currentScope = null; + } + if (currentElement) { + $animate.leave(currentElement).done(function(response) { + if (response !== false) previousElement = null; + }); + previousElement = currentElement; + currentElement = null; + } + }; + + scope.$watch(srcExp, function ngIncludeWatchAction(src) { + var afterAnimation = function(response) { + if (response !== false && isDefined(autoScrollExp) && + (!autoScrollExp || scope.$eval(autoScrollExp))) { + $anchorScroll(); + } + }; + var thisChangeId = ++changeCounter; + + if (src) { + //set the 2nd param to true to ignore the template request error so that the inner + //contents and scope can be cleaned up. + $templateRequest(src, true).then(function(response) { + if (scope.$$destroyed) return; + + if (thisChangeId !== changeCounter) return; + var newScope = scope.$new(); + ctrl.template = response; + + // Note: This will also link all children of ng-include that were contained in the original + // html. If that content contains controllers, ... they could pollute/change the scope. + // However, using ng-include on an element with additional content does not make sense... + // Note: We can't remove them in the cloneAttchFn of $transclude as that + // function is called before linking the content, which would apply child + // directives to non existing elements. + var clone = $transclude(newScope, function(clone) { + cleanupLastIncludeContent(); + $animate.enter(clone, null, $element).done(afterAnimation); + }); + + currentScope = newScope; + currentElement = clone; + + currentScope.$emit('$includeContentLoaded', src); + scope.$eval(onloadExp); + }, function() { + if (scope.$$destroyed) return; + + if (thisChangeId === changeCounter) { + cleanupLastIncludeContent(); + scope.$emit('$includeContentError', src); + } + }); + scope.$emit('$includeContentRequested', src); + } else { + cleanupLastIncludeContent(); + ctrl.template = null; + } + }); + }; + } + }; +}]; + +// This directive is called during the $transclude call of the first `ngInclude` directive. +// It will replace and compile the content of the element with the loaded template. +// We need this directive so that the element content is already filled when +// the link function of another directive on the same element as ngInclude +// is called. +var ngIncludeFillContentDirective = ['$compile', + function($compile) { + return { + restrict: 'ECA', + priority: -400, + require: 'ngInclude', + link: function(scope, $element, $attr, ctrl) { + if (toString.call($element[0]).match(/SVG/)) { + // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not + // support innerHTML, so detect this here and try to generate the contents + // specially. + $element.empty(); + $compile(jqLiteBuildFragment(ctrl.template, window.document).childNodes)(scope, + function namespaceAdaptedClone(clone) { + $element.append(clone); + }, {futureParentElement: $element}); + return; + } + + $element.html(ctrl.template); + $compile($element.contents())(scope); + } + }; + }]; + +/** + * @ngdoc directive + * @name ngInit + * @restrict AC + * @priority 450 + * @element ANY + * + * @param {expression} ngInit {@link guide/expression Expression} to eval. + * + * @description + * The `ngInit` directive allows you to evaluate an expression in the + * current scope. + * + *
+ * This directive can be abused to add unnecessary amounts of logic into your templates. + * There are only a few appropriate uses of `ngInit`: + *
    + *
  • aliasing special properties of {@link ng.directive:ngRepeat `ngRepeat`}, + * as seen in the demo below.
  • + *
  • initializing data during development, or for examples, as seen throughout these docs.
  • + *
  • injecting data via server side scripting.
  • + *
+ * + * Besides these few cases, you should use {@link guide/component Components} or + * {@link guide/controller Controllers} rather than `ngInit` to initialize values on a scope. + *
+ * + *
+ * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make + * sure you have parentheses to ensure correct operator precedence: + *
+ * `
` + *
+ *
+ * + * @example + + + +
+
+
+ list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}}; +
+
+
+
+ + it('should alias index positions', function() { + var elements = element.all(by.css('.example-init')); + expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;'); + expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;'); + expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;'); + expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;'); + }); + +
+ */ +var ngInitDirective = ngDirective({ + priority: 450, + compile: function() { + return { + pre: function(scope, element, attrs) { + scope.$eval(attrs.ngInit); + } + }; + } +}); + +/** + * @ngdoc directive + * @name ngList + * @restrict A + * @priority 100 + * + * @param {string=} ngList optional delimiter that should be used to split the value. + * + * @description + * Text input that converts between a delimited string and an array of strings. The default + * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom + * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`. + * + * The behaviour of the directive is affected by the use of the `ngTrim` attribute. + * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each + * list item is respected. This implies that the user of the directive is responsible for + * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a + * tab or newline character. + * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected + * when joining the list items back together) and whitespace around each list item is stripped + * before it is added to the model. + * + * @example + * ### Validation + * + * + * + * angular.module('listExample', []) + * .controller('ExampleController', ['$scope', function($scope) { + * $scope.names = ['morpheus', 'neo', 'trinity']; + * }]); + * + * + *
+ * + * + * + * Required! + * + *
+ * names = {{names}}
+ * myForm.namesInput.$valid = {{myForm.namesInput.$valid}}
+ * myForm.namesInput.$error = {{myForm.namesInput.$error}}
+ * myForm.$valid = {{myForm.$valid}}
+ * myForm.$error.required = {{!!myForm.$error.required}}
+ *
+ *
+ * + * var listInput = element(by.model('names')); + * var names = element(by.exactBinding('names')); + * var valid = element(by.binding('myForm.namesInput.$valid')); + * var error = element(by.css('span.error')); + * + * it('should initialize to model', function() { + * expect(names.getText()).toContain('["morpheus","neo","trinity"]'); + * expect(valid.getText()).toContain('true'); + * expect(error.getCssValue('display')).toBe('none'); + * }); + * + * it('should be invalid if empty', function() { + * listInput.clear(); + * listInput.sendKeys(''); + * + * expect(names.getText()).toContain(''); + * expect(valid.getText()).toContain('false'); + * expect(error.getCssValue('display')).not.toBe('none'); + * }); + * + *
+ * + * @example + * ### Splitting on newline + * + * + * + * + *
{{ list | json }}
+ *
+ * + * it("should split the text by newlines", function() { + * var listInput = element(by.model('list')); + * var output = element(by.binding('list | json')); + * listInput.sendKeys('abc\ndef\nghi'); + * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]'); + * }); + * + *
+ * + */ +var ngListDirective = function() { + return { + restrict: 'A', + priority: 100, + require: 'ngModel', + link: function(scope, element, attr, ctrl) { + var ngList = attr.ngList || ', '; + var trimValues = attr.ngTrim !== 'false'; + var separator = trimValues ? trim(ngList) : ngList; + + var parse = function(viewValue) { + // If the viewValue is invalid (say required but empty) it will be `undefined` + if (isUndefined(viewValue)) return; + + var list = []; + + if (viewValue) { + forEach(viewValue.split(separator), function(value) { + if (value) list.push(trimValues ? trim(value) : value); + }); + } + + return list; + }; + + ctrl.$parsers.push(parse); + ctrl.$formatters.push(function(value) { + if (isArray(value)) { + return value.join(ngList); + } + + return undefined; + }); + + // Override the standard $isEmpty because an empty array means the input is empty. + ctrl.$isEmpty = function(value) { + return !value || !value.length; + }; + } + }; +}; + +/* global VALID_CLASS: true, + INVALID_CLASS: true, + PRISTINE_CLASS: true, + DIRTY_CLASS: true, + UNTOUCHED_CLASS: true, + TOUCHED_CLASS: true, + PENDING_CLASS: true, + addSetValidityMethod: true, + setupValidity: true, + defaultModelOptions: false +*/ + + +var VALID_CLASS = 'ng-valid', + INVALID_CLASS = 'ng-invalid', + PRISTINE_CLASS = 'ng-pristine', + DIRTY_CLASS = 'ng-dirty', + UNTOUCHED_CLASS = 'ng-untouched', + TOUCHED_CLASS = 'ng-touched', + EMPTY_CLASS = 'ng-empty', + NOT_EMPTY_CLASS = 'ng-not-empty'; + +var ngModelMinErr = minErr('ngModel'); + +/** + * @ngdoc type + * @name ngModel.NgModelController + * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a + * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue + * is set. + * + * @property {*} $modelValue The value in the model that the control is bound to. + * + * @property {Array.} $parsers Array of functions to execute, as a pipeline, whenever + * the control updates the ngModelController with a new {@link ngModel.NgModelController#$viewValue + `$viewValue`} from the DOM, usually via user input. + See {@link ngModel.NgModelController#$setViewValue `$setViewValue()`} for a detailed lifecycle explanation. + Note that the `$parsers` are not called when the bound ngModel expression changes programmatically. + + The functions are called in array order, each passing + its return value through to the next. The last return value is forwarded to the + {@link ngModel.NgModelController#$validators `$validators`} collection. + + Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue + `$viewValue`}. + + Returning `undefined` from a parser means a parse error occurred. In that case, + no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel` + will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`} + is set to `true`. The parse error is stored in `ngModel.$error.parse`. + + This simple example shows a parser that would convert text input value to lowercase: + * ```js + * function parse(value) { + * if (value) { + * return value.toLowerCase(); + * } + * } + * ngModelController.$parsers.push(parse); + * ``` + + * + * @property {Array.} $formatters Array of functions to execute, as a pipeline, whenever + the bound ngModel expression changes programmatically. The `$formatters` are not called when the + value of the control is changed by user interaction. + + Formatters are used to format / convert the {@link ngModel.NgModelController#$modelValue + `$modelValue`} for display in the control. + + The functions are called in reverse array order, each passing the value through to the + next. The last return value is used as the actual DOM value. + + This simple example shows a formatter that would convert the model value to uppercase: + + * ```js + * function format(value) { + * if (value) { + * return value.toUpperCase(); + * } + * } + * ngModel.$formatters.push(format); + * ``` + * + * @property {Object.} $validators A collection of validators that are applied + * whenever the model value changes. The key value within the object refers to the name of the + * validator while the function refers to the validation operation. The validation operation is + * provided with the model value as an argument and must return a true or false value depending + * on the response of that validation. + * + * ```js + * ngModel.$validators.validCharacters = function(modelValue, viewValue) { + * var value = modelValue || viewValue; + * return /[0-9]+/.test(value) && + * /[a-z]+/.test(value) && + * /[A-Z]+/.test(value) && + * /\W+/.test(value); + * }; + * ``` + * + * @property {Object.} $asyncValidators A collection of validations that are expected to + * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided + * is expected to return a promise when it is run during the model validation process. Once the promise + * is delivered then the validation status will be set to true when fulfilled and false when rejected. + * When the asynchronous validators are triggered, each of the validators will run in parallel and the model + * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator + * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators + * will only run once all synchronous validators have passed. + * + * Please note that if $http is used then it is important that the server returns a success HTTP response code + * in order to fulfill the validation and a status level of `4xx` in order to reject the validation. + * + * ```js + * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) { + * var value = modelValue || viewValue; + * + * // Lookup user by username + * return $http.get('/api/users/' + value). + * then(function resolved() { + * //username exists, this means validation fails + * return $q.reject('exists'); + * }, function rejected() { + * //username does not exist, therefore this validation passes + * return true; + * }); + * }; + * ``` + * + * @property {Array.} $viewChangeListeners Array of functions to execute whenever + * a change to {@link ngModel.NgModelController#$viewValue `$viewValue`} has caused a change + * to {@link ngModel.NgModelController#$modelValue `$modelValue`}. + * It is called with no arguments, and its return value is ignored. + * This can be used in place of additional $watches against the model value. + * + * @property {Object} $error An object hash with all failing validator ids as keys. + * @property {Object} $pending An object hash with all pending validator ids as keys. + * + * @property {boolean} $untouched True if control has not lost focus yet. + * @property {boolean} $touched True if control has lost focus. + * @property {boolean} $pristine True if user has not interacted with the control yet. + * @property {boolean} $dirty True if user has already interacted with the control. + * @property {boolean} $valid True if there is no error. + * @property {boolean} $invalid True if at least one error on the control. + * @property {string} $name The name attribute of the control. + * + * @description + * + * `NgModelController` provides API for the {@link ngModel `ngModel`} directive. + * The controller contains services for data-binding, validation, CSS updates, and value formatting + * and parsing. It purposefully does not contain any logic which deals with DOM rendering or + * listening to DOM events. + * Such DOM related logic should be provided by other directives which make use of + * `NgModelController` for data-binding to control elements. + * AngularJS provides this DOM logic for most {@link input `input`} elements. + * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example + * custom control example} that uses `ngModelController` to bind to `contenteditable` elements. + * + * @example + * ### Custom Control Example + * This example shows how to use `NgModelController` with a custom control to achieve + * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`) + * collaborate together to achieve the desired result. + * + * `contenteditable` is an HTML5 attribute, which tells the browser to let the element + * contents be edited in place by the user. + * + * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize} + * module to automatically remove "bad" content like inline event listener (e.g. ``). + * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks + * that content using the `$sce` service. + * + * + + [contenteditable] { + border: 1px solid black; + background-color: white; + min-height: 20px; + } + + .ng-invalid { + border: 1px solid red; + } + + + + angular.module('customControl', ['ngSanitize']). + directive('contenteditable', ['$sce', function($sce) { + return { + restrict: 'A', // only activate on element attribute + require: '?ngModel', // get a hold of NgModelController + link: function(scope, element, attrs, ngModel) { + if (!ngModel) return; // do nothing if no ng-model + + // Specify how UI should be updated + ngModel.$render = function() { + element.html($sce.getTrustedHtml(ngModel.$viewValue || '')); + }; + + // Listen for change events to enable binding + element.on('blur keyup change', function() { + scope.$evalAsync(read); + }); + read(); // initialize + + // Write data to the model + function read() { + var html = element.html(); + // When we clear the content editable the browser leaves a
behind + // If strip-br attribute is provided then we strip this out + if (attrs.stripBr && html === '
') { + html = ''; + } + ngModel.$setViewValue(html); + } + } + }; + }]); +
+ +
+
Change me!
+ Required! +
+ +
+
+ + it('should data-bind and become invalid', function() { + if (browser.params.browser === 'safari' || browser.params.browser === 'firefox') { + // SafariDriver can't handle contenteditable + // and Firefox driver can't clear contenteditables very well + return; + } + var contentEditable = element(by.css('[contenteditable]')); + var content = 'Change me!'; + + expect(contentEditable.getText()).toEqual(content); + + contentEditable.clear(); + contentEditable.sendKeys(protractor.Key.BACK_SPACE); + expect(contentEditable.getText()).toEqual(''); + expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/); + }); + + *
+ * + * + */ +NgModelController.$inject = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$q', '$interpolate']; +function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $q, $interpolate) { + this.$viewValue = Number.NaN; + this.$modelValue = Number.NaN; + this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity. + this.$validators = {}; + this.$asyncValidators = {}; + this.$parsers = []; + this.$formatters = []; + this.$viewChangeListeners = []; + this.$untouched = true; + this.$touched = false; + this.$pristine = true; + this.$dirty = false; + this.$valid = true; + this.$invalid = false; + this.$error = {}; // keep invalid keys here + this.$$success = {}; // keep valid keys here + this.$pending = undefined; // keep pending keys here + this.$name = $interpolate($attr.name || '', false)($scope); + this.$$parentForm = nullFormCtrl; + this.$options = defaultModelOptions; + this.$$updateEvents = ''; + // Attach the correct context to the event handler function for updateOn + this.$$updateEventHandler = this.$$updateEventHandler.bind(this); + + this.$$parsedNgModel = $parse($attr.ngModel); + this.$$parsedNgModelAssign = this.$$parsedNgModel.assign; + this.$$ngModelGet = this.$$parsedNgModel; + this.$$ngModelSet = this.$$parsedNgModelAssign; + this.$$pendingDebounce = null; + this.$$parserValid = undefined; + this.$$parserName = 'parse'; + + this.$$currentValidationRunId = 0; + + this.$$scope = $scope; + this.$$rootScope = $scope.$root; + this.$$attr = $attr; + this.$$element = $element; + this.$$animate = $animate; + this.$$timeout = $timeout; + this.$$parse = $parse; + this.$$q = $q; + this.$$exceptionHandler = $exceptionHandler; + + setupValidity(this); + setupModelWatcher(this); +} + +NgModelController.prototype = { + $$initGetterSetters: function() { + if (this.$options.getOption('getterSetter')) { + var invokeModelGetter = this.$$parse(this.$$attr.ngModel + '()'), + invokeModelSetter = this.$$parse(this.$$attr.ngModel + '($$$p)'); + + this.$$ngModelGet = function($scope) { + var modelValue = this.$$parsedNgModel($scope); + if (isFunction(modelValue)) { + modelValue = invokeModelGetter($scope); + } + return modelValue; + }; + this.$$ngModelSet = function($scope, newValue) { + if (isFunction(this.$$parsedNgModel($scope))) { + invokeModelSetter($scope, {$$$p: newValue}); + } else { + this.$$parsedNgModelAssign($scope, newValue); + } + }; + } else if (!this.$$parsedNgModel.assign) { + throw ngModelMinErr('nonassign', 'Expression \'{0}\' is non-assignable. Element: {1}', + this.$$attr.ngModel, startingTag(this.$$element)); + } + }, + + + /** + * @ngdoc method + * @name ngModel.NgModelController#$render + * + * @description + * Called when the view needs to be updated. It is expected that the user of the ng-model + * directive will implement this method. + * + * The `$render()` method is invoked in the following situations: + * + * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last + * committed value then `$render()` is called to update the input control. + * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and + * the `$viewValue` are different from last time. + * + * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of + * `$modelValue` and `$viewValue` are actually different from their previous values. If `$modelValue` + * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be + * invoked if you only change a property on the objects. + */ + $render: noop, + + /** + * @ngdoc method + * @name ngModel.NgModelController#$isEmpty + * + * @description + * This is called when we need to determine if the value of an input is empty. + * + * For instance, the required directive does this to work out if the input has data or not. + * + * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`. + * + * You can override this for input directives whose concept of being empty is different from the + * default. The `checkboxInputType` directive does this because in its case a value of `false` + * implies empty. + * + * @param {*} value The value of the input to check for emptiness. + * @returns {boolean} True if `value` is "empty". + */ + $isEmpty: function(value) { + // eslint-disable-next-line no-self-compare + return isUndefined(value) || value === '' || value === null || value !== value; + }, + + $$updateEmptyClasses: function(value) { + if (this.$isEmpty(value)) { + this.$$animate.removeClass(this.$$element, NOT_EMPTY_CLASS); + this.$$animate.addClass(this.$$element, EMPTY_CLASS); + } else { + this.$$animate.removeClass(this.$$element, EMPTY_CLASS); + this.$$animate.addClass(this.$$element, NOT_EMPTY_CLASS); + } + }, + + /** + * @ngdoc method + * @name ngModel.NgModelController#$setPristine + * + * @description + * Sets the control to its pristine state. + * + * This method can be called to remove the `ng-dirty` class and set the control to its pristine + * state (`ng-pristine` class). A model is considered to be pristine when the control + * has not been changed from when first compiled. + */ + $setPristine: function() { + this.$dirty = false; + this.$pristine = true; + this.$$animate.removeClass(this.$$element, DIRTY_CLASS); + this.$$animate.addClass(this.$$element, PRISTINE_CLASS); + }, + + /** + * @ngdoc method + * @name ngModel.NgModelController#$setDirty + * + * @description + * Sets the control to its dirty state. + * + * This method can be called to remove the `ng-pristine` class and set the control to its dirty + * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed + * from when first compiled. + */ + $setDirty: function() { + this.$dirty = true; + this.$pristine = false; + this.$$animate.removeClass(this.$$element, PRISTINE_CLASS); + this.$$animate.addClass(this.$$element, DIRTY_CLASS); + this.$$parentForm.$setDirty(); + }, + + /** + * @ngdoc method + * @name ngModel.NgModelController#$setUntouched + * + * @description + * Sets the control to its untouched state. + * + * This method can be called to remove the `ng-touched` class and set the control to its + * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched + * by default, however this function can be used to restore that state if the model has + * already been touched by the user. + */ + $setUntouched: function() { + this.$touched = false; + this.$untouched = true; + this.$$animate.setClass(this.$$element, UNTOUCHED_CLASS, TOUCHED_CLASS); + }, + + /** + * @ngdoc method + * @name ngModel.NgModelController#$setTouched + * + * @description + * Sets the control to its touched state. + * + * This method can be called to remove the `ng-untouched` class and set the control to its + * touched state (`ng-touched` class). A model is considered to be touched when the user has + * first focused the control element and then shifted focus away from the control (blur event). + */ + $setTouched: function() { + this.$touched = true; + this.$untouched = false; + this.$$animate.setClass(this.$$element, TOUCHED_CLASS, UNTOUCHED_CLASS); + }, + + /** + * @ngdoc method + * @name ngModel.NgModelController#$rollbackViewValue + * + * @description + * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`, + * which may be caused by a pending debounced event or because the input is waiting for some + * future event. + * + * If you have an input that uses `ng-model-options` to set up debounced updates or updates that + * depend on special events such as `blur`, there can be a period when the `$viewValue` is out of + * sync with the ngModel's `$modelValue`. + * + * In this case, you can use `$rollbackViewValue()` to manually cancel the debounced / future update + * and reset the input to the last committed view value. + * + * It is also possible that you run into difficulties if you try to update the ngModel's `$modelValue` + * programmatically before these debounced/future events have resolved/occurred, because AngularJS's + * dirty checking mechanism is not able to tell whether the model has actually changed or not. + * + * The `$rollbackViewValue()` method should be called before programmatically changing the model of an + * input which may have such events pending. This is important in order to make sure that the + * input field will be updated with the new model value and any pending operations are cancelled. + * + * @example + * + * + * angular.module('cancel-update-example', []) + * + * .controller('CancelUpdateController', ['$scope', function($scope) { + * $scope.model = {value1: '', value2: ''}; + * + * $scope.setEmpty = function(e, value, rollback) { + * if (e.keyCode === 27) { + * e.preventDefault(); + * if (rollback) { + * $scope.myForm[value].$rollbackViewValue(); + * } + * $scope.model[value] = ''; + * } + * }; + * }]); + * + * + *
+ *

Both of these inputs are only updated if they are blurred. Hitting escape should + * empty them. Follow these steps and observe the difference:

+ *
    + *
  1. Type something in the input. You will see that the model is not yet updated
  2. + *
  3. Press the Escape key. + *
      + *
    1. In the first example, nothing happens, because the model is already '', and no + * update is detected. If you blur the input, the model will be set to the current view. + *
    2. + *
    3. In the second example, the pending update is cancelled, and the input is set back + * to the last committed view value (''). Blurring the input does nothing. + *
    4. + *
    + *
  4. + *
+ * + *
+ *
+ *

Without $rollbackViewValue():

+ * + * value1: "{{ model.value1 }}" + *
+ * + *
+ *

With $rollbackViewValue():

+ * + * value2: "{{ model.value2 }}" + *
+ *
+ *
+ *
+ + div { + display: table-cell; + } + div:nth-child(1) { + padding-right: 30px; + } + + + *
+ */ + $rollbackViewValue: function() { + this.$$timeout.cancel(this.$$pendingDebounce); + this.$viewValue = this.$$lastCommittedViewValue; + this.$render(); + }, + + /** + * @ngdoc method + * @name ngModel.NgModelController#$validate + * + * @description + * Runs each of the registered validators (first synchronous validators and then + * asynchronous validators). + * If the validity changes to invalid, the model will be set to `undefined`, + * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`. + * If the validity changes to valid, it will set the model to the last available valid + * `$modelValue`, i.e. either the last parsed value or the last value set from the scope. + */ + $validate: function() { + + // ignore $validate before model is initialized + if (isNumberNaN(this.$modelValue)) { + return; + } + + var viewValue = this.$$lastCommittedViewValue; + // Note: we use the $$rawModelValue as $modelValue might have been + // set to undefined during a view -> model update that found validation + // errors. We can't parse the view here, since that could change + // the model although neither viewValue nor the model on the scope changed + var modelValue = this.$$rawModelValue; + + var prevValid = this.$valid; + var prevModelValue = this.$modelValue; + + var allowInvalid = this.$options.getOption('allowInvalid'); + + var that = this; + this.$$runValidators(modelValue, viewValue, function(allValid) { + // If there was no change in validity, don't update the model + // This prevents changing an invalid modelValue to undefined + if (!allowInvalid && prevValid !== allValid) { + // Note: Don't check this.$valid here, as we could have + // external validators (e.g. calculated on the server), + // that just call $setValidity and need the model value + // to calculate their validity. + that.$modelValue = allValid ? modelValue : undefined; + + if (that.$modelValue !== prevModelValue) { + that.$$writeModelToScope(); + } + } + }); + }, + + $$runValidators: function(modelValue, viewValue, doneCallback) { + this.$$currentValidationRunId++; + var localValidationRunId = this.$$currentValidationRunId; + var that = this; + + // check parser error + if (!processParseErrors()) { + validationDone(false); + return; + } + if (!processSyncValidators()) { + validationDone(false); + return; + } + processAsyncValidators(); + + function processParseErrors() { + var errorKey = that.$$parserName; + + if (isUndefined(that.$$parserValid)) { + setValidity(errorKey, null); + } else { + if (!that.$$parserValid) { + forEach(that.$validators, function(v, name) { + setValidity(name, null); + }); + forEach(that.$asyncValidators, function(v, name) { + setValidity(name, null); + }); + } + + // Set the parse error last, to prevent unsetting it, should a $validators key == parserName + setValidity(errorKey, that.$$parserValid); + return that.$$parserValid; + } + return true; + } + + function processSyncValidators() { + var syncValidatorsValid = true; + forEach(that.$validators, function(validator, name) { + var result = Boolean(validator(modelValue, viewValue)); + syncValidatorsValid = syncValidatorsValid && result; + setValidity(name, result); + }); + if (!syncValidatorsValid) { + forEach(that.$asyncValidators, function(v, name) { + setValidity(name, null); + }); + return false; + } + return true; + } + + function processAsyncValidators() { + var validatorPromises = []; + var allValid = true; + forEach(that.$asyncValidators, function(validator, name) { + var promise = validator(modelValue, viewValue); + if (!isPromiseLike(promise)) { + throw ngModelMinErr('nopromise', + 'Expected asynchronous validator to return a promise but got \'{0}\' instead.', promise); + } + setValidity(name, undefined); + validatorPromises.push(promise.then(function() { + setValidity(name, true); + }, function() { + allValid = false; + setValidity(name, false); + })); + }); + if (!validatorPromises.length) { + validationDone(true); + } else { + that.$$q.all(validatorPromises).then(function() { + validationDone(allValid); + }, noop); + } + } + + function setValidity(name, isValid) { + if (localValidationRunId === that.$$currentValidationRunId) { + that.$setValidity(name, isValid); + } + } - scope.$watch(attr[name], ngClassWatchAction, true); + function validationDone(allValid) { + if (localValidationRunId === that.$$currentValidationRunId) { - attr.$observe('class', function(value) { - ngClassWatchAction(scope.$eval(attr[name])); - }); + doneCallback(allValid); + } + } + }, + /** + * @ngdoc method + * @name ngModel.NgModelController#$commitViewValue + * + * @description + * Commit a pending update to the `$modelValue`. + * + * Updates may be pending by a debounced event or because the input is waiting for a some future + * event defined in `ng-model-options`. this method is rarely needed as `NgModelController` + * usually handles calling this in response to input events. + */ + $commitViewValue: function() { + var viewValue = this.$viewValue; - if (name !== 'ngClass') { - scope.$watch('$index', function($index, old$index) { - // jshint bitwise: false - var mod = $index & 1; - if (mod !== old$index & 1) { - var classes = arrayClasses(scope.$eval(attr[name])); - mod === selector ? - addClasses(classes) : - removeClasses(classes); - } - }); - } + this.$$timeout.cancel(this.$$pendingDebounce); - function addClasses(classes) { - var newClasses = digestClassCounts(classes, 1); - attr.$addClass(newClasses); - } + // If the view value has not changed then we should just exit, except in the case where there is + // a native validator on the element. In this case the validation state may have changed even though + // the viewValue has stayed empty. + if (this.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !this.$$hasNativeValidators)) { + return; + } + this.$$updateEmptyClasses(viewValue); + this.$$lastCommittedViewValue = viewValue; - function removeClasses(classes) { - var newClasses = digestClassCounts(classes, -1); - attr.$removeClass(newClasses); - } + // change to dirty + if (this.$pristine) { + this.$setDirty(); + } + this.$$parseAndValidate(); + }, - function digestClassCounts (classes, count) { - var classCounts = element.data('$classCounts') || {}; - var classesToUpdate = []; - forEach(classes, function (className) { - if (count > 0 || classCounts[className]) { - classCounts[className] = (classCounts[className] || 0) + count; - if (classCounts[className] === +(count > 0)) { - classesToUpdate.push(className); - } - } - }); - element.data('$classCounts', classCounts); - return classesToUpdate.join(' '); - } + $$parseAndValidate: function() { + var viewValue = this.$$lastCommittedViewValue; + var modelValue = viewValue; + var that = this; - function updateClasses (oldClasses, newClasses) { - var toAdd = arrayDifference(newClasses, oldClasses); - var toRemove = arrayDifference(oldClasses, newClasses); - toRemove = digestClassCounts(toRemove, -1); - toAdd = digestClassCounts(toAdd, 1); + this.$$parserValid = isUndefined(modelValue) ? undefined : true; - if (toAdd.length === 0) { - $animate.removeClass(element, toRemove); - } else if (toRemove.length === 0) { - $animate.addClass(element, toAdd); - } else { - $animate.setClass(element, toAdd, toRemove); - } - } + // Reset any previous parse error + this.$setValidity(this.$$parserName, null); + this.$$parserName = 'parse'; - function ngClassWatchAction(newVal) { - if (selector === true || scope.$index % 2 === selector) { - var newClasses = arrayClasses(newVal || []); - if (!oldVal) { - addClasses(newClasses); - } else if (!equals(newVal,oldVal)) { - var oldClasses = arrayClasses(oldVal); - updateClasses(oldClasses, newClasses); - } - } - oldVal = copy(newVal); + if (this.$$parserValid) { + for (var i = 0; i < this.$parsers.length; i++) { + modelValue = this.$parsers[i](modelValue); + if (isUndefined(modelValue)) { + this.$$parserValid = false; + break; } } - }; + } + if (isNumberNaN(this.$modelValue)) { + // this.$modelValue has not been touched yet... + this.$modelValue = this.$$ngModelGet(this.$$scope); + } + var prevModelValue = this.$modelValue; + var allowInvalid = this.$options.getOption('allowInvalid'); + this.$$rawModelValue = modelValue; - function arrayDifference(tokens1, tokens2) { - var values = []; + if (allowInvalid) { + this.$modelValue = modelValue; + writeToModelIfNeeded(); + } - outer: - for(var i = 0; i < tokens1.length; i++) { - var token = tokens1[i]; - for(var j = 0; j < tokens2.length; j++) { - if(token == tokens2[j]) continue outer; - } - values.push(token); + // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date. + // This can happen if e.g. $setViewValue is called from inside a parser + this.$$runValidators(modelValue, this.$$lastCommittedViewValue, function(allValid) { + if (!allowInvalid) { + // Note: Don't check this.$valid here, as we could have + // external validators (e.g. calculated on the server), + // that just call $setValidity and need the model value + // to calculate their validity. + that.$modelValue = allValid ? modelValue : undefined; + writeToModelIfNeeded(); } - return values; - } + }); - function arrayClasses (classVal) { - if (isArray(classVal)) { - return classVal; - } else if (isString(classVal)) { - return classVal.split(' '); - } else if (isObject(classVal)) { - var classes = [], i = 0; - forEach(classVal, function(v, k) { - if (v) { - classes.push(k); - } - }); - return classes; + function writeToModelIfNeeded() { + if (that.$modelValue !== prevModelValue) { + that.$$writeModelToScope(); } - return classVal; } - }]; -} + }, -/** - * @ngdoc directive - * @name ngClass - * @restrict AC - * - * @description - * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding - * an expression that represents all classes to be added. - * - * The directive operates in three different ways, depending on which of three types the expression - * evaluates to: - * - * 1. If the expression evaluates to a string, the string should be one or more space-delimited class - * names. - * - * 2. If the expression evaluates to an array, each element of the array should be a string that is - * one or more space-delimited class names. - * - * 3. If the expression evaluates to an object, then for each key-value pair of the - * object with a truthy value the corresponding key is used as a class name. - * - * The directive won't add duplicate classes if a particular class was already set. - * - * When the expression changes, the previously added classes are removed and only then the - * new classes are added. - * - * @animations - * add - happens just before the class is applied to the element - * remove - happens just before the class is removed from the element - * - * @element ANY - * @param {expression} ngClass {@link guide/expression Expression} to eval. The result - * of the evaluation can be a string representing space delimited class - * names, an array, or a map of class names to boolean values. In the case of a map, the - * names of the properties whose values are truthy will be added as css classes to the - * element. - * - * @example Example that demonstrates basic bindings via ngClass directive. - - -

Map Syntax Example

- deleted (apply "strike" class)
- important (apply "bold" class)
- error (apply "red" class) -
-

Using String Syntax

- -
-

Using Array Syntax

-
-
-
-
- - .strike { - text-decoration: line-through; - } - .bold { - font-weight: bold; - } - .red { - color: red; - } - - - var ps = element.all(by.css('p')); + $$writeModelToScope: function() { + this.$$ngModelSet(this.$$scope, this.$modelValue); + forEach(this.$viewChangeListeners, function(listener) { + try { + listener(); + } catch (e) { + // eslint-disable-next-line no-invalid-this + this.$$exceptionHandler(e); + } + }, this); + }, - it('should let you toggle the class', function() { + /** + * @ngdoc method + * @name ngModel.NgModelController#$setViewValue + * + * @description + * Update the view value. + * + * This method should be called when a control wants to change the view value; typically, + * this is done from within a DOM event handler. For example, the {@link ng.directive:input input} + * directive calls it when the value of the input changes and {@link ng.directive:select select} + * calls it when an option is selected. + * + * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers` + * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged + * value is sent directly for processing through the `$parsers` pipeline. After this, the `$validators` and + * `$asyncValidators` are called and the value is applied to `$modelValue`. + * Finally, the value is set to the **expression** specified in the `ng-model` attribute and + * all the registered change listeners, in the `$viewChangeListeners` list are called. + * + * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn` + * and the `default` trigger is not listed, all those actions will remain pending until one of the + * `updateOn` events is triggered on the DOM element. + * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions} + * directive is used with a custom debounce for this particular event. + * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce` + * is specified, once the timer runs out. + * + * When used with standard inputs, the view value will always be a string (which is in some cases + * parsed into another type, such as a `Date` object for `input[date]`.) + * However, custom controls might also pass objects to this method. In this case, we should make + * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not + * perform a deep watch of objects, it only looks for a change of identity. If you only change + * the property of the object then ngModel will not realize that the object has changed and + * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should + * not change properties of the copy once it has been passed to `$setViewValue`. + * Otherwise you may cause the model value on the scope to change incorrectly. + * + *
+ * In any case, the value passed to the method should always reflect the current value + * of the control. For example, if you are calling `$setViewValue` for an input element, + * you should pass the input DOM value. Otherwise, the control and the scope model become + * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change + * the control's DOM value in any way. If we want to change the control's DOM value + * programmatically, we should update the `ngModel` scope expression. Its new value will be + * picked up by the model controller, which will run it through the `$formatters`, `$render` it + * to update the DOM, and finally call `$validate` on it. + *
+ * + * @param {*} value value from the view. + * @param {string} trigger Event that triggered the update. + */ + $setViewValue: function(value, trigger) { + this.$viewValue = value; + if (this.$options.getOption('updateOnDefault')) { + this.$$debounceViewValueCommit(trigger); + } + }, - expect(ps.first().getAttribute('class')).not.toMatch(/bold/); - expect(ps.first().getAttribute('class')).not.toMatch(/red/); + $$debounceViewValueCommit: function(trigger) { + var debounceDelay = this.$options.getOption('debounce'); + + if (isNumber(debounceDelay[trigger])) { + debounceDelay = debounceDelay[trigger]; + } else if (isNumber(debounceDelay['default']) && + this.$options.getOption('updateOn').indexOf(trigger) === -1 + ) { + debounceDelay = debounceDelay['default']; + } else if (isNumber(debounceDelay['*'])) { + debounceDelay = debounceDelay['*']; + } - element(by.model('important')).click(); - expect(ps.first().getAttribute('class')).toMatch(/bold/); + this.$$timeout.cancel(this.$$pendingDebounce); + var that = this; + if (debounceDelay > 0) { // this fails if debounceDelay is an object + this.$$pendingDebounce = this.$$timeout(function() { + that.$commitViewValue(); + }, debounceDelay); + } else if (this.$$rootScope.$$phase) { + this.$commitViewValue(); + } else { + this.$$scope.$apply(function() { + that.$commitViewValue(); + }); + } + }, - element(by.model('error')).click(); - expect(ps.first().getAttribute('class')).toMatch(/red/); - }); + /** + * @ngdoc method + * + * @name ngModel.NgModelController#$overrideModelOptions + * + * @description + * + * Override the current model options settings programmatically. + * + * The previous `ModelOptions` value will not be modified. Instead, a + * new `ModelOptions` object will inherit from the previous one overriding + * or inheriting settings that are defined in the given parameter. + * + * See {@link ngModelOptions} for information about what options can be specified + * and how model option inheritance works. + * + *
+ * **Note:** this function only affects the options set on the `ngModelController`, + * and not the options on the {@link ngModelOptions} directive from which they might have been + * obtained initially. + *
+ * + *
+ * **Note:** it is not possible to override the `getterSetter` option. + *
+ * + * @param {Object} options a hash of settings to override the previous options + * + */ + $overrideModelOptions: function(options) { + this.$options = this.$options.createChild(options); + this.$$setUpdateOnEvents(); + }, - it('should let you toggle string example', function() { - expect(ps.get(1).getAttribute('class')).toBe(''); - element(by.model('style')).clear(); - element(by.model('style')).sendKeys('red'); - expect(ps.get(1).getAttribute('class')).toBe('red'); - }); + /** + * @ngdoc method + * + * @name ngModel.NgModelController#$processModelValue - it('array example should have 3 classes', function() { - expect(ps.last().getAttribute('class')).toBe(''); - element(by.model('style1')).sendKeys('bold'); - element(by.model('style2')).sendKeys('strike'); - element(by.model('style3')).sendKeys('red'); - expect(ps.last().getAttribute('class')).toBe('bold strike red'); - }); + * @description + * + * Runs the model -> view pipeline on the current + * {@link ngModel.NgModelController#$modelValue $modelValue}. + * + * The following actions are performed by this method: + * + * - the `$modelValue` is run through the {@link ngModel.NgModelController#$formatters $formatters} + * and the result is set to the {@link ngModel.NgModelController#$viewValue $viewValue} + * - the `ng-empty` or `ng-not-empty` class is set on the element + * - if the `$viewValue` has changed: + * - {@link ngModel.NgModelController#$render $render} is called on the control + * - the {@link ngModel.NgModelController#$validators $validators} are run and + * the validation status is set. + * + * This method is called by ngModel internally when the bound scope value changes. + * Application developers usually do not have to call this function themselves. + * + * This function can be used when the `$viewValue` or the rendered DOM value are not correctly + * formatted and the `$modelValue` must be run through the `$formatters` again. + * + * @example + * Consider a text input with an autocomplete list (for fruit), where the items are + * objects with a name and an id. + * A user enters `ap` and then selects `Apricot` from the list. + * Based on this, the autocomplete widget will call `$setViewValue({name: 'Apricot', id: 443})`, + * but the rendered value will still be `ap`. + * The widget can then call `ctrl.$processModelValue()` to run the model -> view + * pipeline again, which formats the object to the string `Apricot`, + * then updates the `$viewValue`, and finally renders it in the DOM. + * + * + +
+
+ Search Fruit: + +
+
+ Model:
+
{{selectedFruit | json}}
+
+
-
+ + angular.module('inputExample', []) + .controller('inputController', function($scope) { + $scope.items = [ + {name: 'Apricot', id: 443}, + {name: 'Clementine', id: 972}, + {name: 'Durian', id: 169}, + {name: 'Jackfruit', id: 982}, + {name: 'Strawberry', id: 863} + ]; + }) + .component('basicAutocomplete', { + bindings: { + items: '<', + onSelect: '&' + }, + templateUrl: 'autocomplete.html', + controller: function($element, $scope) { + var that = this; + var ngModel; + + that.$postLink = function() { + ngModel = $element.find('input').controller('ngModel'); + + ngModel.$formatters.push(function(value) { + return (value && value.name) || value; + }); - ## Animations + ngModel.$parsers.push(function(value) { + var match = value; + for (var i = 0; i < that.items.length; i++) { + if (that.items[i].name === value) { + match = that.items[i]; + break; + } + } - The example below demonstrates how to perform animations using ngClass. + return match; + }); + }; - - - - -
- Sample Text + that.selectItem = function(item) { + ngModel.$setViewValue(item); + ngModel.$processModelValue(); + that.onSelect({item: item}); + }; + } + });
- - .base-class { - -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - } - - .base-class.my-class { - color: red; - font-size:3em; - } + +
+ +
    +
  • + +
  • +
+
- - it('should check ng-class', function() { - expect(element(by.css('.base-class')).getAttribute('class')).not. - toMatch(/my-class/); + *
+ * + */ + $processModelValue: function() { + var viewValue = this.$$format(); + + if (this.$viewValue !== viewValue) { + this.$$updateEmptyClasses(viewValue); + this.$viewValue = this.$$lastCommittedViewValue = viewValue; + this.$render(); + // It is possible that model and view value have been updated during render + this.$$runValidators(this.$modelValue, this.$viewValue, noop); + } + }, - element(by.id('setbtn')).click(); + /** + * This method is called internally to run the $formatters on the $modelValue + */ + $$format: function() { + var formatters = this.$formatters, + idx = formatters.length; - expect(element(by.css('.base-class')).getAttribute('class')). - toMatch(/my-class/); + var viewValue = this.$modelValue; + while (idx--) { + viewValue = formatters[idx](viewValue); + } - element(by.id('clearbtn')).click(); + return viewValue; + }, - expect(element(by.css('.base-class')).getAttribute('class')).not. - toMatch(/my-class/); - }); -
-
+ /** + * This method is called internally when the bound scope value changes. + */ + $$setModelValue: function(modelValue) { + this.$modelValue = this.$$rawModelValue = modelValue; + this.$$parserValid = undefined; + this.$processModelValue(); + }, + $$setUpdateOnEvents: function() { + if (this.$$updateEvents) { + this.$$element.off(this.$$updateEvents, this.$$updateEventHandler); + } - ## ngClass and pre-existing CSS3 Transitions/Animations - The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure. - Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder - any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure - to view the step by step details of {@link ngAnimate.$animate#addclass $animate.addClass} and - {@link ngAnimate.$animate#removeclass $animate.removeClass}. - */ -var ngClassDirective = classDirective('', true); + this.$$updateEvents = this.$options.getOption('updateOn'); + if (this.$$updateEvents) { + this.$$element.on(this.$$updateEvents, this.$$updateEventHandler); + } + }, + + $$updateEventHandler: function(ev) { + this.$$debounceViewValueCommit(ev && ev.type); + } +}; + +function setupModelWatcher(ctrl) { + // model -> value + // Note: we cannot use a normal scope.$watch as we want to detect the following: + // 1. scope value is 'a' + // 2. user enters 'b' + // 3. ng-change kicks in and reverts scope value to 'a' + // -> scope value did not change since the last digest as + // ng-change executes in apply phase + // 4. view should be changed back to 'a' + ctrl.$$scope.$watch(function ngModelWatch(scope) { + var modelValue = ctrl.$$ngModelGet(scope); + + // if scope model value and ngModel value are out of sync + // This cannot be moved to the action function, because it would not catch the + // case where the model is changed in the ngChange function or the model setter + if (modelValue !== ctrl.$modelValue && + // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator + // eslint-disable-next-line no-self-compare + (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue) + ) { + ctrl.$$setModelValue(modelValue); + } + + return modelValue; + }); +} /** - * @ngdoc directive - * @name ngClassOdd - * @restrict AC + * @ngdoc method + * @name ngModel.NgModelController#$setValidity * * @description - * The `ngClassOdd` and `ngClassEven` directives work exactly as - * {@link ng.directive:ngClass ngClass}, except they work in - * conjunction with `ngRepeat` and take effect only on odd (even) rows. - * - * This directive can be applied only within the scope of an - * {@link ng.directive:ngRepeat ngRepeat}. - * - * @element ANY - * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result - * of the evaluation can be a string representing space delimited class names or an array. - * - * @example - - -
    -
  1. - - {{name}} - -
  2. -
-
- - .odd { - color: red; - } - .even { - color: blue; - } - - - it('should check ng-class-odd and ng-class-even', function() { - expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). - toMatch(/odd/); - expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). - toMatch(/even/); - }); - -
+ * Change the validity state, and notify the form. + * + * This method can be called within $parsers/$formatters or a custom validation implementation. + * However, in most cases it should be sufficient to use the `ngModel.$validators` and + * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically. + * + * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned + * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]` + * (for unfulfilled `$asyncValidators`), so that it is available for data-binding. + * The `validationErrorKey` should be in camelCase and will get converted into dash-case + * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error` + * classes and can be bound to as `{{ someForm.someControl.$error.myError }}`. + * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined), + * or skipped (null). Pending is used for unfulfilled `$asyncValidators`. + * Skipped is used by AngularJS when validators do not run because of parse errors and + * when `$asyncValidators` do not run because any of the `$validators` failed. */ -var ngClassOddDirective = classDirective('Odd', 0); +addSetValidityMethod({ + clazz: NgModelController, + set: function(object, property) { + object[property] = true; + }, + unset: function(object, property) { + delete object[property]; + } +}); + /** * @ngdoc directive - * @name ngClassEven - * @restrict AC + * @name ngModel + * @restrict A + * @priority 1 + * @param {expression} ngModel assignable {@link guide/expression Expression} to bind to. * * @description - * The `ngClassOdd` and `ngClassEven` directives work exactly as - * {@link ng.directive:ngClass ngClass}, except they work in - * conjunction with `ngRepeat` and take effect only on odd (even) rows. + * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a + * property on the scope using {@link ngModel.NgModelController NgModelController}, + * which is created and exposed by this directive. * - * This directive can be applied only within the scope of an - * {@link ng.directive:ngRepeat ngRepeat}. + * `ngModel` is responsible for: * - * @element ANY - * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The - * result of the evaluation can be a string representing space delimited class names or an array. + * - Binding the view into the model, which other directives such as `input`, `textarea` or `select` + * require. + * - Providing validation behavior (i.e. required, number, email, url). + * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors). + * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, + * `ng-untouched`, `ng-empty`, `ng-not-empty`) including animations. + * - Registering the control with its parent {@link ng.directive:form form}. * - * @example - - -
    -
  1. - - {{name}}       - -
  2. -
-
- - .odd { - color: red; - } - .even { - color: blue; - } - - - it('should check ng-class-odd and ng-class-even', function() { - expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')). - toMatch(/odd/); - expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')). - toMatch(/even/); - }); - -
- */ -var ngClassEvenDirective = classDirective('Even', 1); - -/** - * @ngdoc directive - * @name ngCloak - * @restrict AC + * Note: `ngModel` will try to bind to the property given by evaluating the expression on the + * current scope. If the property doesn't already exist on this scope, it will be created + * implicitly and added to the scope. * - * @description - * The `ngCloak` directive is used to prevent the Angular html template from being briefly - * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this - * directive to avoid the undesirable flicker effect caused by the html template display. + * For best practices on using `ngModel`, see: * - * The directive can be applied to the `` element, but the preferred usage is to apply - * multiple `ngCloak` directives to small portions of the page to permit progressive rendering - * of the browser view. + * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes) * - * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and - * `angular.min.js`. - * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). + * For basic examples, how to use `ngModel`, see: * - * ```css - * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { - * display: none !important; - * } - * ``` + * - {@link ng.directive:input input} + * - {@link input[text] text} + * - {@link input[checkbox] checkbox} + * - {@link input[radio] radio} + * - {@link input[number] number} + * - {@link input[email] email} + * - {@link input[url] url} + * - {@link input[date] date} + * - {@link input[datetime-local] datetime-local} + * - {@link input[time] time} + * - {@link input[month] month} + * - {@link input[week] week} + * - {@link ng.directive:select select} + * - {@link ng.directive:textarea textarea} * - * When this css rule is loaded by the browser, all html elements (including their children) that - * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive - * during the compilation of the template it deletes the `ngCloak` element attribute, making - * the compiled element visible. + * ## Complex Models (objects or collections) * - * For the best result, the `angular.js` script must be loaded in the head section of the html - * document; alternatively, the css rule above must be included in the external stylesheet of the - * application. + * By default, `ngModel` watches the model by reference, not value. This is important to know when + * binding inputs to models that are objects (e.g. `Date`) or collections (e.g. arrays). If only properties of the + * object or collection change, `ngModel` will not be notified and so the input will not be re-rendered. * - * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they - * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css - * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below. + * The model must be assigned an entirely new object or collection before a re-rendering will occur. * - * @element ANY + * Some directives have options that will cause them to use a custom `$watchCollection` on the model expression + * - for example, `ngOptions` will do so when a `track by` clause is included in the comprehension expression or + * if the select is given the `multiple` attribute. * - * @example - - -
{{ 'hello' }}
-
{{ 'hello IE7' }}
-
- - it('should remove the template directive and css class', function() { - expect($('#template1').getAttribute('ng-cloak')). - toBeNull(); - expect($('#template2').getAttribute('ng-cloak')). - toBeNull(); - }); - -
+ * The `$watchCollection()` method only does a shallow comparison, meaning that changing properties deeper than the + * first level of the object (or only changing the properties of an item in the collection if it's an array) will still + * not trigger a re-rendering of the model. * - */ -var ngCloakDirective = ngDirective({ - compile: function(element, attr) { - attr.$set('ngCloak', undefined); - element.removeClass('ng-cloak'); - } -}); - -/** - * @ngdoc directive - * @name ngController + * ## CSS classes + * The following CSS classes are added and removed on the associated input/select/textarea element + * depending on the validity of the model. * - * @description - * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular - * supports the principles behind the Model-View-Controller design pattern. + * - `ng-valid`: the model is valid + * - `ng-invalid`: the model is invalid + * - `ng-valid-[key]`: for each valid key added by `$setValidity` + * - `ng-invalid-[key]`: for each invalid key added by `$setValidity` + * - `ng-pristine`: the control hasn't been interacted with yet + * - `ng-dirty`: the control has been interacted with + * - `ng-touched`: the control has been blurred + * - `ng-untouched`: the control hasn't been blurred + * - `ng-pending`: any `$asyncValidators` are unfulfilled + * - `ng-empty`: the view does not contain a value or the value is deemed "empty", as defined + * by the {@link ngModel.NgModelController#$isEmpty} method + * - `ng-not-empty`: the view contains a non-empty value * - * MVC components in angular: + * Keep in mind that ngAnimate can detect each of these classes when added and removed. * - * * Model — The Model is scope properties; scopes are attached to the DOM where scope properties - * are accessed through bindings. - * * View — The template (HTML with data bindings) that is rendered into the View. - * * Controller — The `ngController` directive specifies a Controller class; the class contains business - * logic behind the application to decorate the scope with functions and values + * @animations + * Animations within models are triggered when any of the associated CSS classes are added and removed + * on the input element which is attached to the model. These classes include: `.ng-pristine`, `.ng-dirty`, + * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself. + * The animations that are triggered within ngModel are similar to how they work in ngClass and + * animations can be hooked into using CSS transitions, keyframes as well as JS animations. * - * Note that you can also attach controllers to the DOM by declaring it in a route definition - * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller - * again using `ng-controller` in the template itself. This will cause the controller to be attached - * and executed twice. + * The following example shows a simple way to utilize CSS transitions to style an input element + * that has been rendered as invalid after it has been validated: * - * @element ANY - * @scope - * @param {expression} ngController Name of a globally accessible constructor function or an - * {@link guide/expression expression} that on the current scope evaluates to a - * constructor function. The controller instance can be published into a scope property - * by specifying `as propertyName`. + *
+ * //be sure to include ngAnimate as a module to hook into more
+ * //advanced animations
+ * .my-input {
+ *   transition:0.5s linear all;
+ *   background: white;
+ * }
+ * .my-input.ng-invalid {
+ *   background: red;
+ *   color:white;
+ * }
+ * 
* * @example - * Here is a simple form for editing user contact information. Adding, removing, clearing, and - * greeting are methods declared on the controller (see source tab). These methods can - * easily be called from the angular markup. Notice that the scope becomes the `this` for the - * controller's instance. This allows for easy access to the view data from the controller. Also - * notice that any changes to the data are automatically reflected in the View without the need - * for a manual update. The example is shown in two different declaration styles you may use - * according to preference. - + * ### Basic Usage + * - -
- Name: - [ greet ]
- Contact: -
    -
  • - - - [ clear - | X ] -
  • -
  • [ add ]
  • -
-
-
- - it('should check controller as', function() { - var container = element(by.id('ctrl-as-exmpl')); - - expect(container.findElement(by.model('settings.name')) - .getAttribute('value')).toBe('John Smith'); - - var firstRepeat = - container.findElement(by.repeater('contact in settings.contacts').row(0)); - var secondRepeat = - container.findElement(by.repeater('contact in settings.contacts').row(1)); - - expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value')) - .toBe('408 555 1212'); - expect(secondRepeat.findElement(by.model('contact.value')).getAttribute('value')) - .toBe('john.smith@example.org'); - - firstRepeat.findElement(by.linkText('clear')).click(); - - expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value')) - .toBe(''); - - container.findElement(by.linkText('add')).click(); - - expect(container.findElement(by.repeater('contact in settings.contacts').row(2)) - .findElement(by.model('contact.value')) - .getAttribute('value')) - .toBe('yourname@example.org'); - }); + + +

+ Update input to see transitions when valid/invalid. + Integer is a valid value. +

+
+ +
-
- - - -
- Name: - [ greet ]
- Contact: -
    -
  • - - - [ clear - | X ] -
  • -
  • [ add ]
  • -
-
+ *
+ * + * @example + * ### Binding to a getter/setter + * + * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a + * function that returns a representation of the model when called with zero arguments, and sets + * the internal state of a model when called with an argument. It's sometimes useful to use this + * for models that have an internal representation that's different from what the model exposes + * to the view. + * + *
+ * **Best Practice:** It's best to keep getters fast because AngularJS is likely to call them more + * frequently than other parts of your code. + *
+ * + * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that + * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to + * a `
`, which will enable this behavior for all ``s within it. See + * {@link ng.directive:ngModelOptions `ngModelOptions`} for more. + * + * The following example shows how to use `ngModel` with a getter/setter: + * + * @example + * + +
+ + + +
user.name = 
+
- - it('should check controller', function() { - var container = element(by.id('ctrl-exmpl')); + + angular.module('getterSetterExample', []) + .controller('ExampleController', ['$scope', function($scope) { + var _name = 'Brian'; + $scope.user = { + name: function(newName) { + // Note that newName can be undefined for two reasons: + // 1. Because it is called as a getter and thus called with no arguments + // 2. Because the property should actually be set to undefined. This happens e.g. if the + // input is invalid + return arguments.length ? (_name = newName) : _name; + } + }; + }]); + + *
+ */ +var ngModelDirective = ['$rootScope', function($rootScope) { + return { + restrict: 'A', + require: ['ngModel', '^?form', '^?ngModelOptions'], + controller: NgModelController, + // Prelink needs to run before any input directive + // so that we can set the NgModelOptions in NgModelController + // before anyone else uses it. + priority: 1, + compile: function ngModelCompile(element) { + // Setup initial state of the control + element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS); + + return { + pre: function ngModelPreLink(scope, element, attr, ctrls) { + var modelCtrl = ctrls[0], + formCtrl = ctrls[1] || modelCtrl.$$parentForm, + optionsCtrl = ctrls[2]; - expect(container.findElement(by.model('name')) - .getAttribute('value')).toBe('John Smith'); + if (optionsCtrl) { + modelCtrl.$options = optionsCtrl.$options; + } - var firstRepeat = - container.findElement(by.repeater('contact in contacts').row(0)); - var secondRepeat = - container.findElement(by.repeater('contact in contacts').row(1)); + modelCtrl.$$initGetterSetters(); - expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value')) - .toBe('408 555 1212'); - expect(secondRepeat.findElement(by.model('contact.value')).getAttribute('value')) - .toBe('john.smith@example.org'); + // notify others, especially parent forms + formCtrl.$addControl(modelCtrl); - firstRepeat.findElement(by.linkText('clear')).click(); + attr.$observe('name', function(newValue) { + if (modelCtrl.$name !== newValue) { + modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue); + } + }); - expect(firstRepeat.findElement(by.model('contact.value')).getAttribute('value')) - .toBe(''); + scope.$on('$destroy', function() { + modelCtrl.$$parentForm.$removeControl(modelCtrl); + }); + }, + post: function ngModelPostLink(scope, element, attr, ctrls) { + var modelCtrl = ctrls[0]; + modelCtrl.$$setUpdateOnEvents(); - container.findElement(by.linkText('add')).click(); + function setTouched() { + modelCtrl.$setTouched(); + } - expect(container.findElement(by.repeater('contact in contacts').row(2)) - .findElement(by.model('contact.value')) - .getAttribute('value')) - .toBe('yourname@example.org'); - }); - -
+ element.on('blur', function() { + if (modelCtrl.$touched) return; - */ -var ngControllerDirective = [function() { - return { - scope: true, - controller: '@', - priority: 500 + if ($rootScope.$$phase) { + scope.$evalAsync(setTouched); + } else { + scope.$apply(setTouched); + } + }); + } + }; + } }; }]; +/* exported defaultModelOptions */ +var defaultModelOptions; +var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/; + /** - * @ngdoc directive - * @name ngCsp - * - * @element html + * @ngdoc type + * @name ModelOptions * @description - * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support. - * - * This is necessary when developing things like Google Chrome Extensions. - * - * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things). - * For us to be compatible, we just need to implement the "getterFn" in $parse without violating - * any of these restrictions. - * - * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp` - * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will - * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will - * be raised. - * - * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically - * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}). - * To make those directives work in CSP mode, include the `angular-csp.css` manually. - * - * In order to use this feature put the `ngCsp` directive on the root element of the application. - * - * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.* - * - * @example - * This example shows how to apply the `ngCsp` directive to the `html` tag. - ```html - - - ... - ... - - ``` + * A container for the options set by the {@link ngModelOptions} directive */ +function ModelOptions(options) { + this.$$options = options; +} -// ngCsp is not implemented as a proper directive any more, because we need it be processed while we bootstrap -// the system (before $parse is instantiated), for this reason we just have a csp() fn that looks for ng-csp attribute -// anywhere in the current doc +ModelOptions.prototype = { -/** - * @ngdoc directive - * @name ngClick - * - * @description - * The ngClick directive allows you to specify custom behavior when - * an element is clicked. - * - * @element ANY - * @priority 0 - * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon - * click. ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @example - - - - count: {{count}} - - - it('should check ng-click', function() { - expect(element(by.binding('count')).getText()).toMatch('0'); - element(by.css('button')).click(); - expect(element(by.binding('count')).getText()).toMatch('1'); - }); - - - */ -/* - * A directive that allows creation of custom onclick handlers that are defined as angular - * expressions and are compiled and executed within the current scope. - * - * Events that are handled via these handler are always configured not to propagate further. - */ -var ngEventDirectives = {}; -forEach( - 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), - function(name) { - var directiveName = directiveNormalize('ng-' + name); - ngEventDirectives[directiveName] = ['$parse', function($parse) { - return { - compile: function($element, attr) { - var fn = $parse(attr[directiveName]); - return function(scope, element, attr) { - element.on(lowercase(name), function(event) { - scope.$apply(function() { - fn(scope, {$event:event}); - }); - }); - }; + /** + * @ngdoc method + * @name ModelOptions#getOption + * @param {string} name the name of the option to retrieve + * @returns {*} the value of the option + * @description + * Returns the value of the given option + */ + getOption: function(name) { + return this.$$options[name]; + }, + + /** + * @ngdoc method + * @name ModelOptions#createChild + * @param {Object} options a hash of options for the new child that will override the parent's options + * @return {ModelOptions} a new `ModelOptions` object initialized with the given options. + */ + createChild: function(options) { + var inheritAll = false; + + // make a shallow copy + options = extend({}, options); + + // Inherit options from the parent if specified by the value `"$inherit"` + forEach(options, /** @this */ function(option, key) { + if (option === '$inherit') { + if (key === '*') { + inheritAll = true; + } else { + options[key] = this.$$options[key]; + // `updateOn` is special so we must also inherit the `updateOnDefault` option + if (key === 'updateOn') { + options.updateOnDefault = this.$$options.updateOnDefault; + } } - }; - }]; + } else { + if (key === 'updateOn') { + // If the `updateOn` property contains the `default` event then we have to remove + // it from the event list and set the `updateOnDefault` flag. + options.updateOnDefault = false; + options[key] = trim(option.replace(DEFAULT_REGEXP, function() { + options.updateOnDefault = true; + return ' '; + })); + } + } + }, this); + + if (inheritAll) { + // We have a property of the form: `"*": "$inherit"` + delete options['*']; + defaults(options, this.$$options); + } + + // Finally add in any missing defaults + defaults(options, defaultModelOptions.$$options); + + return new ModelOptions(options); } -); +}; -/** - * @ngdoc directive - * @name ngDblclick - * - * @description - * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. - * - * @element ANY - * @priority 0 - * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon - * a dblclick. (The Event object is available as `$event`) - * - * @example - - - - count: {{count}} - - - */ + +defaultModelOptions = new ModelOptions({ + updateOn: '', + updateOnDefault: true, + debounce: 0, + getterSetter: false, + allowInvalid: false, + timezone: null +}); /** * @ngdoc directive - * @name ngMousedown + * @name ngModelOptions + * @restrict A + * @priority 10 * * @description - * The ngMousedown directive allows you to specify custom behavior on mousedown event. + * This directive allows you to modify the behaviour of {@link ngModel} directives within your + * application. You can specify an `ngModelOptions` directive on any element. All {@link ngModel} + * directives will use the options of their nearest `ngModelOptions` ancestor. * - * @element ANY - * @priority 0 - * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon - * mousedown. ({@link guide/expression#-event- Event object is available as `$event`}) + * The `ngModelOptions` settings are found by evaluating the value of the attribute directive as + * an AngularJS expression. This expression should evaluate to an object, whose properties contain + * the settings. For example: `
- - - count: {{count}} - - - */ - - -/** - * @ngdoc directive - * @name ngMouseup + * ## Inheriting Options * - * @description - * Specify custom behavior on mouseup event. + * You can specify that an `ngModelOptions` setting should be inherited from a parent `ngModelOptions` + * directive by giving it the value of `"$inherit"`. + * Then it will inherit that setting from the first `ngModelOptions` directive found by traversing up the + * DOM tree. If there is no ancestor element containing an `ngModelOptions` directive then default settings + * will be used. * - * @element ANY - * @priority 0 - * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon - * mouseup. ({@link guide/expression#-event- Event object is available as `$event`}) + * For example given the following fragment of HTML * - * @example - - - - count: {{count}} - - - */ - -/** - * @ngdoc directive - * @name ngMouseover * - * @description - * Specify custom behavior on mouseover event. + * ```html + *
+ *
+ * + *
+ *
+ * ``` * - * @element ANY - * @priority 0 - * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon - * mouseover. ({@link guide/expression#-event- Event object is available as `$event`}) + * the `input` element will have the following settings * - * @example - - - - count: {{count}} - - - */ - - -/** - * @ngdoc directive - * @name ngMouseenter + * ```js + * { allowInvalid: true, updateOn: 'default', debounce: 0 } + * ``` * - * @description - * Specify custom behavior on mouseenter event. + * Notice that the `debounce` setting was not inherited and used the default value instead. * - * @element ANY - * @priority 0 - * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon - * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`}) + * You can specify that all undefined settings are automatically inherited from an ancestor by + * including a property with key of `"*"` and value of `"$inherit"`. * - * @example - - - - count: {{count}} - - - */ - - -/** - * @ngdoc directive - * @name ngMouseleave + * For example given the following fragment of HTML * - * @description - * Specify custom behavior on mouseleave event. * - * @element ANY - * @priority 0 - * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon - * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`}) + * ```html + *
+ *
+ * + *
+ *
+ * ``` * - * @example - - - - count: {{count}} - - - */ - - -/** - * @ngdoc directive - * @name ngMousemove + * the `input` element will have the following settings * - * @description - * Specify custom behavior on mousemove event. + * ```js + * { allowInvalid: true, updateOn: 'default', debounce: 200 } + * ``` * - * @element ANY - * @priority 0 - * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon - * mousemove. ({@link guide/expression#-event- Event object is available as `$event`}) + * Notice that the `debounce` setting now inherits the value from the outer `
` element. * - * @example - - - - count: {{count}} - - - */ - - -/** - * @ngdoc directive - * @name ngKeydown + * If you are creating a reusable component then you should be careful when using `"*": "$inherit"` + * since you may inadvertently inherit a setting in the future that changes the behavior of your component. * - * @description - * Specify custom behavior on keydown event. * - * @element ANY - * @priority 0 - * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon - * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * ## Triggering and debouncing model updates * - * @example - - - - key down count: {{count}} - - - */ - - -/** - * @ngdoc directive - * @name ngKeyup + * The `updateOn` and `debounce` properties allow you to specify a custom list of events that will + * trigger a model update and/or a debouncing delay so that the actual update only takes place when + * a timer expires; this timer will be reset after another change takes place. * - * @description - * Specify custom behavior on keyup event. + * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might + * be different from the value in the actual model. This means that if you update the model you + * should also invoke {@link ngModel.NgModelController#$rollbackViewValue} on the relevant input field in + * order to make sure it is synchronized with the model and that any debounced action is canceled. * - * @element ANY - * @priority 0 - * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon - * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.) + * The easiest way to reference the control's {@link ngModel.NgModelController#$rollbackViewValue} + * method is by making sure the input is placed inside a form that has a `name` attribute. This is + * important because `form` controllers are published to the related scope under the name in their + * `name` attribute. * - * @example - - - - key up count: {{count}} - - - */ - - -/** - * @ngdoc directive - * @name ngKeypress + * Any pending changes will take place immediately when an enclosing form is submitted via the + * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit` + * to have access to the updated model. * - * @description - * Specify custom behavior on keypress event. + * ### Overriding immediate updates * - * @element ANY - * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon - * keypress. ({@link guide/expression#-event- Event object is available as `$event`} - * and can be interrogated for keyCode, altKey, etc.) + * The following example shows how to override immediate updates. Changes on the inputs within the + * form will update the model only when the control loses focus (blur event). If `escape` key is + * pressed while the input field is focused, the value is reset to the value in the current model. * - * @example - - - - key press count: {{count}} - - - */ - - -/** - * @ngdoc directive - * @name ngSubmit + * + * + *
+ *
+ *
+ *
+ *
+ *
user.name = 
+ *
+ *
+ * + * angular.module('optionsExample', []) + * .controller('ExampleController', ['$scope', function($scope) { + * $scope.user = { name: 'say', data: '' }; + * + * $scope.cancel = function(e) { + * if (e.keyCode === 27) { + * $scope.userForm.userName.$rollbackViewValue(); + * } + * }; + * }]); + * + * + * var model = element(by.binding('user.name')); + * var input = element(by.model('user.name')); + * var other = element(by.model('user.data')); + * + * it('should allow custom events', function() { + * input.sendKeys(' hello'); + * input.click(); + * expect(model.getText()).toEqual('say'); + * other.click(); + * expect(model.getText()).toEqual('say hello'); + * }); * - * @description - * Enables binding angular expressions to onsubmit events. + * it('should $rollbackViewValue when model changes', function() { + * input.sendKeys(' hello'); + * expect(input.getAttribute('value')).toEqual('say hello'); + * input.sendKeys(protractor.Key.ESCAPE); + * expect(input.getAttribute('value')).toEqual('say'); + * other.click(); + * expect(model.getText()).toEqual('say'); + * }); + * + *
* - * Additionally it prevents the default action (which for form means sending the request to the - * server and reloading the current page), but only if the form does not contain `action`, - * `data-action`, or `x-action` attributes. + * ### Debouncing updates * - * @element form - * @priority 0 - * @param {expression} ngSubmit {@link guide/expression Expression} to eval. - * ({@link guide/expression#-event- Event object is available as `$event`}) + * The next example shows how to debounce model changes. Model will be updated only 1 sec after last change. + * If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty. * - * @example - - - -
- Enter text and hit enter: - - -
list={{list}}
-
-
- - it('should check ng-submit', function() { - expect(element(by.binding('list')).getText()).toBe('list=[]'); - element(by.css('#submit')).click(); - expect(element(by.binding('list')).getText()).toContain('hello'); - expect(element(by.input('text')).getAttribute('value')).toBe(''); - }); - it('should ignore empty strings', function() { - expect(element(by.binding('list')).getText()).toBe('list=[]'); - element(by.css('#submit')).click(); - element(by.css('#submit')).click(); - expect(element(by.binding('list')).getText()).toContain('hello'); + * + * + *
+ *
+ * Name: + * + *
+ *
+ *
user.name = 
+ *
+ *
+ * + * angular.module('optionsExample', []) + * .controller('ExampleController', ['$scope', function($scope) { + * $scope.user = { name: 'say' }; + * }]); + * + *
+ * + * ### Default events, extra triggers, and catch-all debounce values + * + * This example shows the relationship between "default" update events and + * additional `updateOn` triggers. + * + * `default` events are those that are bound to the control, and when fired, update the `$viewValue` + * via {@link ngModel.NgModelController#$setViewValue $setViewValue}. Every event that is not listed + * in `updateOn` is considered a "default" event, since different control types have different + * default events. + * + * The control in this example updates by "default", "click", and "blur", with different `debounce` + * values. You can see that "click" doesn't have an individual `debounce` value - + * therefore it uses the `*` debounce value. + * + * There is also a button that calls {@link ngModel.NgModelController#$setViewValue $setViewValue} + * directly with a "custom" event. Since "custom" is not defined in the `updateOn` list, + * it is considered a "default" event and will update the + * control if "default" is defined in `updateOn`, and will receive the "default" debounce value. + * Note that this is just to illustrate how custom controls would possibly call `$setViewValue`. + * + * You can change the `updateOn` and `debounce` configuration to test different scenarios. This + * is done with {@link ngModel.NgModelController#$overrideModelOptions $overrideModelOptions}. + * + + + + + + angular.module('optionsExample', []) + .component('modelUpdateDemo', { + templateUrl: 'template.html', + controller: function() { + this.name = 'Chinua'; + + this.options = { + updateOn: 'default blur click', + debounce: { + default: 2000, + blur: 0, + '*': 1000 + } + }; + + this.updateEvents = function() { + var eventList = this.options.updateOn.split(' '); + eventList.push('*'); + var events = {}; + + for (var i = 0; i < eventList.length; i++) { + events[eventList[i]] = this.options.debounce[eventList[i]]; + } + + this.events = events; + }; + + this.updateOptions = function() { + var options = angular.extend(this.options, { + updateOn: Object.keys(this.events).join(' ').replace('*', ''), + debounce: this.events + }); + + this.form.input.$overrideModelOptions(options); + }; + + // Initialize the event form + this.updateEvents(); + } }); - - - */ +
+ +
+ Input: +
+ Model: {{$ctrl.name}} +
+ + +
+
+ updateOn
+ + + + + + + + + + + +
OptionDebounce value
{{key}}
-/** - * @ngdoc directive - * @name ngFocus +
+ +
+
+
* - * @description - * Specify custom behavior on focus event. * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon - * focus. ({@link guide/expression#-event- Event object is available as `$event`}) + * ## Model updates and validation * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - -/** - * @ngdoc directive - * @name ngBlur + * The default behaviour in `ngModel` is that the model value is set to `undefined` when the + * validation determines that the value is invalid. By setting the `allowInvalid` property to true, + * the model will still be updated even if the value is invalid. * - * @description - * Specify custom behavior on blur event. * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon - * blur. ({@link guide/expression#-event- Event object is available as `$event`}) + * ## Connecting to the scope * - * @example - * See {@link ng.directive:ngClick ngClick} - */ - -/** - * @ngdoc directive - * @name ngCopy + * By setting the `getterSetter` property to true you are telling ngModel that the `ngModel` expression + * on the scope refers to a "getter/setter" function rather than the value itself. * - * @description - * Specify custom behavior on copy event. + * The following example shows how to bind to getter/setters: * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon - * copy. ({@link guide/expression#-event- Event object is available as `$event`}) + * + * + *
+ *
+ * + *
+ *
user.name = 
+ *
+ *
+ * + * angular.module('getterSetterExample', []) + * .controller('ExampleController', ['$scope', function($scope) { + * var _name = 'Brian'; + * $scope.user = { + * name: function(newName) { + * return angular.isDefined(newName) ? (_name = newName) : _name; + * } + * }; + * }]); + * + *
* - * @example - - - - copied: {{copied}} - - - */ - -/** - * @ngdoc directive - * @name ngCut * - * @description - * Specify custom behavior on cut event. + * ## Programmatically changing options * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon - * cut. ({@link guide/expression#-event- Event object is available as `$event`}) + * The `ngModelOptions` expression is only evaluated once when the directive is linked; it is not + * watched for changes. However, it is possible to override the options on a single + * {@link ngModel.NgModelController} instance with + * {@link ngModel.NgModelController#$overrideModelOptions `NgModelController#$overrideModelOptions()`}. + * See also the example for + * {@link ngModelOptions#default-events-extra-triggers-and-catch-all-debounce-values + * Default events, extra triggers, and catch-all debounce values}. * - * @example - - - - cut: {{cut}} - - - */ - -/** - * @ngdoc directive - * @name ngPaste * - * @description - * Specify custom behavior on paste event. + * ## Specifying timezones * - * @element window, input, select, textarea, a - * @priority 0 - * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon - * paste. ({@link guide/expression#-event- Event object is available as `$event`}) + * You can specify the timezone that date/time input directives expect by providing its name in the + * `timezone` property. * - * @example - + * + * ## Formatting the value of `time` and `datetime-local` + * + * With the options `timeSecondsFormat` and `timeStripZeroSeconds` it is possible to adjust the value + * that is displayed in the control. Note that browsers may apply their own formatting + * in the user interface. + * + - - pasted: {{paste}} + - + + angular.module('timeExample', []) + .component('timeExample', { + templateUrl: 'timeExample.html', + controller: function() { + this.time = new Date(1970, 0, 1, 14, 57, 0); + + this.options = { + timeSecondsFormat: 'ss', + timeStripZeroSeconds: true + }; + + this.optionChange = function() { + this.timeForm.timeFormatted.$overrideModelOptions(this.options); + this.time = new Date(this.time); + }; + } + }); + + +
+ Default: +
+ With options: + +
+ + Options:
+ timeSecondsFormat: + +
+ timeStripZeroSeconds: + +
+
+ *
+ * + * @param {Object} ngModelOptions options to apply to {@link ngModel} directives on this element and + * and its descendents. + * + * **General options**: + * + * - `updateOn`: string specifying which event should the input be bound to. You can set several + * events using an space delimited list. There is a special event called `default` that + * matches the default events belonging to the control. These are the events that are bound to + * the control, and when fired, update the `$viewValue` via `$setViewValue`. + * + * `ngModelOptions` considers every event that is not listed in `updateOn` a "default" event, + * since different control types use different default events. + * + * See also the section {@link ngModelOptions#triggering-and-debouncing-model-updates + * Triggering and debouncing model updates}. + * + * - `debounce`: integer value which contains the debounce model update value in milliseconds. A + * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a + * custom value for each event. For example: + * ``` + * ng-model-options="{ + * updateOn: 'default blur', + * debounce: { 'default': 500, 'blur': 0 } + * }" + * ``` + * You can use the `*` key to specify a debounce value that applies to all events that are not + * specifically listed. In the following example, `mouseup` would have a debounce delay of 1000: + * ``` + * ng-model-options="{ + * updateOn: 'default blur mouseup', + * debounce: { 'default': 500, 'blur': 0, '*': 1000 } + * }" + * ``` + * - `allowInvalid`: boolean value which indicates that the model can be set with values that did + * not validate correctly instead of the default behavior of setting the model to undefined. + * - `getterSetter`: boolean value which determines whether or not to treat functions bound to + * `ngModel` as getters/setters. + * + * + * **Input-type specific options**: + * + * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for + * ``, ``, ... . It understands UTC/GMT and the + * continental US time zone abbreviations, but for general use, use a time zone offset, for + * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian) + * If not specified, the timezone of the browser will be used. + * Note that changing the timezone will have no effect on the current date, and is only applied after + * the next input / model change. + * + * - `timeSecondsFormat`: Defines if the `time` and `datetime-local` types should show seconds and + * milliseconds. The option follows the format string of {@link date date filter}. + * By default, the options is `undefined` which is equal to `'ss.sss'` (seconds and milliseconds). + * The other options are `'ss'` (strips milliseconds), and `''` (empty string), which strips both + * seconds and milliseconds. + * Note that browsers that support `time` and `datetime-local` require the hour and minutes + * part of the time string, and may show the value differently in the user interface. + * {@link ngModelOptions#formatting-the-value-of-time-and-datetime-local- See the example}. + * + * - `timeStripZeroSeconds`: Defines if the `time` and `datetime-local` types should strip the + * seconds and milliseconds from the formatted value if they are zero. This option is applied + * after `timeSecondsFormat`. + * This option can be used to make the formatting consistent over different browsers, as some + * browsers with support for `time` will natively hide the milliseconds and + * seconds if they are zero, but others won't, and browsers that don't implement these input + * types will always show the full string. + * {@link ngModelOptions#formatting-the-value-of-time-and-datetime-local- See the example}. + * */ +var ngModelOptionsDirective = function() { + NgModelOptionsController.$inject = ['$attrs', '$scope']; + function NgModelOptionsController($attrs, $scope) { + this.$$attrs = $attrs; + this.$$scope = $scope; + } + NgModelOptionsController.prototype = { + $onInit: function() { + var parentOptions = this.parentCtrl ? this.parentCtrl.$options : defaultModelOptions; + var modelOptionsDefinition = this.$$scope.$eval(this.$$attrs.ngModelOptions); + + this.$options = parentOptions.createChild(modelOptionsDefinition); + } + }; + + return { + restrict: 'A', + // ngModelOptions needs to run before ngModel and input directives + priority: 10, + require: {parentCtrl: '?^^ngModelOptions'}, + bindToController: true, + controller: NgModelOptionsController + }; +}; + + +// shallow copy over values from `src` that are not already specified on `dst` +function defaults(dst, src) { + forEach(src, function(value, key) { + if (!isDefined(dst[key])) { + dst[key] = value; + } + }); +} /** * @ngdoc directive - * @name ngIf - * @restrict A + * @name ngNonBindable + * @restrict AC + * @priority 1000 + * @element ANY * * @description - * The `ngIf` directive removes or recreates a portion of the DOM tree based on an - * {expression}. If the expression assigned to `ngIf` evaluates to a false - * value then the element is removed from the DOM, otherwise a clone of the - * element is reinserted into the DOM. - * - * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the - * element in the DOM rather than changing its visibility via the `display` css property. A common - * case when this difference is significant is when using css selectors that rely on an element's - * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes. - * - * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope - * is created when the element is restored. The scope created within `ngIf` inherits from - * its parent scope using - * [prototypal inheritance](https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance). - * An important implication of this is if `ngModel` is used within `ngIf` to bind to - * a javascript primitive defined in the parent scope. In this case any modifications made to the - * variable within the child scope will override (hide) the value in the parent scope. - * - * Also, `ngIf` recreates elements using their compiled state. An example of this behavior - * is if an element's class attribute is directly modified after it's compiled, using something like - * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element - * the added class will be lost because the original compiled state is used to regenerate the element. - * - * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter` - * and `leave` effects. - * - * @animations - * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container - * leave - happens just before the ngIf contents are removed from the DOM - * - * @element ANY - * @scope - * @priority 600 - * @param {expression} ngIf If the {@link guide/expression expression} is falsy then - * the element is removed from the DOM tree. If it is truthy a copy of the compiled - * element is added to the DOM tree. + * The `ngNonBindable` directive tells AngularJS not to compile or bind the contents of the current + * DOM element, including directives on the element itself that have a lower priority than + * `ngNonBindable`. This is useful if the element contains what appears to be AngularJS directives + * and bindings but which should be ignored by AngularJS. This could be the case if you have a site + * that displays snippets of code, for instance. * * @example - + * In this example there are two locations where a simple interpolation binding (`{{}}`) is present, + * but the one wrapped in `ngNonBindable` is left alone. + * + - Click me:
- Show when checked: - - I'm removed when the checkbox is unchecked. - +
Normal: {{1 + 2}}
+
Ignored: {{1 + 2}}
- - .animate-if { - background:white; - border:1px solid black; - padding:10px; - } - - .animate-if.ng-enter, .animate-if.ng-leave { - -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s; - } - - .animate-if.ng-enter, - .animate-if.ng-leave.ng-leave-active { - opacity:0; - } - - .animate-if.ng-leave, - .animate-if.ng-enter.ng-enter-active { - opacity:1; - } + + it('should check ng-non-bindable', function() { + expect(element(by.binding('1 + 2')).getText()).toContain('3'); + expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/); + });
*/ -var ngIfDirective = ['$animate', function($animate) { - return { - transclude: 'element', - priority: 600, - terminal: true, - restrict: 'A', - $$tlb: true, - link: function ($scope, $element, $attr, ctrl, $transclude) { - var block, childScope, previousElements; - $scope.$watch($attr.ngIf, function ngIfWatchAction(value) { +var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); - if (toBoolean(value)) { - if (!childScope) { - childScope = $scope.$new(); - $transclude(childScope, function (clone) { - clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' '); - // Note: We only need the first/last node of the cloned nodes. - // However, we need to keep the reference to the jqlite wrapper as it might be changed later - // by a directive with templateUrl when it's template arrives. - block = { - clone: clone - }; - $animate.enter(clone, $element.parent(), $element); - }); - } - } else { - if(previousElements) { - previousElements.remove(); - previousElements = null; - } - if(childScope) { - childScope.$destroy(); - childScope = null; - } - if(block) { - previousElements = getBlockElements(block.clone); - $animate.leave(previousElements, function() { - previousElements = null; - }); - block = null; - } - } - }); - } - }; -}]; +/* exported ngOptionsDirective */ + +/* global jqLiteRemove */ + +var ngOptionsMinErr = minErr('ngOptions'); /** * @ngdoc directive - * @name ngInclude - * @restrict ECA + * @name ngOptions + * @restrict A * * @description - * Fetches, compiles and includes an external HTML fragment. * - * By default, the template URL is restricted to the same domain and protocol as the - * application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl - * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols - * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or - * [wrap them](ng.$sce#trustAsResourceUrl) as trusted values. Refer to Angular's {@link - * ng.$sce Strict Contextual Escaping}. + * The `ngOptions` attribute can be used to dynamically generate a list of `` + * DOM element. + * * `disable`: The result of this expression will be used to disable the rendered `