diff --git a/.gitignore b/.gitignore index 5ad4bb98b..f01b25411 100644 --- a/.gitignore +++ b/.gitignore @@ -137,3 +137,5 @@ Tests/Telerik.Sitefinity.Frontend.ClientTest/templates.js 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 5384f74ae..000000000 --- a/.nuget/NuGet.targets +++ /dev/null @@ -1,147 +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/AssemblyInfoShare/SharedAssemblyInfo.cs b/AssemblyInfoShare/SharedAssemblyInfo.cs deleted file mode 100644 index b5c99ae83..000000000 --- a/AssemblyInfoShare/SharedAssemblyInfo.cs +++ /dev/null @@ -1,28 +0,0 @@ -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: AssemblyCompany("Telerik")] -[assembly: AssemblyProduct("Telerik Sitefinity CMS")] -[assembly: AssemblyCopyright("Copyright © Telerik 2015")] -[assembly: AssemblyTrademark("Sitefinity")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.3.350.0")] -[assembly: AssemblyFileVersion("1.3.350.0")] \ No newline at end of file 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/Feather.sln b/Feather.sln index 603ae6fc3..5bde174c4 100644 --- a/Feather.sln +++ b/Feather.sln @@ -1,91 +1,31 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2012 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telerik.Sitefinity.Frontend", "Telerik.Sitefinity.Frontend\Telerik.Sitefinity.Frontend.csproj", "{17ED04C3-0AB9-4055-9908-6C70720DAF77}" +# Visual Studio Version 17 +VisualStudioVersion = 17.4.33205.214 +MinimumVisualStudioVersion = 10.0.40219.1 +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}") = "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(TestCaseManagementSettings) = postSolution - CategoryFile = Feather.vsmdi - EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU - Release Pro|Any CPU = Release Pro|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {17ED04C3-0AB9-4055-9908-6C70720DAF77}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {17ED04C3-0AB9-4055-9908-6C70720DAF77}.Debug|Any CPU.Build.0 = Debug|Any CPU - {17ED04C3-0AB9-4055-9908-6C70720DAF77}.Release Pro|Any CPU.ActiveCfg = Release|Any CPU - {17ED04C3-0AB9-4055-9908-6C70720DAF77}.Release Pro|Any CPU.Build.0 = Release|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 Pro|Any CPU.ActiveCfg = Release|Any CPU - {889A8B70-2B62-472A-AB7C-33CA9A7F48A0}.Release Pro|Any CPU.Build.0 = Release|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 Pro|Any CPU.ActiveCfg = Release|Any CPU - {49B06F58-0510-4279-B6F1-90F23AB3768D}.Release Pro|Any CPU.Build.0 = Release|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 Pro|Any CPU.ActiveCfg = Release|Any CPU - {1C663AB5-AEBC-41B5-A861-F635C37DAB47}.Release Pro|Any CPU.Build.0 = Release|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 Pro|Any CPU.ActiveCfg = Release|Any CPU - {637A9A4D-A6D1-4C84-9A00-58AA440C2D58}.Release Pro|Any CPU.Build.0 = Release|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 Pro|Any CPU.ActiveCfg = Release|Any CPU - {D607959E-5DE3-43B9-8731-C22E495FCEF7}.Release Pro|Any CPU.Build.0 = Release|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 - {637A9A4D-A6D1-4C84-9A00-58AA440C2D58} = {EFF407A4-62ED-4B78-9573-7F65D70482C6} - {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} - {D607959E-5DE3-43B9-8731-C22E495FCEF7} = {D7E812B2-E16E-4B90-9EF8-1C5F9F907E96} + 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 bf28f89d1..000000000 --- a/FxCop/CustomDictionary.xml +++ /dev/null @@ -1,587 +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 - Templatable - - - - 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 f44a1861e..000000000 --- a/FxCop/Feather.ruleset +++ /dev/null @@ -1,371 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Gruntfile.js b/Gruntfile.js deleted file mode 100644 index 2ed817f53..000000000 --- a/Gruntfile.js +++ /dev/null @@ -1,89 +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/client-components/**/*.js', - 'Tests/Telerik.Sitefinity.Frontend.ClientTest/unit/**/*.js' - ] - }, - - jasmine: { - unit:{ - src: [ - 'Tests/Telerik.Sitefinity.Frontend.ClientTest/templates.js', - 'Telerik.Sitefinity.Frontend/Designers/Scripts/*.js', - 'Telerik.Sitefinity.Frontend/MVC/Scripts/Designer/*.js', - 'Telerik.Sitefinity.Frontend/MVC/Scripts/*.js', - 'Telerik.Sitefinity.Frontend/client-components/selectors/common/sf-services.js', - 'Telerik.Sitefinity.Frontend/client-components/selectors/common/sf-selectors.js', - 'Telerik.Sitefinity.Frontend/client-components/selectors/common/sf-list-selector.js', - 'Telerik.Sitefinity.Frontend/client-components/selectors/common/sf-items-tree.js', - 'Telerik.Sitefinity.Frontend/client-components/selectors/common/sf-selected-items-view.js', - 'Telerik.Sitefinity.Frontend/client-components/fields/sf-fields.js', - 'Telerik.Sitefinity.Frontend/client-components/**/*.js', - '!Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor.js', - 'Tests/Telerik.Sitefinity.Frontend.ClientTest/helpers/mocks/*.js'], - options: { - vendor:[ - 'Tests/Telerik.Sitefinity.Frontend.ClientTest/helpers/jquery.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/helpers/kendo.all.min.js', - 'Tests/Telerik.Sitefinity.Frontend.ClientTest/helpers/common-methods.js', - 'Tests/Telerik.Sitefinity.Frontend.ClientTest/helpers/jasmine-matchers.js', - 'Telerik.Sitefinity.Frontend/MVC/Scripts/Bootstrap/js/*.js', - '!Telerik.Sitefinity.Frontend/Mvc/Scripts/Angular/**', - 'Telerik.Sitefinity.Frontend/MVC/Scripts/ng-tags-input.min/ng-tags-input.min.js' - ], - specs: ['Tests/Telerik.Sitefinity.Frontend.ClientTest/unit/**/*.js'], - junit: { - path: 'Tests/Telerik.Sitefinity.Frontend.ClientTest/TestResults' - }, - 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/client-components/**/*.html', 'Telerik.Sitefinity.Frontend/client-components/**/*.sf-cshtml'], - 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 87f9d18c8..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 © 2015 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 2672422e7..3c8c4b347 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,12 @@ This repository contains the core infrastructure related to [Project Feather](ht | Feather version | Sitefinity version | |----|----| -| v.1.3.300.1 - latest | 8.1.5800.0 to 8.1.9999 | +| 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 | @@ -35,7 +40,7 @@ This repository contains the core infrastructure related to [Project Feather](ht [Upgrade Instructions](https://github.com/Sitefinity/feather/wiki/upgrade-instructions) - Upgrade your existing Feather projects following this guide -[What's new](https://github.com/Sitefinity/feather/wiki/What's-new) - See what's new in Feather +[What's new](https://github.com/Sitefinity/feather/releases/latest) - See what's new in Feather [Documentation Home](https://github.com/Sitefinity/feather/wiki) - See full project Feather documentation in the wiki @@ -43,7 +48,7 @@ This repository contains the core infrastructure related to [Project Feather](ht 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 © 2015 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 2ea453b5b..000000000 --- a/Settings.StyleCop +++ /dev/null @@ -1,294 +0,0 @@ - - - NoMerge - - \..\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 - - - - - - - - - - False - - - - - - - - - id - is - ui - - - - - \ 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 98% rename from Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileData.cs rename to Telerik.Sitefinity.Frontend.Data/FileData.cs index b1e6fc784..e768d93e6 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileData.cs +++ b/Telerik.Sitefinity.Frontend.Data/FileData.cs @@ -8,7 +8,7 @@ namespace Telerik.Sitefinity.Frontend.FilesMonitoring.Data /// [Persistent] [ManagerType(typeof(FileMonitorDataManager))] - internal class FileData + public class FileData { #region Contructors diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorDataManager.cs b/Telerik.Sitefinity.Frontend.Data/FileMonitorDataManager.cs similarity index 98% rename from Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorDataManager.cs rename to Telerik.Sitefinity.Frontend.Data/FileMonitorDataManager.cs index 44fd8c84e..620a406ce 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorDataManager.cs +++ b/Telerik.Sitefinity.Frontend.Data/FileMonitorDataManager.cs @@ -10,7 +10,7 @@ namespace Telerik.Sitefinity.Frontend.FilesMonitoring.Data /// /// Represents the data manager for the file monitoring functionality. /// - internal class FileMonitorDataManager : ManagerBase + public class FileMonitorDataManager : ManagerBase { #region Constructors /// diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorDataProvider.cs b/Telerik.Sitefinity.Frontend.Data/FileMonitorDataProvider.cs similarity index 98% rename from Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorDataProvider.cs rename to Telerik.Sitefinity.Frontend.Data/FileMonitorDataProvider.cs index 5fcfe83c9..2256d2795 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorDataProvider.cs +++ b/Telerik.Sitefinity.Frontend.Data/FileMonitorDataProvider.cs @@ -8,7 +8,7 @@ namespace Telerik.Sitefinity.Frontend.FilesMonitoring.Data /// Represents the data provider for the file monitoring functionality. /// [Telerik.Microsoft.Practices.Unity.InterceptionExtension.ApplyNoPolicies] - internal abstract class FileMonitorDataProvider : DataProviderBase + public abstract class FileMonitorDataProvider : DataProviderBase { #region Public methods diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorFluentMapping.cs b/Telerik.Sitefinity.Frontend.Data/FileMonitorFluentMapping.cs similarity index 87% rename from Telerik.Sitefinity.Frontend/FilesMonitoring/Data/FileMonitorFluentMapping.cs rename to Telerik.Sitefinity.Frontend.Data/FileMonitorFluentMapping.cs index 010eb5eb6..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 @@ -8,7 +9,7 @@ namespace Telerik.Sitefinity.Frontend.FilesMonitoring.Data /// /// A concrete implementation of the for the file monitoring. /// - internal class FileMonitorFluentMapping : OpenAccessFluentMappingBase + public class FileMonitorFluentMapping : OpenAccessFluentMappingBase { #region Contructors @@ -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 94% rename from Telerik.Sitefinity.Frontend/FilesMonitoring/Data/OpenAccessFileMonitorDataProvider.cs rename to Telerik.Sitefinity.Frontend.Data/OpenAccessFileMonitorDataProvider.cs index 43f00c80e..745659edc 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/Data/OpenAccessFileMonitorDataProvider.cs +++ b/Telerik.Sitefinity.Frontend.Data/OpenAccessFileMonitorDataProvider.cs @@ -8,7 +8,7 @@ namespace Telerik.Sitefinity.Frontend.FilesMonitoring.Data /// /// OpenAccess implementation of the . /// - internal class OpenAccessFileMonitorDataProvider : FileMonitorDataProvider, IOpenAccessDataProvider, IOpenAccessUpgradableProvider + public class OpenAccessFileMonitorDataProvider : FileMonitorDataProvider, IOpenAccessDataProvider, IOpenAccessUpgradableProvider { #region Upgrade diff --git a/Tests/Telerik.Sitefinity.Frontend.ClientTest/Properties/AssemblyInfo.cs b/Telerik.Sitefinity.Frontend.Data/Properties/AssemblyInfo.cs similarity index 70% rename from Tests/Telerik.Sitefinity.Frontend.ClientTest/Properties/AssemblyInfo.cs rename to Telerik.Sitefinity.Frontend.Data/Properties/AssemblyInfo.cs index 42868e033..de8521556 100644 --- a/Tests/Telerik.Sitefinity.Frontend.ClientTest/Properties/AssemblyInfo.cs +++ b/Telerik.Sitefinity.Frontend.Data/Properties/AssemblyInfo.cs @@ -1,10 +1,10 @@ using System.Reflection; using System.Runtime.InteropServices; -// General Information about an assembly is controlled through the following +// 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.ClientTest")] +[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("01b70fb0-dd5b-44d4-a09b-e6f85c8ae946")] +[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 73b4e79bf..e4012c865 100644 --- a/Telerik.Sitefinity.Frontend/Designers/DesignerInitializer.cs +++ b/Telerik.Sitefinity.Frontend/Designers/DesignerInitializer.cs @@ -1,10 +1,13 @@ 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.Services; using Telerik.Sitefinity.Web.UI; @@ -14,21 +17,21 @@ namespace Telerik.Sitefinity.Frontend.Designers /// /// This class contains logic for initializing the MVC designer. /// - internal 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}/Master/{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}/View/{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()); @@ -37,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. /// @@ -45,11 +57,12 @@ 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(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.min.js")); + @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) @@ -57,11 +70,10 @@ private void RegisteringScriptsHandler(IScriptsRegisteringEvent @event) //// @event.Scripts.Add(scriptRef); ////} - @event.Scripts.Add(new ScriptReference(scriptRootPath + "Mvc/Scripts/Kendo/kendo.all.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/LABjs/LAB.min.js")); + @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"))); + + @event.Scripts.Add(new ScriptReference(UrlHelpers.AppendVersion(scriptRootPath + "Mvc/Scripts/LABjs/LAB.min.js"))); var currentPackage = new PackageManager().GetCurrentPackage(); if (!currentPackage.IsNullOrEmpty()) @@ -85,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 1d422a908..ad4a32feb 100644 --- a/Telerik.Sitefinity.Frontend/Designers/DesignerResolver.cs +++ b/Telerik.Sitefinity.Frontend/Designers/DesignerResolver.cs @@ -1,8 +1,14 @@ 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 @@ -12,6 +18,15 @@ namespace Telerik.Sitefinity.Frontend.Designers /// 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 /// @@ -35,7 +50,45 @@ public string GetUrl(Type widgetType) if (!this.TryResolveUrlFromAttribute(widgetType, out designerUrl)) designerUrl = this.GetDefaultUrl(widgetType); - return new PackageManager().EnhanceUrl(designerUrl); + return this.packageManager.EnhanceUrl(designerUrl); + } + + /// + /// 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 @@ -105,6 +158,9 @@ private string GetDefaultUrl(Type widgetType) private const string DefaultActionUrlTemplate = "~/Telerik.Sitefinity.Frontend/Designer/Master/{0}"; private const string DefaultGridActionUrlTemplate = "~/Telerik.Sitefinity.Frontend/GridDesigner/Master/GridDesigner"; + private readonly PackageManager packageManager; + + 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 c65172129..a605cac44 100644 --- a/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor-services.js +++ b/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor-services.js @@ -72,7 +72,7 @@ */ var getUrl = function () { if (!httpGetUrl) { - httpGetUrl = widgetContext.webServiceUrl + widgetContext.widgetId + '/?pageId=' + widgetContext.pageId; + httpGetUrl = widgetContext.webServiceUrl + widgetContext.widgetId + '/?pageId=' + widgetContext.pageId + "&mediaType=" + widgetContext.mediaType; } return httpGetUrl; }; @@ -95,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) @@ -103,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; @@ -159,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; @@ -204,6 +229,10 @@ */ toAssociativeArray: function (propertyBag) { return toAssociativeArray(propertyBag); + }, + + toHierarchyArray: function (propertyBag) { + return toHierarchyArray(propertyBag); } }; @@ -238,7 +267,7 @@ var getInnerElements = function (layoutRoot) { var gridElements = []; - var elements = $(layoutRoot).find('[data-sf-element]'); + var elements = $(layoutRoot).findExcludeNested('[data-sf-element]'); //Sort out the inner columns for (var i = 0; i < elements.length; i++) { @@ -260,7 +289,7 @@ var tempLayout = $(gridContext.layoutRoot).clone(); for (var i = 0; i < elements.length; i++) { - var innerDiv = elements[i].id ? $(tempLayout).find('#' + elements[i].id) : $(tempLayout).find('[data-sf-element=' + elements[i].name + ']'); + 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; @@ -288,14 +317,22 @@ var refreshContainer = function (elements) { for (var i = 0; i < elements.length; i++) { - var innerDiv = elements[i].id ? $(gridContext.layoutContainer).find('#' + elements[i].id) : $(gridContext.layoutContainer).find('[data-sf-element=' + elements[i].name + ']'); + 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; - $(innerDiv).find('.zeDockZoneLabel b').html(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); @@ -307,6 +344,27 @@ } }; + // 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); diff --git a/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor.js b/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor.js index ac3fc854d..c664c7aec 100644 --- a/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor.js +++ b/Telerik.Sitefinity.Frontend/Designers/Scripts/page-editor.js @@ -3,182 +3,228 @@ var sitefinity = sitefinity || {}; (function ($) { - - var loader, + $(function () { + var loader, loaderMarkup = '
', loaderTemplate = kendo.template(loaderMarkup), - dialog; + 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 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'); + 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]); + var result = []; + for (var i = 0; i < scripts.length; i++) { + if (isScriptTag(scripts[i])) { + result.push(scripts[i]); + } } - } - return result; - } + return result; + } - function stripScripts(markup) { - var div = document.createElement('div'); - div.innerHTML = markup; - var scripts = div.getElementsByTagName('script'); + 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]); + 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 - }); + return div.innerHTML; + } - for (var i = 0; i < scriptTags.length; i++) { - if (scriptTags[i].src) { - 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 + 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); + }); } - 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 (ev, args) { - this.showLoader(args.AppPath); - this.widgetContext = args; - - var separator; - if (this.widgetContext.url.indexOf('?') > -1) - separator = '&'; - else - separator = '?'; - - var url = this.widgetContext.url + separator + 'controlId=' + this.widgetContext.Id; - $.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); - }); - }, - - /** - * 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('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)); - } + /** + * 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/FileMonitor.cs b/Telerik.Sitefinity.Frontend/FilesMonitoring/FileMonitor.cs index b7905c681..4f4b0435a 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/FileMonitor.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/FileMonitor.cs @@ -1,570 +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.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) - { - 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 => !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. - /// - /// Type of the resource. - /// 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. - /// - 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 - - /// - /// 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, args.FilePath); - - 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, 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; - - #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 d233cdd02..c1111b12d 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/FileMonitoringInitializer.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/FileMonitoringInitializer.cs @@ -1,31 +1,35 @@ -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. /// - internal class FileMonitoringInitializer + internal class FileMonitoringInitializer : IInitializer { /// /// Initializes and configure file monitoring functionality. /// public void Initialize() { - if (!ObjectFactory.Container.IsRegistered(typeof(IFileMonitor))) + if (!ObjectFactory.IsTypeRegistered(typeof(IFileMonitor))) { ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); } - if (!ObjectFactory.Container.IsRegistered(typeof(IFileManager), ResourceType.Layouts.ToString())) + if (!ObjectFactory.IsTypeRegistered(ResourceType.Layouts.ToString())) { ObjectFactory.Container.RegisterType(ResourceType.Layouts.ToString(), new ContainerControlledLifetimeManager()); } - if (!ObjectFactory.Container.IsRegistered(typeof(IFileManager), ResourceType.Grid.ToString())) + if (!ObjectFactory.IsTypeRegistered(ResourceType.Grid.ToString())) { ObjectFactory.Container.RegisterType(ResourceType.Grid.ToString(), new ContainerControlledLifetimeManager()); } @@ -33,18 +37,90 @@ public void Initialize() 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 index d710343e7..7b885edb5 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/GridFileManager.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/GridFileManager.cs @@ -2,20 +2,10 @@ 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.Frontend.GridSystem; -using Telerik.Sitefinity.Modules.Pages; -using Telerik.Sitefinity.Modules.Pages.Configuration; -using Telerik.Sitefinity.Multisite; -using Telerik.Sitefinity.Project.Configuration; -using Telerik.Sitefinity.Services; -using Telerik.Sitefinity.Web.UI; +using Telerik.Sitefinity.Frontend.Resources; namespace Telerik.Sitefinity.Frontend.FilesMonitoring { @@ -64,16 +54,18 @@ protected virtual GridWidgetRegistrator WidgetRegistrator /// /// 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, string packageName = "") + public void FileAdded(string fileName, string filePath, FileData fileData, string packageName = "") { var fileMonitorDataManager = FileMonitorDataManager.GetManager(); - var fileData = fileMonitorDataManager.GetFilesData().Where(file => file.FilePath.Equals(filePath, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); - this.AddToToolboxAndFileData(fileMonitorDataManager, fileName, filePath, packageName, fileData); - fileMonitorDataManager.SaveChanges(); + if (this.AddToToolboxAndFileData(fileMonitorDataManager, fileName, filePath, packageName, fileData)) + { + fileMonitorDataManager.SaveChanges(); + } } /// @@ -92,7 +84,7 @@ public void FileDeleted(string filePath, string packageName) fileMonitorDataManager.SaveChanges(); } - this.WidgetRegistrator.UnregisterToolboxItem(this.GetFileName(filePath), packageName); + this.WidgetRegistrator.UnregisterToolboxItem(this.GetFileName(filePath)); } /// @@ -108,25 +100,38 @@ public void FileRenamed(string newFileName, string oldFileName, string newFilePa var fileMonitorDataManager = FileMonitorDataManager.GetManager(); var fileData = fileMonitorDataManager.GetFilesData().Where(file => file.FilePath.Equals(oldFilePath, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); - this.AddToToolboxAndFileData(fileMonitorDataManager, newFileName, newFilePath, packageName, fileData, oldFileName); - - this.WidgetRegistrator.UpdateControlData(newFileName, oldFileName); - - fileMonitorDataManager.SaveChanges(); + 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 void AddToToolboxAndFileData(FileMonitorDataManager fileMonitorDataManager, string newFileName, string newFilePath, string packageName, FileData fileData, string oldFileName = "") + private bool AddToToolboxAndFileData(FileMonitorDataManager fileMonitorDataManager, string newFileName, string newFilePath, string packageName, FileData fileData, string oldFileName = "") { if (!this.IsFileValid(newFileName, newFilePath, packageName)) - return; + return false; - this.WidgetRegistrator.RegisterToolboxItem(newFileName, packageName, oldFileName); + this.WidgetRegistrator.RegisterToolboxItem(newFileName, oldFileName); - this.CreateOrUpdateFileData(fileMonitorDataManager, newFileName, newFilePath, packageName, fileData); + return this.CreateOrUpdateFileData(fileMonitorDataManager, newFileName, newFilePath, packageName, fileData); } /// @@ -154,7 +159,13 @@ private bool IsFileInValidFolder(string filePath, string packageName = "") if (!string.IsNullOrEmpty(packageName)) expectedGridFolderStructure = expectedGridFolderStructure.Insert(0, packageName + Path.DirectorySeparatorChar); - if (directory.FullName.EndsWith(expectedGridFolderStructure, StringComparison.OrdinalIgnoreCase) && directory.FullName.StartsWith(HostingEnvironment.ApplicationPhysicalPath, StringComparison.OrdinalIgnoreCase)) + 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; @@ -173,19 +184,34 @@ private bool IsFileValid(string fileName, string filePath, string packageName) var absolutePath = FrontendManager.VirtualPathBuilder.MapPath(filePath); var isSupproted = extension == GridFileManager.GridTemplateExtension; - var isValid = isSupproted && !packageName.IsNullOrEmpty() && this.IsFileInValidFolder(absolutePath, packageName); + var isValid = isSupproted && this.IsFileInValidFolder(absolutePath, packageName); return isValid; } - private void CreateOrUpdateFileData(FileMonitorDataManager dataManager, string fileName, string filePath, string packageName, FileData fileData) + 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; + } - fileData.FilePath = filePath; - fileData.FileName = fileName; - fileData.PackageName = packageName; + return changed; } /// diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/IFileManager.cs b/Telerik.Sitefinity.Frontend/FilesMonitoring/IFileManager.cs index 8127af86b..8097346ae 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/IFileManager.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/IFileManager.cs @@ -1,4 +1,6 @@ -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. @@ -10,8 +12,9 @@ internal interface IFileManager /// /// 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. diff --git a/Telerik.Sitefinity.Frontend/FilesMonitoring/LayoutFileManager.cs b/Telerik.Sitefinity.Frontend/FilesMonitoring/LayoutFileManager.cs index 18c16ddb0..2f2bfc6dc 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/LayoutFileManager.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/LayoutFileManager.cs @@ -2,17 +2,23 @@ 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; @@ -20,7 +26,6 @@ using Telerik.Sitefinity.Services.RelatedData.Messages; using Telerik.Sitefinity.Taxonomies; using Telerik.Sitefinity.Taxonomies.Model; -using Telerik.Sitefinity.Web; using Telerik.Sitefinity.Web.UI; namespace Telerik.Sitefinity.Frontend.FilesMonitoring @@ -62,25 +67,12 @@ public virtual ICollection FolderPathStructure /// The id of the category. public virtual Guid GetOrCreateTemplateCategoryId(string templateCategoryName, bool createIfNotExist = true) { - var taxonomyManager = TaxonomyManager.GetManager(); + if (string.IsNullOrWhiteSpace(templateCategoryName)) + return SiteInitializer.CustomTemplatesCategoryId; - var pageTemplatesTaxonomy = taxonomyManager.GetTaxonomy(SiteInitializer.PageTemplatesTaxonomyId); - var templateCategory = pageTemplatesTaxonomy.Taxa.SingleOrDefault(t => t.Name.Equals(templateCategoryName, StringComparison.OrdinalIgnoreCase)); + var createdIds = this.CreateTemplateCategories(new HashSet() { templateCategoryName }, createIfNotExist); - if (templateCategory == null && createIfNotExist) - { - templateCategory = taxonomyManager.CreateTaxon(); - templateCategory.Name = templateCategoryName; - templateCategory.UrlName = templateCategoryName; - templateCategory.RenderAsLink = false; - templateCategory.Title = templateCategoryName; - templateCategory.Description = string.Format("Represents category for {0} page templates.", templateCategoryName); - - pageTemplatesTaxonomy.Taxa.Add(templateCategory); - taxonomyManager.SaveChanges(); - } - - return templateCategory.Id; + return createdIds[0]; } /// @@ -108,14 +100,16 @@ public virtual void AttachImageToTemplate(PageTemplate template, PageManager pag /// /// The virtual file name. /// The virtual file path. + /// The file data /// Name of the package. - public void FileAdded(string fileName, string filePath, string packageName = "") + public void FileAdded(string fileName, string filePath, FileData fileData, 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); + if (fileData == null && this.CreateTemplateAndFileData(fileName, filePath, packageName, fileMonitorDataManager, ref fileData)) + { + fileMonitorDataManager.SaveChanges(); + } } /// @@ -151,207 +145,177 @@ public void FileRenamed(string newFileName, string oldFileName, string newFilePa var fileData = fileMonitorDataManager.GetFilesData().Where(file => file.FilePath.Equals(oldFilePath, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (fileData != null) - this.CreateTemplateAndFileData(newFileName, newFilePath, packageName, fileMonitorDataManager, fileData); + { + 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, packageName); + { + this.FileAdded(newFileName, newFilePath, null, packageName); + } } - internal void CreateDefaultSemanticUiTemplates() - { - var header = new LayoutControlDescription() - { - Caption = LayoutFileManager.LayoutCaptionHeader, - Description = LayoutFileManager.LayoutDescriptionHeader, - Path = LayoutFileManager.GridTemplatePathSemanticUiContainer - }; + #endregion - var content = new LayoutControlDescription() - { - Caption = LayoutFileManager.LayoutCaptionContent, - Description = LayoutFileManager.LayoutDescriptionContent, - Path = LayoutFileManager.GridTemplatePathSemanticUiContainer - }; + #region Internal methods - var footer = new LayoutControlDescription() + /// + /// 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 { - Caption = LayoutFileManager.LayoutCaptionFooter, - Description = LayoutFileManager.LayoutDescriptionFooter, - Path = LayoutFileManager.GridTemplatePathSemanticUiContainer + LayoutFileManager.TemplateImage1Column, + LayoutFileManager.TemplateImage2Columns, + LayoutFileManager.TemplateImage3Columns, + LayoutFileManager.TemplateImage4Columns, + LayoutFileManager.TemplateImageLeftSidebar, + LayoutFileManager.TemplateImageRightSidebar, + "default" }; - var twoColumns = new LayoutControlDescription() + var templateThumbsImageLibrary = librariesManager.GetAlbums().FirstOrDefault(lib => lib.Id == LibrariesModule.DefaultTemplateThumbnailsLibraryId); + if (templateThumbsImageLibrary != null) { - Caption = LayoutFileManager.LayoutCaption2Columns, - Description = LayoutFileManager.LayoutDescriptionContentColumns, - Path = LayoutFileManager.GridTemplatePathSemanticUi2Columns - }; + 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); - var threeColumns = new LayoutControlDescription() - { - Caption = LayoutFileManager.LayoutCaption3Columns, - Description = LayoutFileManager.LayoutDescriptionContentColumns, - Path = LayoutFileManager.GridTemplatePathSemanticUi3Columns - }; + 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(); + } + } + } + } + } + } + } - var fourColumns = new LayoutControlDescription() - { - Caption = LayoutFileManager.LayoutCaption4Columns, - Description = LayoutFileManager.LayoutDescriptionContentColumns, - Path = LayoutFileManager.GridTemplatePathSemanticUi4Columns - }; + internal IList CreateTemplateCategories(ISet categoryNames, bool createIfNotExist) + { + var categoryIds = new List(); + var taxonomyManager = TaxonomyManager.GetManager(); - var leftSidebar = new LayoutControlDescription() + foreach (var templateCategoryName in categoryNames) { - Caption = LayoutFileManager.LayoutCaptionContentSidebar, - Description = LayoutFileManager.LayoutDescriptionContentSidebar, - Path = LayoutFileManager.GridTemplatePathSemanticUiLeftSidebar - }; + var pageTemplatesTaxonomy = taxonomyManager.GetTaxonomy(SiteInitializer.PageTemplatesTaxonomyId); + var templateCategory = pageTemplatesTaxonomy.Taxa.SingleOrDefault(t => t.Name != null && t.Name.Equals(templateCategoryName, StringComparison.OrdinalIgnoreCase)); - var rightSidebar = new LayoutControlDescription() - { - Caption = LayoutFileManager.LayoutCaptionContentSidebar, - Description = LayoutFileManager.LayoutDescriptionContentSidebar, - Path = LayoutFileManager.GridTemplatePathSemanticUiRightSidebar - }; + 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); + } + } - this.CreateSemanticUiTemplate(LayoutFileManager.TemplateCaption1Column, LayoutFileManager.TemplateImage1Column, new LayoutControlDescription[] { header, content, footer }); - this.CreateSemanticUiTemplate(LayoutFileManager.TemplateCaption2Columns, LayoutFileManager.TemplateImage2Columns, new LayoutControlDescription[] { header, twoColumns, footer }); - this.CreateSemanticUiTemplate(LayoutFileManager.TemplateCaption3Columns, LayoutFileManager.TemplateImage3Columns, new LayoutControlDescription[] { header, threeColumns, footer }); - this.CreateSemanticUiTemplate(LayoutFileManager.TemplateCaption4Columns, LayoutFileManager.TemplateImage4Columns, new LayoutControlDescription[] { header, fourColumns, footer }); - this.CreateSemanticUiTemplate(LayoutFileManager.TemplateCaptionLeftSidebar, LayoutFileManager.TemplateImageLeftSidebar, new LayoutControlDescription[] { header, leftSidebar, footer }); - this.CreateSemanticUiTemplate(LayoutFileManager.TemplateCaptionRightSidebar, LayoutFileManager.TemplateImageRightSidebar, new LayoutControlDescription[] { header, rightSidebar, footer }); + taxonomyManager.SaveChanges(); + + return categoryIds; } - internal void CreateDefaultFoundationTemplates() + internal void CreateDefaultTemplates(string packageName, string layoutFile) { var header = new LayoutControlDescription() { Caption = LayoutFileManager.LayoutCaptionHeader, Description = LayoutFileManager.LayoutDescriptionHeader, - Path = LayoutFileManager.GridTemplatePathFoundationContainer + Path = LayoutFileManager.GridTemplatePathContainer }; var content = new LayoutControlDescription() { Caption = LayoutFileManager.LayoutCaptionContent, Description = LayoutFileManager.LayoutDescriptionContent, - Path = LayoutFileManager.GridTemplatePathFoundationContainer + Path = LayoutFileManager.GridTemplatePathContainer }; var footer = new LayoutControlDescription() { Caption = LayoutFileManager.LayoutCaptionFooter, Description = LayoutFileManager.LayoutDescriptionFooter, - Path = LayoutFileManager.GridTemplatePathFoundationContainer + Path = LayoutFileManager.GridTemplatePathContainer }; var twoColumns = new LayoutControlDescription() { Caption = LayoutFileManager.LayoutCaption2Columns, Description = LayoutFileManager.LayoutDescriptionContentColumns, - Path = LayoutFileManager.GridTemplatePathFoundation2Columns + Path = LayoutFileManager.GridTemplatePath2Columns }; var threeColumns = new LayoutControlDescription() { Caption = LayoutFileManager.LayoutCaption3Columns, Description = LayoutFileManager.LayoutDescriptionContentColumns, - Path = LayoutFileManager.GridTemplatePathFoundation3Columns + Path = LayoutFileManager.GridTemplatePath3Columns }; var fourColumns = new LayoutControlDescription() { Caption = LayoutFileManager.LayoutCaption4Columns, Description = LayoutFileManager.LayoutDescriptionContentColumns, - Path = LayoutFileManager.GridTemplatePathFoundation4Columns + Path = LayoutFileManager.GridTemplatePath4Columns }; var leftSidebar = new LayoutControlDescription() { Caption = LayoutFileManager.LayoutCaptionContentSidebar, Description = LayoutFileManager.LayoutDescriptionContentSidebar, - Path = LayoutFileManager.GridTemplatePathFoundationLeftSidebar + Path = LayoutFileManager.GridTemplatePathLeftSidebar }; var rightSidebar = new LayoutControlDescription() { Caption = LayoutFileManager.LayoutCaptionContentSidebar, Description = LayoutFileManager.LayoutDescriptionContentSidebar, - Path = LayoutFileManager.GridTemplatePathFoundationRightSidebar + Path = LayoutFileManager.GridTemplatePathRightSidebar }; - this.CreateFoundationTemplate(LayoutFileManager.TemplateCaption1Column, LayoutFileManager.TemplateImage1Column, new LayoutControlDescription[] { header, content, footer }); - this.CreateFoundationTemplate(LayoutFileManager.TemplateCaption2Columns, LayoutFileManager.TemplateImage2Columns, new LayoutControlDescription[] { header, twoColumns, footer }); - this.CreateFoundationTemplate(LayoutFileManager.TemplateCaption3Columns, LayoutFileManager.TemplateImage3Columns, new LayoutControlDescription[] { header, threeColumns, footer }); - this.CreateFoundationTemplate(LayoutFileManager.TemplateCaption4Columns, LayoutFileManager.TemplateImage4Columns, new LayoutControlDescription[] { header, fourColumns, footer }); - this.CreateFoundationTemplate(LayoutFileManager.TemplateCaptionLeftSidebar, LayoutFileManager.TemplateImageLeftSidebar, new LayoutControlDescription[] { header, leftSidebar, footer }); - this.CreateFoundationTemplate(LayoutFileManager.TemplateCaptionRightSidebar, LayoutFileManager.TemplateImageRightSidebar, new LayoutControlDescription[] { header, rightSidebar, footer }); - } - - internal void CreateDefaultBootstrapTemplates() - { - var header = new LayoutControlDescription() - { - Caption = LayoutFileManager.LayoutCaptionHeader, - Description = LayoutFileManager.LayoutDescriptionHeader, - Path = LayoutFileManager.GridTemplatePathBootstrapContainer - }; - - var content = new LayoutControlDescription() - { - Caption = LayoutFileManager.LayoutCaptionContent, - Description = LayoutFileManager.LayoutDescriptionContent, - Path = LayoutFileManager.GridTemplatePathBootstrapContainer - }; - - var footer = new LayoutControlDescription() - { - Caption = LayoutFileManager.LayoutCaptionFooter, - Description = LayoutFileManager.LayoutDescriptionFooter, - Path = LayoutFileManager.GridTemplatePathBootstrapContainer - }; - - var twoColumns = new LayoutControlDescription() - { - Caption = LayoutFileManager.LayoutCaption2Columns, - Description = LayoutFileManager.LayoutDescriptionContentColumns, - Path = LayoutFileManager.GridTemplatePathBootstrap2Columns - }; - - var threeColumns = new LayoutControlDescription() - { - Caption = LayoutFileManager.LayoutCaption3Columns, - Description = LayoutFileManager.LayoutDescriptionContentColumns, - Path = LayoutFileManager.GridTemplatePathBootstrap3Columns - }; - - var fourColumns = new LayoutControlDescription() - { - Caption = LayoutFileManager.LayoutCaption4Columns, - Description = LayoutFileManager.LayoutDescriptionContentColumns, - Path = LayoutFileManager.GridTemplatePathBootstrap4Columns - }; - - var leftSidebar = new LayoutControlDescription() - { - Caption = LayoutFileManager.LayoutCaptionContentSidebar, - Description = LayoutFileManager.LayoutDescriptionContentSidebar, - Path = LayoutFileManager.GridTemplatePathBootstrapLeftSidebar - }; + 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 }); + } - var rightSidebar = new LayoutControlDescription() - { - Caption = LayoutFileManager.LayoutCaptionContentSidebar, - Description = LayoutFileManager.LayoutDescriptionContentSidebar, - Path = LayoutFileManager.GridTemplatePathBootstrapRightSidebar - }; - - this.CreateBootstrapTemplate(LayoutFileManager.TemplateCaption1Column, LayoutFileManager.TemplateImage1Column, new LayoutControlDescription[] { header, content, footer }); - this.CreateBootstrapTemplate(LayoutFileManager.TemplateCaption2Columns, LayoutFileManager.TemplateImage2Columns, new LayoutControlDescription[] { header, twoColumns, footer }); - this.CreateBootstrapTemplate(LayoutFileManager.TemplateCaption3Columns, LayoutFileManager.TemplateImage3Columns, new LayoutControlDescription[] { header, threeColumns, footer }); - this.CreateBootstrapTemplate(LayoutFileManager.TemplateCaption4Columns, LayoutFileManager.TemplateImage4Columns, new LayoutControlDescription[] { header, fourColumns, footer }); - this.CreateBootstrapTemplate(LayoutFileManager.TemplateCaptionLeftSidebar, LayoutFileManager.TemplateImageLeftSidebar, new LayoutControlDescription[] { header, leftSidebar, footer }); - this.CreateBootstrapTemplate(LayoutFileManager.TemplateCaptionRightSidebar, LayoutFileManager.TemplateImageRightSidebar, new LayoutControlDescription[] { header, rightSidebar, 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 @@ -384,7 +348,13 @@ private bool IsFileInValidFolder(string filePath, string packageName = "") if (!string.IsNullOrEmpty(packageName)) expectedLayoutFolderStructure = packageName + Path.DirectorySeparatorChar + expectedLayoutFolderStructure; - if (directory.FullName.EndsWith(expectedLayoutFolderStructure, StringComparison.OrdinalIgnoreCase) && directory.FullName.StartsWith(HostingEnvironment.ApplicationPhysicalPath, StringComparison.OrdinalIgnoreCase)) + 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; @@ -398,31 +368,59 @@ private bool IsFileInValidFolder(string filePath, string packageName = "") /// 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) + /// + 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)) - return; - - var extension = fileName.Split('.').LastOrDefault(); - var fileNameWithoutExtension = fileName.Substring(0, fileName.Length - (extension.Length + 1)); + if (this.IsFileInValidFolder(absolutePath, packageName)) + { + var extension = fileName.Split('.').LastOrDefault(); + var fileNameWithoutExtension = fileName.Substring(0, fileName.Length - (extension.Length + 1)); - var viewFileExtensions = this.GetViewExtensions(); + var viewFileExtensions = this.GetViewExtensions(); - if (viewFileExtensions.Contains(extension, StringComparer.Ordinal)) - { - if (fileData == null) - fileData = fileMonitorDataManager.CreateFileData(); + 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; + } - fileData.FilePath = filePath; - fileData.FileName = fileName; - fileData.PackageName = packageName; + if (fileData.FileName != fileName) + { + fileData.FileName = fileName; + changed = true; + } - fileMonitorDataManager.SaveChanges(); + if (fileData.PackageName != packageName) + { + fileData.PackageName = packageName; + changed = true; + } + } - this.CreateTemplate(packageName, fileNameWithoutExtension); + if (changed) + { + this.CreateTemplate(packageName, fileNameWithoutExtension); + return true; + } + } } + + return false; } /// @@ -440,21 +438,6 @@ private void CreateTemplate(string packageName, string fileNameWithoutExtension) this.CreateTemplate(packageName, fileNameWithoutExtension, fileNameWithoutExtension, null, null); } - private void CreateBootstrapTemplate(string title, string image, LayoutControlDescription[] layoutControls) - { - this.CreateTemplate("Bootstrap", "default", title, image, layoutControls); - } - - private void CreateFoundationTemplate(string title, string image, LayoutControlDescription[] layoutControls) - { - this.CreateTemplate("Foundation", "default", title, image, layoutControls); - } - - private void CreateSemanticUiTemplate(string title, string image, LayoutControlDescription[] layoutControls) - { - this.CreateTemplate("SemanticUI", "default", title, image, layoutControls); - } - private void CreateTemplate(string packageName, string fileNameWithoutExtension, string title, string image, LayoutControlDescription[] layoutControls) { var multisiteContext = SystemManager.CurrentContext as MultisiteContext; @@ -474,35 +457,42 @@ private void CreateTemplate(string packageName, string 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 template = pageManager.CreateTemplate(); + 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.CreatePublishedInvarianLanguageData(); + var languageData = pageManager.CreatePublishedLanguageData(); template.LanguageData.Add(languageData); this.AttachImageToTemplate(template, pageManager, image ?? "default"); this.AddLayoutControls(pageManager, template, layoutControls); - pageManager.SaveChanges(); - 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.CreateDefaultBootstrapTemplates(); + this.CreateDefaultTemplates("Bootstrap", "default"); else if (string.Equals(LayoutFileManager.FoundationDefaultTemplateName, fullTemplateName, StringComparison.OrdinalIgnoreCase)) - this.CreateDefaultFoundationTemplates(); + this.CreateDefaultTemplates("Foundation", "default"); else if (string.Equals(LayoutFileManager.SemanticUIDefaultTemplateName, fullTemplateName, StringComparison.OrdinalIgnoreCase)) - this.CreateDefaultSemanticUiTemplates(); + 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) @@ -553,7 +543,7 @@ private Image GetTemplateImage(PageTemplate template, string imageName) if (templateThumbsImageLibrary != null) { // Try get image from library - image = templateThumbsImageLibrary.Images().FirstOrDefault(i => i.Title.Equals("MVC_" + imageName, StringComparison.OrdinalIgnoreCase)); + 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 @@ -590,7 +580,7 @@ private Image UploadTemplateImage(LibrariesManager libraryManager, Album templat using (var imageStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(iconResource)) { - using (var resourceImage = System.Drawing.Image.FromStream(imageStream)) + using (var resourceImage = ImagesHelper.CurrentImageProcessor.GetImageFromStream(imageStream)) { var resourceImageStream = new MemoryStream(); resourceImage.Save(resourceImageStream, System.Drawing.Imaging.ImageFormat.Png); @@ -621,8 +611,8 @@ private void AddTemplatePresentation(PageTemplate template, PageManager pageMana private void AddTemplateRelatedData(PageTemplate template, Image image, PageManager pageManager) { - var changedRelations = new ContentLinkChange[] - { + var changedRelations = new ContentLinkChange[] + { new ContentLinkChange() { ChildItemId = image.Id, @@ -639,6 +629,15 @@ private void AddTemplateRelatedData(PageTemplate template, Image image, PageMana 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 @@ -670,15 +669,19 @@ private class LayoutControlDescription /// 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.BootstrapDefaultTemplateName, - LayoutFileManager.SemanticUIDefaultTemplateName, - LayoutFileManager.FoundationDefaultTemplateName + 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"; @@ -709,26 +712,12 @@ private class LayoutControlDescription 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 GridTemplatePathBootstrapContainer = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/container.html"; - private const string GridTemplatePathBootstrap2Columns = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-6+6.html"; - private const string GridTemplatePathBootstrap3Columns = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+4+4.html"; - private const string GridTemplatePathBootstrap4Columns = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+3+3+3.html"; - private const string GridTemplatePathBootstrapLeftSidebar = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+9.html"; - private const string GridTemplatePathBootstrapRightSidebar = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-9+3.html"; - - private const string GridTemplatePathFoundationContainer = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-12.html"; - private const string GridTemplatePathFoundation2Columns = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-6+6.html"; - private const string GridTemplatePathFoundation3Columns = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+4+4.html"; - private const string GridTemplatePathFoundation4Columns = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+3+3+3.html"; - private const string GridTemplatePathFoundationLeftSidebar = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+9.html"; - private const string GridTemplatePathFoundationRightSidebar = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-9+3.html"; - - private const string GridTemplatePathSemanticUiContainer = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-one-col.html"; - private const string GridTemplatePathSemanticUi2Columns = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-two-cols.html"; - private const string GridTemplatePathSemanticUi3Columns = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-three-cols.html"; - private const string GridTemplatePathSemanticUi4Columns = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-four-cols.html"; - private const string GridTemplatePathSemanticUiLeftSidebar = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+12.html"; - private const string GridTemplatePathSemanticUiRightSidebar = "~/Frontend-Assembly/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-12+4.html"; + 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 0d4223e6a..57415c2f1 100644 --- a/Telerik.Sitefinity.Frontend/FilesMonitoring/MonitoredDirectory.cs +++ b/Telerik.Sitefinity.Frontend/FilesMonitoring/MonitoredDirectory.cs @@ -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/FrontendModule.cs b/Telerik.Sitefinity.Frontend/FrontendModule.cs index ef4601046..4ba38c3ed 100644 --- a/Telerik.Sitefinity.Frontend/FrontendModule.cs +++ b/Telerik.Sitefinity.Frontend/FrontendModule.cs @@ -3,24 +3,22 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; +using System.Threading.Tasks; +using System.Web.Mvc; using Ninject; -using Telerik.Microsoft.Practices.Unity; +using Ninject.Modules; using Telerik.Sitefinity.Abstractions; using Telerik.Sitefinity.Configuration; using Telerik.Sitefinity.Data; -using Telerik.Sitefinity.Frontend.Designers; -using Telerik.Sitefinity.Frontend.FilesMonitoring; +using Telerik.Sitefinity.Frontend; using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Layouts; -using Telerik.Sitefinity.Frontend.Resources; -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; + +[assembly: SitefinityModule(FrontendModule.ModuleName, + typeof(FrontendModule), + "Feather", + "Modern, intuitive, convention based, mobile-first UI for Progress Sitefinity CMS.", + StartupType.OnApplicationStart)] namespace Telerik.Sitefinity.Frontend { @@ -40,7 +38,7 @@ public static FrontendModule Current { get { - return (FrontendModule)SystemManager.GetModule("Feather"); + return (FrontendModule)SystemManager.GetModule(FrontendModule.ModuleName); } } @@ -59,7 +57,7 @@ public override Guid LandingPageId /// An array of objects. public override Type[] Managers { - get { return new Type[0]; } + get { return ManagerTypes; } } /// @@ -72,7 +70,7 @@ public IKernel DependencyResolver { get { - return this.ninjectDependencyResolver; + return ninjectDependencyResolver; } } @@ -82,31 +80,38 @@ public IKernel DependencyResolver /// The initializer. public override void Install(SiteInitializer initializer) { - if (this.FrontendServiceExists()) - { - this.InitialUpgrade(initializer); - } + FrontendModuleInstaller.Install(initializer); } /// - /// Initializes the service with specified settings. + /// Initializes the module with specified settings. /// /// The settings. public override void Initialize(ModuleSettings settings) { base.Initialize(settings); - Bootstrapper.Initialized -= this.Bootstrapper_Initialized; - Bootstrapper.Initialized += this.Bootstrapper_Initialized; + App.WorkWith() + .Module(settings.Name) + .Initialize() + .Configuration(); + + this.PreloadControllerTypeCacheAsync(); + } + + /// + /// Integrate the module into the system. + /// + public override void Load() + { + base.Load(); - SystemManager.RegisterServiceStackPlugin(new ListsServiceStackPlugin()); - SystemManager.RegisterServiceStackPlugin(new FilesServiceStackPlugin()); - SystemManager.RegisterServiceStackPlugin(new ReviewsServiceStackPlugin()); + this.InitializeDependencyResolver(); - this.controllerAssemblies = new ControllerContainerInitializer().RetrieveAssemblies(); + FrontendModuleInstaller.Initialize(); - this.ninjectDependencyResolver = new StandardKernel(); - this.ninjectDependencyResolver.Load(this.controllerAssemblies); + Bootstrapper.Initialized -= this.Bootstrapper_Initialized; + Bootstrapper.Initialized += this.Bootstrapper_Initialized; } /// @@ -115,14 +120,22 @@ public override void Initialize(ModuleSettings settings) /// public override void Unload() { - if (this.ninjectDependencyResolver != null && !this.ninjectDependencyResolver.IsDisposed) - this.ninjectDependencyResolver.Dispose(); - - Bootstrapper.Initialized -= this.Bootstrapper_Initialized; - + 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. /// @@ -131,33 +144,7 @@ public override void Unload() public override void Upgrade(SiteInitializer initializer, Version upgradeFrom) { base.Upgrade(initializer, upgradeFrom); - - if (upgradeFrom < new Version(1, 2, 140, 0)) - { - this.DeleteOldGridSection(); - this.UpdateContentBlockTitle(); - } - - if (upgradeFrom <= new Version(1, 2, 180, 1)) - { - this.RemoveMvcWidgetToolboxItems(); - this.RenameDynamicContentMvcToolboxItems(); - } - - if (upgradeFrom <= new Version(1, 2, 260, 1)) - { - this.RecategorizePageTemplates(); - } - - if (upgradeFrom <= new Version(1, 2, 270, 1)) - { - this.UpdatePageTemplates(); - } - - if (upgradeFrom <= new Version(1, 2, 280, 2)) - { - this.CreateDefaultTemplates(); - } + FrontendModuleUpgrader.Upgrade(upgradeFrom, initializer); } /// @@ -165,283 +152,177 @@ public override void Upgrade(SiteInitializer initializer, Version upgradeFrom) /// protected override ConfigSection GetModuleConfig() { - return null; + return Config.Get(); } /// - /// Handles the Initialized event of the Bootstrapper. + /// Gets the meta data aggregation mode of the module persistence. /// - /// The source of the event. - /// The instance containing the event data. - protected virtual void Bootstrapper_Initialized(object sender, ExecutedEventArgs e) + protected override ManagersInitializationMode ManagersInitializationMode { - if (e.CommandName == "Bootstrapped") + get { - var resourcesInitializer = new ResourcesInitializer(); - resourcesInitializer.Initialize(); - - var fileMonitoringInitilizer = new FileMonitoringInitializer(); - fileMonitoringInitilizer.Initialize(); - - var controllerContainerInitializer = new ControllerContainerInitializer(); - controllerContainerInitializer.Initialize(this.controllerAssemblies); - this.controllerAssemblies = null; // We won't be needing those anymore. Set them free. - - var layoutsInitializer = new LayoutInitializer(); - layoutsInitializer.Initialize(); - - var designerInitializer = new DesignerInitializer(); - designerInitializer.Initialize(); - - ObjectFactory.Container.RegisterType(new ContainerControlledLifetimeManager()); + return ManagersInitializationMode.OnStartup; } } - private void InitialUpgrade(SiteInitializer initializer) - { - this.RemoveFrontendService(); - this.RenameControllers(initializer); - this.ClearToolboxItems(); - } - - private void ClearToolboxItems() + /// + /// Creates Ninject kernel. + /// + /// + protected virtual IKernel CreateKernel() { - 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) + var bootstrapper = new Ninject.Web.Common.Bootstrapper(); + IKernel kernel; + if (bootstrapper.Kernel != null) + kernel = bootstrapper.Kernel; + else { - this.RemoveToolboxItemIfExists(mvcWidgetsSection, "ContentBlock"); - this.RemoveToolboxItemIfExists(mvcWidgetsSection, "Navigation"); - this.RemoveToolboxItemIfExists(mvcWidgetsSection, "News"); - - configManager.SaveSection(toolboxesConfig); + var ninjectSettings = new NinjectSettings(); + ninjectSettings.LoadExtensions = Config.Get().NinjectLoadExtensions; + kernel = new SitefinityKernel(ninjectSettings); } - } - private void RemoveToolboxItemIfExists(ToolboxSection mvcWidgetsSection, string toolName) - { - var tool = mvcWidgetsSection.Tools.FirstOrDefault(t => t.Name == toolName); - if (tool != null) - mvcWidgetsSection.Tools.Remove(tool); + return kernel; } - private void RenameControllers(SiteInitializer initializer) + /// + /// 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) { - 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 (e.CommandName == "Bootstrapped") { - 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") + using (new HealthMonitoring.MethodPerformanceRegion("Feather")) { - property.Value = "Telerik.Sitefinity.Frontend.Navigation.Mvc.Controllers.NavigationController"; - } - else if (property.Value == "SocialShare.Mvc.Controllers.SocialShareController") - { - property.Value = "Telerik.Sitefinity.Frontend.SocialShare.Mvc.Controllers.SocialShareController"; - } - else if (property.Value == "DynamicContent.Mvc.Controllers.DynamicContentController") - { - property.Value = "Telerik.Sitefinity.Frontend.DynamicContent.Mvc.Controllers.DynamicContentController"; + FrontendModuleInstaller.Bootstrapper_Initialized(this.initializers.Value); } } } - private void RemoveMvcWidgetToolboxItems() + // Called both by Unload and Uninstall + private void Uninitialize() { - var configManager = ConfigManager.GetManager(); - using (new ElevatedConfigModeRegion()) - { - var toolboxConfig = configManager.GetSection(); - var pageControls = toolboxConfig.Toolboxes["PageControls"]; + this.UninitializeDependencyResolver(); - 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) - { - section.Tools.Remove(tool); - } - } - - var mvcWidgetsSection = pageControls.Sections.FirstOrDefault(s => s.Name == "MvcWidgets"); - if (mvcWidgetsSection != null) - { - pageControls.Sections.Remove(mvcWidgetsSection); - } - - configManager.SaveSection(toolboxConfig); - } + Bootstrapper.Initialized -= this.Bootstrapper_Initialized; } - private void RenameDynamicContentMvcToolboxItems() + /// + /// Triggers the initialization of the controller type cache for the default controller factory asynchroniously. + /// + private void PreloadControllerTypeCacheAsync() { - 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); - } + Task.Run(() => this.InitializeControllerTypeCache()); } - private void RemoveFrontendService() + /// + /// Initializes the controller type cache of the default controller factory. + /// + private void InitializeControllerTypeCache() { - var configManager = ConfigManager.GetManager(); - var systemConfig = configManager.GetSection(); - systemConfig.SystemServices.Remove(FrontendModule.FrontendServiceName); - configManager.SaveSection(systemConfig); - } + DefaultControllerFactory defaultControllerFactory = + System.Web.Mvc.DependencyResolver.Current.GetService() as DefaultControllerFactory ?? + (ControllerBuilder.Current.GetControllerFactory() as DefaultControllerFactory ?? new DefaultControllerFactory()); - private bool FrontendServiceExists() - { - var systemConfig = Config.Get(); - return systemConfig.SystemServices.ContainsKey(FrontendModule.FrontendServiceName); + MethodInfo getControllerTypesMethod = defaultControllerFactory.GetType().GetMethod("GetControllerTypes", BindingFlags.Instance | BindingFlags.NonPublic); + getControllerTypesMethod.Invoke(defaultControllerFactory, null); } - private void DeleteOldGridSection() + private void InitializeDependencyResolver() { - 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) - { - layoutsToolbox.Sections.Remove(htmlLayoutsSection); - configManager.SaveSection(toolboxConfig); - } - } - } - } + if (ninjectDependencyResolver != null) + return; - [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 void UpdateContentBlockTitle() - { - var configManager = ConfigManager.GetManager(); - using (new ElevatedConfigModeRegion()) + ninjectDependencyResolver = this.CreateKernel(); + var assemblies = new ControllerContainerInitializer().ControllerContainerAssemblies; + var loadedModules = ninjectDependencyResolver.GetModules(); + + foreach (var assembly in assemblies) { - var toolboxConfig = configManager.GetSection(); - var controlsToolbox = toolboxConfig.Toolboxes["PageControls"]; - if (controlsToolbox != null) + 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()) { - var mvcWidgetsSection = controlsToolbox.Sections.FirstOrDefault(s => s.Name == "MvcWidgets"); - if (mvcWidgetsSection != null) + foreach (var module in assemblyModules) { - var contentBlockTool = mvcWidgetsSection.Tools.FirstOrDefault(t => t.Name == "ContentBlock"); - if (contentBlockTool != null) + if (!registeredAssemblyModules.Any(registeredModule => registeredModule.Name.Equals(module.Name, StringComparison.OrdinalIgnoreCase))) { - contentBlockTool.Title = "Content Block"; - configManager.SaveSection(toolboxConfig); + ninjectDependencyResolver.Load(module); } } } - } - - 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) + else { - contentBlock.Caption = "Content Block"; + ninjectDependencyResolver.Load(assembly); } - - pageManager.SaveChanges(); } } - private void RecategorizePageTemplates() + private void UninitializeDependencyResolver() { - var pageManager = PageManager.GetManager(); - var layoutManager = new LayoutFileManager(); - - var customPageTemplates = pageManager.GetTemplates().Where(pt => pt.Category == SiteInitializer.CustomTemplatesCategoryId).ToArray(); - foreach (var customPageTemplate in customPageTemplates) + if (ninjectDependencyResolver != null && !ninjectDependencyResolver.IsDisposed && ninjectDependencyResolver is SitefinityKernel) { - var titleTokens = customPageTemplate.Title.ToString().Split('.'); - if (titleTokens.Length > 1 && (new PackageManager()).PackageExists(titleTokens[0])) - { - customPageTemplate.Category = layoutManager.GetOrCreateTemplateCategoryId(titleTokens[0]); - } + ninjectDependencyResolver.Dispose(); + ninjectDependencyResolver = null; } - - pageManager.SaveChanges(); } - private void UpdatePageTemplates() + private Lazy> initializers = new Lazy>(() => { - 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) + try { - // 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"); + 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; } + }); - pageManager.SaveChanges(); + private IEnumerable GetNinjectModules(Assembly assembly) + { + return assembly.GetExportedTypes().Where(new Func(this.IsLoadableModule)).Select((Type type) => Activator.CreateInstance(type) as INinjectModule); } - private void CreateDefaultTemplates() - { - var layoutManager = new LayoutFileManager(); + private bool IsLoadableModule(Type type) + { + if (!typeof(INinjectModule).IsAssignableFrom(type) || type.IsAbstract || type.IsInterface) + { + return false; + } + + return type.GetConstructor(Type.EmptyTypes) != null; + } - var pageManager = PageManager.GetManager(); - var defaultPageTemplates = pageManager.GetTemplates().Where(pt => LayoutFileManager.DefaultTemplateNames.Contains(pt.Name)); - foreach (var template in defaultPageTemplates) + /// + /// 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() { - if (string.Equals(LayoutFileManager.BootstrapDefaultTemplateName, template.Name, StringComparison.OrdinalIgnoreCase)) - layoutManager.CreateDefaultBootstrapTemplates(); - else if (string.Equals(LayoutFileManager.FoundationDefaultTemplateName, template.Name, StringComparison.OrdinalIgnoreCase)) - layoutManager.CreateDefaultFoundationTemplates(); - else if (string.Equals(LayoutFileManager.SemanticUIDefaultTemplateName, template.Name, StringComparison.OrdinalIgnoreCase)) - layoutManager.CreateDefaultSemanticUiTemplates(); } - } - - private IKernel ninjectDependencyResolver; - private IEnumerable controllerAssemblies; - private const string FrontendServiceName = "Telerik.Sitefinity.Frontend"; + 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/GlobalSuppressions.cs b/Telerik.Sitefinity.Frontend/GlobalSuppressions.cs index f39cd2f55..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/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/GridWidgetRegistrator.cs b/Telerik.Sitefinity.Frontend/GridSystem/GridWidgetRegistrator.cs index 310caf38f..c39967fff 100644 --- a/Telerik.Sitefinity.Frontend/GridSystem/GridWidgetRegistrator.cs +++ b/Telerik.Sitefinity.Frontend/GridSystem/GridWidgetRegistrator.cs @@ -20,35 +20,68 @@ internal class GridWidgetRegistrator /// Registers the grid widget in toolbox. ///
/// Name of the file. - /// Name of the package. /// Old name of the file. - public void RegisterToolboxItem(string fileName, string packageName, string oldFileName = "") + public void RegisterToolboxItem(string fileName, string oldFileName = "") { - var configManager = ConfigManager.GetManager(); - using (new ElevatedConfigModeRegion()) + 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 toolboxConfig = configManager.GetSection(); - var sectionName = packageName + GridWidgetRegistrator.GridSectionNameSuffix; - var sectionTitle = packageName + GridWidgetRegistrator.GridSectionTitleSuffix; - var htmlLayoutsSection = this.GetOrCreateToolBoxSection(toolboxConfig, sectionName, sectionTitle); + var oldFileNameWithoutExtension = this.GetFileNameWithoutExtension(oldFileName); + toolboxItemName = oldFileNameWithoutExtension; + } - var layoutControl = this.CreateGridControlsData(fileName); - this.AddOrRenameGridControl(htmlLayoutsSection.Tools, layoutControl, oldFileName); + ToolboxItem toolboxItem = null; + if (configManager == null) + toolboxItem = htmlLayoutsSection.Tools.FirstOrDefault(t => t.Name == toolboxItemName); - configManager.SaveSection(toolboxConfig); + 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, string packageName) + /// 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 = packageName + GridWidgetRegistrator.GridSectionNameSuffix; + var sectionName = GridWidgetRegistrator.GridSectionName; var section = pageControls.Sections.Where(e => e.Name == sectionName).FirstOrDefault(); if (section != null) @@ -56,12 +89,12 @@ public virtual void UnregisterToolboxItem(string fileName, string packageName) var fileNameWithoutExtension = this.GetFileNameWithoutExtension(fileName); var itemToDelete = section.Tools.FirstOrDefault(e => e.Name == fileNameWithoutExtension); - if (itemToDelete != null) + if (itemToDelete != null && itemToDelete.Source == ConfigSource.Database) { section.Tools.Remove(itemToDelete); } - if (!section.Tools.Any()) + if (!section.Tools.Any() && section.Source == ConfigSource.Database) { pageControls.Sections.Remove(section); } @@ -82,7 +115,7 @@ public void UpdateControlData(string newFileName, string oldFileName) var baseTemplatePath = string.Format( CultureInfo.InvariantCulture, GridWidgetRegistrator.GridFolderPathStringTemplate, - FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(FrontendService).Assembly)); + 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); @@ -102,25 +135,19 @@ public void UpdateControlData(string newFileName, string oldFileName) /// /// Gets existing or create a tool box section for the grid controls. /// - /// The toolbox configuration. + /// The toolbox configuration. /// Name of the section. /// The section title. - /// - protected virtual ToolboxSection GetOrCreateToolBoxSection(ToolboxesConfig toolboxConfig, string sectionName, string sectionTitle) + /// The section. + protected virtual ToolboxSection CreateToolBoxSection(Toolbox toolbox, string sectionName, string sectionTitle) { - var layoutsToolbox = toolboxConfig.Toolboxes["PageLayouts"]; + var htmlLayoutsSection = new ToolboxSection(toolbox.Sections); + htmlLayoutsSection.Name = sectionName; - var htmlLayoutsSection = layoutsToolbox.Sections.FirstOrDefault(s => s.Name == sectionName); - if (htmlLayoutsSection == null) - { - htmlLayoutsSection = new ToolboxSection(layoutsToolbox.Sections); - htmlLayoutsSection.Name = sectionName; + /// TODO: Set resource class id and use resource keys for Title and Description. + htmlLayoutsSection.Title = sectionTitle; - /// TODO: Set resource class id and use resource keys for Title and Description. - htmlLayoutsSection.Title = sectionTitle; - - layoutsToolbox.Sections.Add(htmlLayoutsSection); - } + toolbox.Sections.Add(htmlLayoutsSection); return htmlLayoutsSection; } @@ -128,34 +155,25 @@ protected virtual ToolboxSection GetOrCreateToolBoxSection(ToolboxesConfig toolb /// /// Adds or renames the grid control. /// - /// The parent. + /// The parent toolbox section. /// The data. - /// Old name of the file. + /// Old name of the file. /// data - protected virtual void AddOrRenameGridControl(ConfigElementList parent, GridControlData data, string oldFileName = "") + protected virtual void AddOrRenameGridControl(ToolboxSection section, GridControlData data, string toolboxItemName = default(string)) { if (data == null) throw new ArgumentNullException("data"); - string toolboxItemName; - if (oldFileName.IsNullOrEmpty()) - { - toolboxItemName = data.Name; - } - else - { - var oldFileNameWithoutExtension = this.GetFileNameWithoutExtension(oldFileName); - toolboxItemName = oldFileNameWithoutExtension; - } + var tools = section.Tools; - var control = parent.FirstOrDefault(t => t.Name == toolboxItemName); + var control = tools.FirstOrDefault(t => t.Name == toolboxItemName); if (control == null) { - control = new ToolboxItem(parent); + control = new ToolboxItem(tools); control.ControlType = typeof(GridControl).AssemblyQualifiedName; control.CssClass = data.CssClass; - parent.Add(control); + tools.Add(control); } control.Name = data.Name; @@ -173,7 +191,7 @@ protected GridControlData CreateGridControlsData(string fileName) var baseTemplatePath = string.Format( System.Globalization.CultureInfo.InvariantCulture, GridWidgetRegistrator.GridFolderPathStringTemplate, - FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(FrontendService).Assembly)); + FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(FrontendModule).Assembly)); var fileNameWithoutExtension = this.GetFileNameWithoutExtension(fileName); var cssClass = this.GetInferredCssClass(fileNameWithoutExtension); @@ -243,14 +261,14 @@ private string GetInferredCssClass(string fileNameWithoutExtension) public const string GridFolderPathStringTemplate = "~/{0}GridSystem/Templates/"; /// - /// The grid section name suffix + /// The grid section name. /// - public const string GridSectionNameSuffix = "Grids"; + public const string GridSectionName = "Grids"; /// - /// The grid section title suffix + /// The grid section title. /// - public const string GridSectionTitleSuffix = " grid widgets"; + public const string GridSectionTitle = "Grid widgets"; #endregion } 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 new file mode 100644 index 000000000..daae99815 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-12.html @@ -0,0 +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 new file mode 100644 index 000000000..db3f65f78 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-2+3+2+3+2.html @@ -0,0 +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 new file mode 100644 index 000000000..97e08843b --- /dev/null +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+3+3+3.html @@ -0,0 +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 new file mode 100644 index 000000000..a0d9f0538 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+6+3.html @@ -0,0 +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 new file mode 100644 index 000000000..7e9733a7b --- /dev/null +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-3+9.html @@ -0,0 +1,12 @@ +
+
+
+ +
+
+
+
+ +
+
+
diff --git a/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+4+4.html b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+4+4.html new file mode 100644 index 000000000..262d0bcce --- /dev/null +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+4+4.html @@ -0,0 +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 new file mode 100644 index 000000000..f4b2485f3 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-4+8.html @@ -0,0 +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 new file mode 100644 index 000000000..d392b690b --- /dev/null +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-6+6.html @@ -0,0 +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 new file mode 100644 index 000000000..5fa5e715b --- /dev/null +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-8+4.html @@ -0,0 +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 new file mode 100644 index 000000000..c43e44cc8 --- /dev/null +++ b/Telerik.Sitefinity.Frontend/GridSystem/Templates/grid-9+3.html @@ -0,0 +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/InterfaceMappings.cs b/Telerik.Sitefinity.Frontend/InterfaceMappings.cs index baccfba32..147979f5c 100644 --- a/Telerik.Sitefinity.Frontend/InterfaceMappings.cs +++ b/Telerik.Sitefinity.Frontend/InterfaceMappings.cs @@ -12,6 +12,7 @@ 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 index ef5f4139e..8c537930a 100644 --- a/Telerik.Sitefinity.Frontend/Modules/Comments/ReviewNotificationStrategy.cs +++ b/Telerik.Sitefinity.Frontend/Modules/Comments/ReviewNotificationStrategy.cs @@ -4,6 +4,7 @@ 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 { @@ -16,42 +17,33 @@ internal class ReviewNotificationStrategy : CommentNotificationsStrategy, IComme /// Gets the message template unique identifier for the specified event. ///
/// The event. - protected override Guid GetMessageTemplateId(ICommentEvent @event) + protected override IMessageTemplateRequest GetMessageTemplate(ICommentEvent @event) { - IComment comment = @event.Item; + if (@event == null || @event.Item == null) + return null; + IMessageTemplateRequest messageTemplate; + IComment comment = @event.Item; ICommentService cs = SystemManager.GetCommentsService(); IThread thread = cs.GetThread(comment.ThreadKey); - var ns = SystemManager.GetNotificationService(); - Guid messageTemplateId; - if (this.IsReviewThread(thread)) { - messageTemplateId = ns.GetMessageTemplates(this.ServiceContext, null) - .Where(mt => mt.Subject == "A new review was posted") - .Select(m => m.Id).FirstOrDefault(); + messageTemplate = this.GetNewReviewMessageTemplate(); } else { - messageTemplateId = ns.GetMessageTemplates(this.ServiceContext, null) - .Where(mt => mt.Subject == "A new comment was posted") - .Select(m => m.Id).FirstOrDefault(); - } - - if (messageTemplateId == Guid.Empty) - { - messageTemplateId = base.GetMessageTemplateId(@event); + messageTemplate = this.GetNewCommentMessageTemplate(); } - return messageTemplateId; + return messageTemplate; } private bool IsReviewThread(IThread thread) { var isReview = false; - if (thread.Behavior == null) + if (thread.Behavior.IsNullOrEmpty()) { isReview = thread.Key.EndsWith("_review", StringComparison.Ordinal); } diff --git a/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/Scripts/MvcControlTemplateEditor.js b/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/Scripts/MvcControlTemplateEditor.js index d711734e7..a167d157b 100644 --- a/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/Scripts/MvcControlTemplateEditor.js +++ b/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/Scripts/MvcControlTemplateEditor.js @@ -13,11 +13,12 @@ Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.UI.MvcControlTemplateEd initialize: function () { Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.UI.MvcControlTemplateEditor.callBaseMethod(this, "initialize"); - this._containerToHide = jQuery(this._otherPropertiesContainer).parent(); + this._containerToHide = this.getInsertSectionContainer(); + this._containerToHide.hide(); }, dispose: function () { - Telerik.Sitefinity.Modules.ControlTemplates.Web.UI.MvcControlTemplateEditor.callBaseMethod(this, "dispose"); + Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.UI.MvcControlTemplateEditor.callBaseMethod(this, "dispose"); }, _valueChangedHandler: function (sender, args) { diff --git a/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/UI/MvcControlTemplateEditor.cs b/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/UI/MvcControlTemplateEditor.cs index 96bb11b41..ab0b5c5b3 100644 --- a/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/UI/MvcControlTemplateEditor.cs +++ b/Telerik.Sitefinity.Frontend/Modules/ControlTemplates/Web/UI/MvcControlTemplateEditor.cs @@ -84,6 +84,6 @@ private List GetRestoreButtonsClientIds() return returnResult; } - private const string MvcControlTemplateEditorScript = "Telerik.Sitefinity.Frontend.Modules.ControlTemplates.Web.Scripts.MvcControlTemplateEditor.js"; + 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 6d7c62be1..c3941a4e4 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Controllers/ContentPagerController.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Controllers/ContentPagerController.cs @@ -1,10 +1,11 @@ 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 @@ -12,7 +13,8 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Controllers /// /// This class represents controller for pager widget. /// - [ControllerMetadataAttribute(IsTemplatableControl = false)] + [Localization(typeof(ContentPagerResources))] + [ControllerMetadata(IsTemplatableControl = false)] public class ContentPagerController : Controller { /// @@ -21,11 +23,12 @@ 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. /// [OutputCache(Duration = 1)] - public PartialViewResult Index(int currentPage, int totalPagesCount, string redirectUrlTemplate) + 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; @@ -66,7 +69,66 @@ public PartialViewResult Index(int currentPage, int totalPagesCount, string redi 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 e5237c41e..67be1f5a7 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Controllers/DesignerController.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Controllers/DesignerController.cs @@ -8,6 +8,8 @@ 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; @@ -21,23 +23,26 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Controllers [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 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, Guid.Parse(controlId)); + var model = this.GetModel(widgetName, Guid.Parse(controlId), moduleName, (DesignMediaType)Enum.Parse(typeof(DesignMediaType), mediaType)); return this.View(DesignerController.DefaultView, model); } @@ -54,15 +59,17 @@ public virtual ActionResult Master(string widgetName) { this.GetHttpContext().Items[SystemManager.IsBackendRequestKey] = true; - var viewName = DesignerController.DesignerViewTemplate.Arrange(viewType); + 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(); + var model = this.GetViewModel(designMediaType); // Passing the DesignerModel to the view model var controlIdParam = this.GetControlIdParam(); if (controlIdParam.HasValue) { - ViewBag.DesignerModel = this.GetModel(widgetName, controlIdParam.Value); + ViewBag.DesignerModel = this.GetModel(widgetName, controlIdParam.Value, designMediaType: designMediaType); } return this.PartialView(viewName, model); @@ -97,21 +104,25 @@ protected virtual HttpContextBase GetHttpContext() /// /// Gets the model of the designer. /// - private IDesignerModel GetModel(string widgetName, Guid controlId) - { + 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 }, - { "controlId", controlId }, - { "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() + private Control GetViewModel(DesignMediaType designMediaType) { var controlIdParam = this.GetControlIdParam(); @@ -119,7 +130,7 @@ private Control GetViewModel() return null; var controlId = controlIdParam.Value; - var manager = PageManager.GetManager(); + var manager = this.GetControlManager(designMediaType); var viewModel = manager.LoadControl(manager.GetControl(controlId)); var widgetProxy = viewModel as MvcWidgetProxy; @@ -134,6 +145,18 @@ private Control GetViewModel() 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/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 index 059ef207b..f3eacb5a7 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/CommentsHelpers.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/CommentsHelpers.cs @@ -34,6 +34,12 @@ public static MvcHtmlString CommentsCount(this HtmlHelper helper, string navigat 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; @@ -151,13 +157,10 @@ private static string GetDataSourceName(IDataItem item) if (item != null && item is DynamicContent) { - var moduleProvider = ModuleBuilderManager.GetManager().Provider; - var itemType = item.GetType().FullName; + var itemType = item.GetType(); - var dynamicContentType = moduleProvider.GetDynamicModules() - .Where(m => m.Status == DynamicModuleStatus.Active) - .Join(moduleProvider.GetDynamicModuleTypes().Where(t => string.Concat(t.TypeNamespace, ".", t.TypeName) == itemType), m => m.Id, t => t.ParentModuleId, (m, t) => t) - .FirstOrDefault(); + var dynamicContentType = ModuleBuilderManager.GetActiveTypes() + .FirstOrDefault(t => t.TypeNamespace == itemType.Namespace && t.TypeName == itemType.Name); if (dynamicContentType != null) { @@ -205,6 +208,11 @@ private static string GetTitle(IDataItem item) } } + if (NewslettersHelper.IsNewsletter()) + { + allowComments = false; + } + return allowComments; } 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/HtmlHelperExtensions.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/HtmlHelperExtensions.cs index 028f2d2aa..6bcf78465 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/HtmlHelperExtensions.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/HtmlHelperExtensions.cs @@ -1,142 +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 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)); - } - } - } +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 index bba497f32..f715d3919 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/HyperLinkHelpers.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/HyperLinkHelpers.cs @@ -1,16 +1,21 @@ using System; -using System.Linq; -using System.Threading; using System.Web; -using System.Web.Mvc; +using System.Linq; using Telerik.Sitefinity.Abstractions; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; +using Telerik.Sitefinity.Data.Linq.Dynamic; using Telerik.Sitefinity.Frontend.Mvc.Models; -using Telerik.Sitefinity.Localization.UrlLocalizationStrategies; 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 { @@ -82,6 +87,60 @@ public static string GetDetailPageUrl(ItemViewModel item, Guid detailsPageId, bo 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. /// @@ -109,9 +168,102 @@ public static string GetFullPageUrl(Guid pageId) { 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 2a7998c39..73aace273 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/InlineEditingHtmlHelpers.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/InlineEditingHtmlHelpers.cs @@ -2,8 +2,10 @@ 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 @@ -47,10 +49,10 @@ public static IHtmlString TextField(this HtmlHelper helper, string propName, str { 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. /// @@ -62,14 +64,14 @@ public static IHtmlString TextField(this HtmlHelper helper, string propName, 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); } @@ -85,6 +87,11 @@ public static IHtmlString InlineEditingAttributes(this HtmlHelper htmlHelper, st 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); @@ -122,7 +129,7 @@ public static IHtmlString InlineEditingFieldAttributes(this HtmlHelper htmlHelpe } /// - /// Returns if the inline editin section should be rendered. + /// Returns if the inline editing section should be rendered. /// /// The HTML helper. /// @@ -150,5 +157,31 @@ public static bool ShouldRenderInlineEditing(this HtmlHelper htmlHelper) 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/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 03ff4c720..8008231e8 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/ResourceHelper.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ResourceHelper.cs @@ -3,8 +3,12 @@ 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; @@ -12,6 +16,7 @@ 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 @@ -21,11 +26,71 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Helpers /// 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 /// @@ -35,7 +100,26 @@ public static class ResourceHelper /// public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath) { - return ResourceHelper.Script(helper, scriptPath, null, false); + 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); } /// @@ -44,6 +128,7 @@ public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath) /// 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 /// @@ -63,6 +148,7 @@ public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath, st /// 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 /// @@ -72,10 +158,95 @@ public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath, st /// public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath, string sectionName, bool throwException) { - if (ResourceHelper.TryConfigureScriptManager(scriptPath, helper.ViewContext.HttpContext.CurrentHandler)) + 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); + 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); } /// @@ -86,12 +257,32 @@ public static MvcHtmlString Script(this HtmlHelper helper, string scriptPath, st /// /// 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); + 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); } /// @@ -103,6 +294,7 @@ public static MvcHtmlString Script(this HtmlHelper helper, ScriptRef scriptRefer /// 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 /// @@ -111,6 +303,25 @@ public static MvcHtmlString Script(this HtmlHelper helper, ScriptRef scriptRefer 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. /// @@ -121,12 +332,48 @@ public static MvcHtmlString Script(this HtmlHelper helper, ScriptRef scriptRefer /// 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) + 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 (ResourceHelper.TryConfigureScriptManager(scriptReference, helper.ViewContext.HttpContext.CurrentHandler)) + 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)); @@ -136,12 +383,32 @@ public static MvcHtmlString Script(this HtmlHelper helper, ScriptRef scriptRefer foreach (var script in references) { var resourceUrl = script.GetResourceUrl(); - outputMarkup.Append(ResourceHelper.RegisterResource(helper.ViewContext.HttpContext, resourceUrl, ResourceType.Js, sectionName, throwException)); + 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. /// @@ -155,6 +422,20 @@ public static MvcHtmlString StyleSheet(this HtmlHelper helper, string resourcePa 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. /// @@ -181,7 +462,23 @@ public static MvcHtmlString StyleSheet(this HtmlHelper helper, string resourcePa /// public static MvcHtmlString StyleSheet(this HtmlHelper helper, string resourcePath, string sectionName, bool throwException) { - return ResourceHelper.RegisterResource(helper.ViewContext.HttpContext, resourcePath, ResourceType.Css, sectionName, 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); } /// @@ -226,6 +523,21 @@ public static MvcHtmlString CodeMirrorScriptReferences(this HtmlHelper helper) 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. /// @@ -233,7 +545,7 @@ public static MvcHtmlString CodeMirrorScriptReferences(this HtmlHelper helper) /// public static MvcHtmlString RenderLangAttribute(this HtmlHelper helper) { - return RenderLangAttribute(helper, CultureInfo.CurrentUICulture.Name); + return RenderLangAttribute(helper, Telerik.Sitefinity.Services.SystemManager.CurrentContext.Culture.Name); } /// @@ -244,7 +556,31 @@ public static MvcHtmlString RenderLangAttribute(this HtmlHelper helper) /// public static MvcHtmlString RenderLangAttribute(this HtmlHelper helper, string culture) { - string attributeString = helper.FormatValue(culture, "lang=\"{0}\""); + 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); } @@ -277,6 +613,76 @@ public static string GetWebResourceUrl(ScriptRef scriptReference) 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. /// @@ -305,7 +711,7 @@ internal static string RenderAllStylesheets(HttpContextBase context, string sect return stylesheetMarkup; } - private static MvcHtmlString RegisterResource(HttpContextBase httpContext, string resourcePath, ResourceType resourceType, string sectionName, bool throwException) + private static MvcHtmlString RegisterResource(HttpContextBase httpContext, string resourcePath, ResourceType resourceType, string sectionName, bool throwException, List> attributes = null) { throwException = throwException && httpContext.CurrentHandler != null; @@ -319,17 +725,37 @@ private static MvcHtmlString RegisterResource(HttpContextBase httpContext, strin 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 (string.IsNullOrEmpty(sectionName) || !SectionRenderer.IsAvailable(httpContext.Handler.GetPageHandler(), sectionName)) + if (sectionName == null || + ResourceHelper.RenderScriptSection) { - if (!register.IsRegistered(resourcePath, sectionName: null)) + if (!register.IsRegistered(resourcePath)) { - result = MvcHtmlString.Create(ResourceHelper.BuildSingleResourceMarkup(resourcePath, resourceType)); + 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); + register.Register(resourcePath, sectionName, throwException, attributes); return result; } @@ -373,7 +799,8 @@ private static bool TryConfigureScriptManager(string scriptReference, IHttpHandl if (scriptManager != null) { - scriptManager.Scripts.Add(new ScriptReference(scriptReference)); + var updatedScriptReference = GetResourceOrMinified(scriptReference); + scriptManager.Scripts.Add(new ScriptReference(updatedScriptReference)); return true; } } @@ -405,43 +832,78 @@ private static string BuildHtmlResourcesMarkup(ResourceRegister resourceRegister { StringBuilder output = new StringBuilder(); - foreach (var resource in resourceRegister.GetResourcesForSection(sectionName)) + foreach (var resource in resourceRegister.GetResourceItemsForSection(sectionName)) { - if (!resourceRegister.IsRendered(resource)) + if (!resourceRegister.IsRendered(resource.ResourceKey)) { - output.Append(ResourceHelper.BuildSingleResourceMarkup(resource, resourceType)); - resourceRegister.MarkAsRendered(resource); + 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) + private static string BuildSingleResourceMarkup(string resourceKey, ResourceType resourceType, string sectionName, List> attributes = null) { string result; if (resourceType == ResourceType.Js) - result = ResourceHelper.BuildScriptMarkup(resourceKey); + result = ResourceHelper.BuildScriptMarkup(resourceKey, sectionName, attributes); else if (resourceType == ResourceType.Css) - result = ResourceHelper.BuildStyleSheetMarkup(resourceKey); + result = ResourceHelper.BuildStyleSheetMarkup(resourceKey, attributes); else result = string.Empty; return result; } - private static string BuildScriptMarkup(string resourceKey) + 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 BuildStyleSheetMarkup(string resourceKey) + 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"); @@ -449,13 +911,21 @@ private static string BuildStyleSheetMarkup(string 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); } - private const string JsRegisterName = "JsRegister"; - private const string CssRegisterName = "CssRegister"; + internal const string JsRegisterName = "JsRegister"; + internal const string CssRegisterName = "CssRegister"; - private class MvcScriptReference : ScriptReference + internal class MvcScriptReference : ScriptReference { public MvcScriptReference(ScriptReference reference) { @@ -496,10 +966,14 @@ private bool IsGetUrlFromPathException(Exception ex) /// /// This enum represents supported resource types. /// - private enum ResourceType + 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/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 fce4ef374..bea9444b9 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/UrlHelpers.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/UrlHelpers.cs @@ -1,145 +1,262 @@ -using System; -using System.Globalization; -using System.Web; -using System.Web.Hosting; -using System.Web.Mvc; -using System.Web.UI; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure; -using Telerik.Sitefinity.Frontend.Resources; -using Telerik.Sitefinity.Modules.Pages; -using Telerik.Sitefinity.Mvc.Rendering; -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); - 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); - } - - 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); - return helper.Content(url); - } - - var resourceUrl = string.Format("~/{0}/{1}", FrontendManager.VirtualPathBuilder.GetVirtualPath(assemblyName), contentPath); - var contentResolvedPath = UrlTransformations.AppendParam(resourceUrl, PackageManager.PackageUrlParameterName, packageName); - - 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) +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) { - var page = helper.RequestContext.HttpContext.Handler.GetPageHandler() ?? new PageProxy(null); - return page.ClientScript.GetWebResourceUrl(TypeResolutionService.ResolveType(type), path); - } - - /// - /// 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; - } - } -} + 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/PagerViewModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewModels/PagerViewModel.cs index 65b8c0cc9..8ee4d93cf 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewModels/PagerViewModel.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewModels/PagerViewModel.cs @@ -28,7 +28,7 @@ public PagerViewModel(int currentPage, int totalPagesCount, string redirectUrlTe /// The current page. /// The total pages count. /// The redirect URL template. - /// The amount of page nodes to render + /// The amount of page nodes to render public PagerViewModel(int currentPage, int totalPagesCount, string redirectUrlTemplate, int displayCount) { this.CurrentPage = currentPage; diff --git a/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewSelectorHelpers.cs b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewSelectorHelpers.cs index 2793965bc..3c50bcaab 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewSelectorHelpers.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Helpers/ViewSelectorHelpers.cs @@ -28,6 +28,10 @@ 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); @@ -44,6 +48,21 @@ public static IEnumerable GetViewNames(this HtmlHelper helper, string co /// 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) { @@ -51,9 +70,22 @@ public static IEnumerable GetViewNames(this HtmlHelper helper, Controlle } 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); + 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/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 4c02f84c6..277634a2f 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/CacheDependentAttribute.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/Attributes/CacheDependentAttribute.cs @@ -28,12 +28,12 @@ public override void OnResultExecuted(ResultExecutedContext filterContext) { 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) { context.Response.AddCacheDependency(cacheDependency); 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/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 262c53228..f7b33cb2d 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerContainerInitializer.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerContainerInitializer.cs @@ -4,341 +4,657 @@ 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 - { - #region Public members - - /// - /// Initializes the controllers that are available to the web application. - /// - public virtual void Initialize(IEnumerable controllerAssemblies) - { - GlobalFilters.Filters.Add(new CacheDependentAttribute()); - - var assemblies = controllerAssemblies ?? this.RetrieveAssemblies(); - this.RegisterVirtualPaths(assemblies); - - var controllerTypes = this.GetControllers(assemblies); - this.InitializeControllers(controllerTypes); - - this.InitializeCustomRouting(); - } - - /// - /// Gets the assemblies that are marked as controller containers with the attribute. - /// - public 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; - } - - #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).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.RegisterTemplateableControls(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(); - ObjectFactory.Container.RegisterType("int"); - ObjectFactory.Container.RegisterType("category"); - ObjectFactory.Container.RegisterType("tag"); +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(); - } - - #endregion - - #region Private members - - /// - /// 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; - } - - 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); - - Telerik.Sitefinity.Modules.ControlTemplates.ControlTemplates.RegisterTemplatableControl(controllerType, controllerType, string.Empty, widgetName, mvcWidgetName); - } - } - - 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 - } -} + 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/ControllerExtensions.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerExtensions.cs index 2b9f4e7af..b36a8430f 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerExtensions.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerExtensions.cs @@ -5,16 +5,22 @@ 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 { @@ -25,12 +31,32 @@ 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. - /// 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) { @@ -65,7 +91,9 @@ public static void UpdateViewEnginesCollection(this Controller controller, IList /// Gets the partial views that are available to the controller. /// /// The controller. - public static IEnumerable GetPartialViews(this Controller 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); @@ -75,10 +103,24 @@ public static IEnumerable GetPartialViews(this Controller controller) /// Gets the views that are available to the controller. /// /// The controller. - public static IEnumerable GetViews(this Controller 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); + return ControllerExtensions.GetViews(controller, viewLocations, moduleName); } /// @@ -94,25 +136,33 @@ public static void AddCacheDependencies(this Controller controller, IEnumerable< if (keys == null) throw new ArgumentNullException("keys"); - if (SystemManager.CurrentHttpContext == null) + var httpContext = SystemManager.CurrentHttpContext; + if (httpContext == 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; - } + string widgetId = controller.ViewData[Telerik.Sitefinity.Mvc.ControllerActionInvoker.ControlDataIdKey] as string; - if (dependencies == null) - { - dependencies = new List(); - SystemManager.CurrentHttpContext.Items.Add(PageCacheDependencyKeys.PageData, dependencies); - } + httpContext.AddCacheDependencies(keys, widgetId); + } - foreach (var key in keys) - dependencies.Add(key); + /// + /// 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. /// @@ -148,7 +198,7 @@ public static string GetCurrentPageUrl(this IController controller) /// /// The controller. /// The dynamic module type. - public static DynamicModuleType GetDynamicContentType(this ControllerBase controller) + public static IDynamicModuleType GetDynamicContentType(this ControllerBase controller) { if (controller == null) throw new ArgumentNullException("controller"); @@ -168,7 +218,7 @@ public static DynamicModuleType GetDynamicContentType(this ControllerBase contro /// /// The dynamic module type. /// - public static DynamicModuleType GetDynamicContentType(this ControllerBase controller, string controllerName) + public static IDynamicModuleType GetDynamicContentType(this ControllerBase controller, string controllerName) { if (controller == null) throw new ArgumentNullException("controller"); @@ -176,7 +226,9 @@ public static DynamicModuleType GetDynamicContentType(this ControllerBase contro if (controllerName == null) throw new ArgumentNullException("controllerName"); - return ControllerExtensions.GetDynamicContentType(controllerName); + var moduleName = controller.ViewBag.ModuleName as string; + + return ControllerExtensions.GetDynamicContentType(controllerName, moduleName); } /// @@ -186,21 +238,22 @@ public static DynamicModuleType GetDynamicContentType(this ControllerBase contro /// /// The dynamic module type. /// - public static DynamicModuleType GetDynamicContentType(string controllerName) + public static IDynamicModuleType GetDynamicContentType(string controllerName) { - if (controllerName == null) - throw new ArgumentNullException("controllerName"); - - if (SystemManager.GetModule("ModuleBuilder") == null) - return null; - - var moduleProvider = ModuleBuilderManager.GetManager().Provider; - 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 ControllerExtensions.GetDynamicContentType(controllerName, null); + } - return dynamicContentType; + /// + /// 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(); } /// @@ -208,13 +261,124 @@ public static DynamicModuleType GetDynamicContentType(string controllerName) /// public static IndexRenderModes GetIndexRenderMode(this IController controller) { - if (controller == null) + 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 @@ -257,6 +421,10 @@ private static string GetKey(Controller controller) { 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(); @@ -280,7 +448,10 @@ private static ViewEngineCollection BuildViewEngineCollection(IList> pathTransformations) { - var newEngine = (VirtualPathProviderViewEngine)Activator.CreateInstance(viewEngine.GetType()); + 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); @@ -302,7 +496,15 @@ private static IViewEngine GetViewEngine(VirtualPathProviderViewEngine viewEngin newEngine.MasterLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.MasterLocationFormats, pathTransformations); newEngine.PartialViewLocationFormats = ControllerExtensions.AppendControllerVirtualPath(viewEngine.PartialViewLocationFormats, pathTransformations); - newEngine.ViewLocationCache = DefaultViewLocationCache.Null; + 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; } @@ -354,30 +556,75 @@ private static IEnumerable GetViewFileExtensions(Controller controller) .Distinct(); } - private static IEnumerable GetViews(Controller controller, IEnumerable viewLocations) + 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 baseFiles = ControllerExtensions.GetViewsForAssembly(controller.GetType().Assembly, viewLocations, viewExtensions); + 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) + private static IEnumerable GetViewsForAssembly(Assembly assembly, IEnumerable viewLocations, IEnumerable viewExtensions, string moduleName = null) { - var pathDef = FrontendManager.VirtualPathBuilder.GetPathDefinition(assembly); + 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); @@ -396,6 +643,31 @@ private static IEnumerable GetViewsForPath(PathDefinition definition, st 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 diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerModelFactory.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerModelFactory.cs index 6062d186a..299f4a68b 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerModelFactory.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/ControllerModelFactory.cs @@ -62,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 2b6c17505..11fd93e9a 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/FrontendControllerFactory.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/FrontendControllerFactory.cs @@ -17,20 +17,8 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers /// /// This class extends the by adding additional virtual paths for controller view engines. /// - public class FrontendControllerFactory : SitefinityControllerFactory, IDisposable + public class FrontendControllerFactory : SitefinityControllerFactory { - #region Constructors - - /// - /// Initializes a new instance of the class. - /// - public FrontendControllerFactory() - { - this.ninjectKernel = new StandardKernel(); - } - - #endregion - #region Public members /// @@ -53,29 +41,23 @@ public override IController CreateController(RequestContext requestContext, stri var controller = baseController as Controller; if (controller != null) { - this.EnhanceViewEngines(controller); + FrontendControllerFactory.EnhanceViewEngines(controller); } return baseController; } /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// Enhances the view engines. /// - public void Dispose() + /// The controller. + internal static void EnhanceViewEngines(Controller controller) { - this.Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - /// If false cleans up native resources, otherwise cleans up both managed and native resources. - protected virtual void Dispose(bool cleanManagedResources) - { - if (cleanManagedResources) - this.ninjectKernel.Dispose(); + var enhanceAttr = FrontendControllerFactory.GetEnhanceAttribute(controller.GetType()); + if (!enhanceAttr.Disabled) + { + controller.UpdateViewEnginesCollection(() => FrontendControllerFactory.GetControllerPathTransformations(controller, enhanceAttr.VirtualPath)); + } } #endregion @@ -83,9 +65,12 @@ protected virtual void Dispose(bool cleanManagedResources) #region Protected members /// - protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType) + protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { - return (IController)this.ninjectKernel.Get(controllerType); + object controllerObject = FrontendModule.Current.DependencyResolver.Get(controllerType); + IController controller = (IController)controllerObject; + + return controller; } #endregion @@ -122,29 +107,11 @@ private static IList> GetControllerPathTransformations(Cont private static void AddDynamicControllerPathTransformations(Controller controller, string virtualPath, string currentPackage, List> pathTransformations) { - if (controller != null && controller.Request != null && controller.Request.QueryString != null && controller.RouteData != null && controller.RouteData.Values.ContainsKey("widgetName") && (string)controller.RouteData.Values["widgetName"] == "DynamicContent") - { - var controlId = controller.Request.QueryString["controlId"] as string; - Guid controlIdGuid; + var dynamicControllerWidgetName = controller.ResolveDynamicControllerWidgetName(); + if (string.IsNullOrEmpty(dynamicControllerWidgetName)) + return; - if (!string.IsNullOrEmpty(controlId) && Guid.TryParse(controlId, out controlIdGuid)) - { - var controlObjectData = PageManager.GetManager().GetControl(controlIdGuid); - - if (controlObjectData != null && controlObjectData.Properties != null) - { - var controllerWidgetProperty = controlObjectData.Properties.FirstOrDefault(x => x.Name == "WidgetName"); - if (controllerWidgetProperty != null) - { - var dynamicControllerWidgetName = controllerWidgetProperty.Value; - if (!string.IsNullOrEmpty(dynamicControllerWidgetName)) - { - pathTransformations.Add(FrontendControllerFactory.GetPathTransformation(virtualPath, currentPackage, dynamicControllerWidgetName)); - } - } - } - } - } + pathTransformations.Add(FrontendControllerFactory.GetPathTransformation(virtualPath, currentPackage, dynamicControllerWidgetName)); } private static Func GetPathTransformation(string controllerVirtualPath, string currentPackage, string widgetName = null) @@ -171,16 +138,7 @@ 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(() => FrontendControllerFactory.GetControllerPathTransformations(controller, enhanceAttr.VirtualPath)); - } - } - - private EnhanceViewEnginesAttribute GetEnhanceAttribute(Type controllerType) + private static EnhanceViewEnginesAttribute GetEnhanceAttribute(Type controllerType) { var enhanceAttr = controllerType.GetCustomAttributes(typeof(EnhanceViewEnginesAttribute), true).FirstOrDefault() as EnhanceViewEnginesAttribute; if (enhanceAttr != null) @@ -198,7 +156,7 @@ private EnhanceViewEnginesAttribute GetEnhanceAttribute(Type controllerType) { var newEnhanceAttr = new EnhanceViewEnginesAttribute { - Disabled = !this.IsInDefaultMvcNamespace(controllerType), + Disabled = !FrontendControllerFactory.IsInDefaultMvcNamespace(controllerType), VirtualPath = AppendDefaultPath(FrontendManager.VirtualPathBuilder.GetVirtualPath(controllerType.Assembly)) }; @@ -212,7 +170,7 @@ private EnhanceViewEnginesAttribute GetEnhanceAttribute(Type controllerType) return enhanceAttr; } - private bool IsInDefaultMvcNamespace(Type controller) + private static bool IsInDefaultMvcNamespace(Type controller) { var expectedTypeName = controller.Assembly.GetName().Name + ".Mvc.Controllers." + controller.Name; return string.Equals(expectedTypeName, controller.FullName, StringComparison.OrdinalIgnoreCase); @@ -222,10 +180,8 @@ private bool IsInDefaultMvcNamespace(Type controller) #region Fields - private IKernel ninjectKernel; - 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/MvcWidgetProxy.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/MvcWidgetProxy.cs index fbc2831cc..95dcf3821 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/MvcWidgetProxy.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Controllers/MvcWidgetProxy.cs @@ -25,27 +25,51 @@ public string WidgetName set { this.widgetName = value; - if (this.Controller != null && this.Controller.ViewBag != null) - this.Controller.ViewBag.WidgetName = this.widgetName; + UpdateControllerViewBag(this.Controller); } } /// - /// Gets or sets the instance of that - /// is being proxied. + /// Gets or sets the name of the module. /// - public override Controller Controller + /// The name of the module. + [Browsable(true)] + public string ModuleName { get { - var controller = base.Controller; - if (controller != null && controller.ViewBag != null && !this.WidgetName.IsNullOrEmpty()) - controller.ViewBag.WidgetName = this.WidgetName; + return this.moduleName; + } - return controller; + 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/InfrastructureResources.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/InfrastructureResources.cs index 6a72c5b9d..f1cab8b98 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/InfrastructureResources.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/InfrastructureResources.cs @@ -1,4 +1,5 @@ -using Telerik.Sitefinity.Localization; +using System.Diagnostics.CodeAnalysis; +using Telerik.Sitefinity.Localization; namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure { @@ -52,5 +53,232 @@ public string ErrorExecutingController 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/LayoutInitializer.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutInitializer.cs index ea2756b8c..f9264fd4b 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutInitializer.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutInitializer.cs @@ -1,30 +1,117 @@ -using Telerik.Microsoft.Practices.Unity; -using Telerik.Sitefinity.Abstractions; -using Telerik.Sitefinity.Abstractions.VirtualPath; -using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing; -using Telerik.Sitefinity.Modules.Pages; -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 - { - /// - /// 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(); - System.Web.Routing.RouteTable.Routes.Insert(1, new System.Web.Routing.Route("Sitefinity/Versioning/{itemId}/{VersionNumber}", ObjectFactory.Resolve())); - } - } -} +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 index 3b03aea7b..83e4bc860 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutMvcPageResolver.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutMvcPageResolver.cs @@ -52,9 +52,11 @@ protected override void BuildWithMasterPage(string virtualPath, RequestContext c { if (LayoutMvcPageResolver.IsLayoutPath(virtualPath)) { - var httpContext = new HttpContextWrapper(new HttpContext(HttpContext.Current.Request, HttpContext.Current.Response)); - httpContext.Items[PackageManager.CurrentPackageKey] = context.HttpContext.Items[PackageManager.CurrentPackageKey]; - SystemManager.RunWithHttpContext(httpContext, () => base.BuildWithMasterPage(virtualPath, context, output, placeHolders, directives)); + SystemManager.RunWithElevatedPrivilege((args) => + { + HttpContext.Current.Items[PackageManager.CurrentPackageKey] = context.HttpContext.Items[PackageManager.CurrentPackageKey]; + base.BuildWithMasterPage(virtualPath, context, output, placeHolders, directives); + }); } else { diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutRenderer.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutRenderer.cs index 2842be38b..c8e6d7801 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutRenderer.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutRenderer.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text.RegularExpressions; using System.Web; using System.Web.Hosting; @@ -24,10 +25,9 @@ internal class LayoutRenderer /// /// 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) { @@ -74,7 +74,7 @@ public virtual string RenderViewToString(ControllerContext context, string viewP if (viewPath == null) throw new ArgumentNullException("viewPath"); - + string result = null; IView view = null; @@ -89,12 +89,12 @@ public virtual string RenderViewToString(ControllerContext context, string viewP // assigning the model so it can be available to the view context.Controller.ViewData.Model = null; - var builtView = view as BuildManagerCompiledView; + var viewVirtualPath = FrontendManager.VirtualPathBuilder.GetViewPath(view); using (var writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture)) { - if (placeholdersOnly && builtView != null) + if (placeholdersOnly && !viewVirtualPath.IsNullOrEmpty()) { - this.RenderContentPlaceHolders(builtView.ViewPath, writer); + this.RenderContentPlaceHolders(viewVirtualPath, writer); } else { @@ -109,10 +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; - 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); @@ -204,12 +204,7 @@ public string LayoutViewPath(string templateName) if (viewEngineResult != null && viewEngineResult.View != null) { - var builtView = viewEngineResult.View as BuildManagerCompiledView; - if (builtView != null) - { - result = builtView.ViewPath; - } - + result = FrontendManager.VirtualPathBuilder.GetViewPath(viewEngineResult.View); viewEngineResult.ViewEngine.ReleaseView(genericController.ControllerContext, viewEngineResult.View); } @@ -258,6 +253,8 @@ private void RenderContentPlaceHolders(string layoutPath, StringWriter writer) 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) { @@ -275,6 +272,46 @@ private void RenderContentPlaceHolders(string layoutPath, StringWriter writer) 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 f2aa899b8..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; @@ -28,7 +29,7 @@ public virtual string GetVirtualPath(Pages.Model.IPageTemplate template) var strictTemplate = template as PageTemplate; if (strictTemplate != null && strictTemplate.Name != null) { - templateName = strictTemplate.Name; + templateName = !strictTemplate.LayoutPath.IsNullOrWhitespace() ? strictTemplate.LayoutPath : strictTemplate.Name; } else { diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutVirtualFileResolver.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutVirtualFileResolver.cs index 5ea814a8f..0cdb9afb8 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutVirtualFileResolver.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/LayoutVirtualFileResolver.cs @@ -57,7 +57,7 @@ public virtual Stream Open(PathDefinition definition, string virtualPath) if (!string.IsNullOrEmpty(layoutHtmlString)) { - var layoutBytes = Encoding.Default.GetBytes(layoutHtmlString.ToCharArray()); + var layoutBytes = Encoding.UTF8.GetBytes(layoutHtmlString.ToCharArray()); outPutStream = new MemoryStream(layoutBytes); } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MasterPageBuilder.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MasterPageBuilder.cs index 2bf35450e..a32de1c64 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MasterPageBuilder.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MasterPageBuilder.cs @@ -108,7 +108,7 @@ public virtual string AddMasterPageDirectives(string layoutHtmlValue) return layoutHtmlValue; } - #endregion + #endregion #region Protected methods @@ -125,12 +125,26 @@ internal static 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; @@ -185,68 +199,23 @@ private static PageSiteNode GetRequestedPageNode() /// 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(); - if (pageData != null) + if (pageData != null && setTitle) { - 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"); + stringBuilder.Append("\r\n\t" + pageData.HtmlTitle.ToString() + "\r\n\t"); } } - /// - /// 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 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() - { - 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")); - - return sb.ToString(); - } - #endregion #region Constants private const string MasterPageDirective = "<%@ Master Language=\"C#\" AutoEventWireup=\"true\" %>\r\n \r\n"; - private const string RobotsMetaTag = ""; #endregion } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MvcMasterPage.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MvcMasterPage.cs index 0b9b5633c..cae4f2846 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MvcMasterPage.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/MvcMasterPage.cs @@ -112,8 +112,9 @@ private void InitializeControls(string source) private void HandleOpenTag(Stack container, HtmlChunk chunk, StringBuilder currentLiteralText) { - if (chunk.TagName.Equals("title", StringComparison.OrdinalIgnoreCase)) + 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); @@ -126,6 +127,7 @@ private void HandleOpenTag(Stack container, HtmlChunk chunk, StringBuil var head = new HtmlHead(); container.Peek().Controls.Add(head); container.Push(head); + isCurrentlyInHeadTag = true; } else if (chunk.TagName.Equals("asp:ContentPlaceHolder", StringComparison.OrdinalIgnoreCase)) { @@ -168,6 +170,13 @@ private void HandleOpenTag(Stack container, HtmlChunk chunk, StringBuil 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 @@ -180,8 +189,9 @@ private void HandleOpenTag(Stack container, HtmlChunk chunk, StringBuil private void HandleCloseTag(Stack container, HtmlChunk chunk, StringBuilder currentLiteralText) { - if (chunk.TagName.Equals("title", StringComparison.OrdinalIgnoreCase)) + 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(); @@ -197,6 +207,7 @@ private void HandleCloseTag(Stack container, HtmlChunk chunk, StringBui { this.AddIfNotEmpty(currentLiteralText.ToString(), container.Pop()); currentLiteralText.Clear(); + isCurrentlyInHeadTag = false; } else if (chunk.TagName.Equals("form", StringComparison.OrdinalIgnoreCase)) { @@ -218,6 +229,10 @@ private void HandleCloseTag(Stack container, HtmlChunk chunk, StringBui { //// Ignore } + else if (chunk.TagName.Equals("meta", StringComparison.OrdinalIgnoreCase)) + { + //// Ignore + } else { currentLiteralText.Append(chunk.Html); @@ -249,5 +264,7 @@ private void InstantiateControls(Control placeHolder) this.InstantiateInContentPlaceHolder(placeHolder, (ITemplate)this.ContentTemplates[placeHolder.ID]); } } + + private bool isCurrentlyInHeadTag = false; } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/SectionRenderer.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/SectionRenderer.cs index e0b78d31a..d04a71b0b 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/SectionRenderer.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Layouts/SectionRenderer.cs @@ -27,6 +27,9 @@ public class SectionRenderer : Control /// 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"); diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/PageInitializer.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/PageInitializer.cs index 01dd3096a..432e7bbba 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/PageInitializer.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/PageInitializer.cs @@ -36,13 +36,11 @@ public void Initialize(IHttpHandler handler) /// /// public string GetInlineStyle() - { - var iconUrl = "client-components/sf-mvc-ext.png"; + { 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 fullIconUrl = RouteHelper.ResolveUrl(string.Format("~/{0}{1}", FrontendManager.VirtualPathBuilder.GetVirtualPath(this.GetType().Assembly), iconUrl), UrlResolveOptions.Rooted); - var cssValue = @".sfMvcIcn { position: relative; } .sfMvcIcn:after { content: """"; background: transparent url(" + fullIconUrl + ") no-repeat; width: 26px; height: 17px;display: block; position: absolute; left: 29px; bottom: 0px;} a.sfAddContentLnk.sfMvcIcn:after{ top: 22px; left: 0; width: 100%; background-position: calc(50% + 15px); }"; + 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; 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/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 c24af6b2e..3ed602e18 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DefaultUrlParamsMapper.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DefaultUrlParamsMapper.cs @@ -21,12 +21,12 @@ public DefaultUrlParamsMapper(ControllerBase controller) } /// - protected override bool TryMatchUrl(string[] urlParams, RequestContext requestContext) + 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(true); + RouteHelper.SetUrlParametersResolved(); return true; } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DetailActionParamsMapper.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DetailActionParamsMapper.cs index 1b42ea266..9679afd48 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DetailActionParamsMapper.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/DetailActionParamsMapper.cs @@ -5,12 +5,19 @@ 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 { @@ -19,6 +26,8 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing /// internal class DetailActionParamsMapper : UrlParamsMapperBase { + private bool showDetailsViewOnChildDetailsView; + /// /// Initializes a new instance of the class. /// @@ -62,181 +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 || urlParams.Length == 0) + 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)) { - SystemManager.CurrentHttpContext.Items["detailItem"] = item; + if(setToContext) + SystemManager.CurrentHttpContext.Items["detailItem"] = item; - this.AddContentItemToRouteData(requestContext, redirectUrl, item); + this.AddContentItemToRouteData(requestContext, redirectUrl, item, setUrlParametersResolved); return true; } - else if (urlParams.Length > 1) + else if (this.showDetailsViewOnChildDetailsView) { - this.TryMatchUrl(urlParams.Take(urlParams.Length - 1).ToArray(), requestContext); - - return false; + 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) + bool isSelectedItem = true; + + var selectionModeProperty = model.GetType().GetProperty("SelectionMode"); + if (selectionModeProperty != null) { - redirectUrl = null; - return null; + var selectionMode = selectionModeProperty.GetValue(model); + if (selectionMode != null) + { + 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()); + } + } } - var itemIdFromQueryParam = (SystemManager.CurrentHttpContext.Request.Params["sf-itemId"] ?? SystemManager.CurrentHttpContext.Items["sf-itemId"]) as string; - if (!itemIdFromQueryParam.IsNullOrEmpty()) + 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) { - Guid itemIdGuid; - if (Guid.TryParse(itemIdFromQueryParam, out itemIdGuid)) + var parentFilterMode = parentFilterModeProperty.GetValue(model); + if (parentFilterMode != null && parentFilterMode.ToString() == "Selected") { - redirectUrl = null; - return manager.GetItem(this.ItemType, itemIdGuid) as IDataItem; + return true; } } + 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"); - IDataItem item; - var contentManager = manager as IContentManager; - if (contentManager != null) + if (serializedSelectedItemsIdsProperty != null) { - var isPublished = !this.IsPreviewRequested() || - this.ResolveRequestedItemStatus() == ContentLifecycleStatus.Live; - item = contentManager.GetItemFromUrl(this.ItemType, url, isPublished, out redirectUrl); + var serializedSelectedItemsIds = serializedSelectedItemsIdsProperty.GetValue(model); + if (serializedSelectedItemsIds != null && serializedSelectedItemsIds.ToString() != "[]") + { + return serializedSelectedItemsIds.ToString(); + } + } + + 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; - if (item != null) + // The parent id is retrieved differently depending if it implement IHasParent or is Dynamic content + if (item is IHasParent) + { + hasSelectedParentItem = serializedSelectedParentsIds.ToString().Contains((item as IHasParent).Parent.Id.ToString()); + if (!hasSelectedParentItem) { - var type = item.GetType(); - if (!type.Equals(this.ItemType) && !(type.Module != null && type.Module.ScopeName == "OpenAccessDynamic" && type.BaseType != null && type.BaseType.Equals(this.ItemType))) + // 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) { - item = null; + var folderId = folderIdProperty.GetValue(item); + if (folderId != null) + { + hasSelectedParentItem = serializedSelectedParentsIds.ToString().Contains(folderId.ToString()); + } } } } - else + else if (item is DynamicContent) { - item = ((IUrlProvider)manager.Provider).GetItemFromUrl(this.ItemType, url, out redirectUrl); + hasSelectedParentItem = serializedSelectedParentsIds.ToString().Contains((item as DynamicContent).SystemParentId.ToString()); } - var lifecycleItem = item as ILifecycleDataItem; - var lifecycleManager = manager as ILifecycleManager; - if (lifecycleItem != null && lifecycleManager != null) - { - if (lifecycleItem.Status != ContentLifecycleStatus.Live) - { - item = lifecycleManager.Lifecycle.GetLive(lifecycleItem); - } + return hasSelectedParentItem; + } - object requestedItem; - if (ContentLocatableViewExtensions.TryGetItemWithRequestedStatus(lifecycleItem, lifecycleManager, out requestedItem)) + /// + /// Gets the selected parents ids + /// + /// The widget model + /// The selected parents ids as a string + private string GetSelectedParentsIds(object model) + { + var serializedSelectedParentsIdsProperty = model.GetType().GetProperty("SerializedSelectedParentsIds"); + + if (serializedSelectedParentsIdsProperty != null) + { + var serializedSelectedParentsIds = serializedSelectedParentsIdsProperty.GetValue(model); + if (serializedSelectedParentsIds != null && serializedSelectedParentsIds.ToString() != "[]") { - item = requestedItem as IDataItem; + return serializedSelectedParentsIds.ToString(); } } - return item; + return null; + } + + /// + protected override bool TryMatchUrl(string[] urlParams, RequestContext requestContext, string urlKeyPrefix) + { + return this.TryMatchUrl(urlParams, requestContext, true); } /// - /// Resolves the manager. + /// Adds the content item to route data. /// - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - protected IManager ResolveManager() + /// 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 providerName = this.providerNameResolver != null ? this.providerNameResolver() : null; + requestContext.RouteData.Values[UrlParamsMapperBase.ActionNameKey] = this.actionName; - IManager manager; + var parameters = this.ActionMethod.GetParameters(); + if (parameters.Length > 0 && parameters[0].ParameterType.IsAssignableFrom(this.ItemType)) + { + requestContext.RouteData.Values[parameters[0].ParameterName] = item; + } - try + if (!redirectUrl.IsNullOrEmpty()) { - ManagerBase.TryGetMappedManager(this.ItemType, providerName, out manager); + 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; } - catch (Exception ex) + + if (redirectUrl.IsNullOrEmpty() == false && parameters.Length > 1 && parameters[1].ParameterType == typeof(string)) { - Log.Write(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Exception occurred in the routing functionality, details: {0}", ex)); - manager = null; + requestContext.RouteData.Values[parameters[1].ParameterName] = redirectUrl; } - return manager; + if (setUrlParametersResolved) + { + RouteHelper.SetUrlParametersResolved(); + } } /// - /// This method returns the requested item status based on content location url parameters. + /// Check if the widget is configured to support details mode. /// - /// Copied from IContentLocatableView in Sitefinity. Should use it instead when it goes public. - /// Requested item status. - private ContentLifecycleStatus ResolveRequestedItemStatus() + protected bool IsDetailsModeSupported() { - var itemStatusParam = SystemManager.CurrentHttpContext.Request.Params["sf-lc-status"] ?? SystemManager.CurrentHttpContext.Items["sf-lc-status"]; - ContentLifecycleStatus status = ContentLifecycleStatus.Live; - if (itemStatusParam != null) + var modelProperty = this.Controller.GetType().GetProperty("Model"); + if (modelProperty != null) { - if (!Enum.TryParse(itemStatusParam as string, out status)) - status = ContentLifecycleStatus.Live; + 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 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.Params["sf-content-action"]; - bool isPreview = actionParam != null && actionParam == "preview"; - return isPreview; + return true; } protected Type ItemType { get; set; } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/FeatherActionInvoker.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/FeatherActionInvoker.cs index 4a9751c2a..d960cf273 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/FeatherActionInvoker.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/FeatherActionInvoker.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.ComponentModel; using System.Linq; using System.Reflection; using System.Threading; @@ -9,14 +10,17 @@ using System.Web.UI; using Telerik.Sitefinity.Abstractions; using Telerik.Sitefinity.Configuration; -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.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; @@ -39,8 +43,30 @@ 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. @@ -78,7 +104,24 @@ protected override void InitializeRouteParameters(MvcProxyBase proxyControl) var originalParams = MvcRequestContextBuilder.GetRouteParams(originalContext); var requestContext = proxyControl.RequestContext; - paramsMapper.ResolveUrlParams(originalParams, 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); @@ -91,14 +134,23 @@ protected override void InitializeRouteParameters(MvcProxyBase proxyControl) } else { - if (FrontendManager.AttributeRouting.UpdateRouteData(this.Context, controller.RouteData)) + if (this.ShouldProcessRequest(controller)) { - //// Attribute routing was successful. - RouteHelper.SetUrlParametersResolved(); + // 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(); + } } } - - controller.TempData.Add("IsInPureMode", proxyControl.IsInPureMode); } /// @@ -108,6 +160,10 @@ protected override void InitializeRouteParameters(MvcProxyBase proxyControl) [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; @@ -133,6 +189,14 @@ protected override void ExecuteController(MvcProxyBase proxyControl) /// 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; @@ -158,38 +222,28 @@ protected virtual bool ShouldDisplayErrors() return customErrors.Mode == CustomErrorsMode.Off || (customErrors.Mode == CustomErrorsMode.RemoteOnly && HttpContext.Current.Request.IsLocal); } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - private IEnumerable GetProviderNames(ControllerBase controller, Type contentType) + internal static object GetModelProperty(ControllerBase controller, string propertyName) { - var providerNameProperty = controller.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).FirstOrDefault(p => p.Name == "ProviderName" && p.PropertyType == typeof(string)); + object wrapper; + var modelProperty = controller.GetType().GetProperty("Model"); - if (providerNameProperty != null) + if (modelProperty != null) { - return new string[1] { providerNameProperty.GetValue(controller, null) as string }; + wrapper = modelProperty.GetValue(controller, null); } else { - IManager manager; + wrapper = controller; + } - 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; - } + var providerNameProperty = wrapper.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).FirstOrDefault(p => p.Name == propertyName); - if (manager != null) - { - return manager.Providers.Select(p => p.Name); - } - else - { - return new string[0]; - } + if (providerNameProperty != null) + { + return providerNameProperty.GetValue(wrapper, null); } + + return null; } private IUrlParamsMapper GetInferredDetailActionParamsMapper(ControllerBase controller) @@ -216,12 +270,8 @@ private IUrlParamsMapper GetInferredDetailActionParamsMapper(ControllerBase cont 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)); - } + var providerNames = GetModelProperty(controller, "ProviderName") as string; + result = result.SetLast(new DetailActionParamsMapper(controller, contentType, () => providerNames)); } } } @@ -229,6 +279,62 @@ private IUrlParamsMapper GetInferredDetailActionParamsMapper(ControllerBase cont 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); @@ -236,22 +342,80 @@ private IUrlParamsMapper GetInferredTaxonFilterMapper(ControllerBase controller, 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; - result = new CustomActionParamsMapper(controller, () => "/{" + taxonParamName + ":category,tag}/{" + pageParamName + "}", actionName); + var urlParamNames = new string[] { FeatherActionInvoker.TaxonNamedParamter, FeatherActionInvoker.PagingNamedParameter }; + result = new CustomActionParamsMapper(controller, () => "/{" + taxonParamName + ":" + routeTemplate + "}/{" + pageParamName + ":int}", actionName, urlParamNames); } - result = result.SetLast(new CustomActionParamsMapper(controller, () => "/{" + taxonParamName + ":category,tag}", actionName)); + 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); @@ -269,7 +433,9 @@ private IUrlParamsMapper GetInferredPagingMapper(ControllerBase controller, stri if (actionDescriptor == null || actionDescriptor.GetParameters().Length == 0 || actionDescriptor.GetParameters()[0].ParameterType != typeof(int?)) return null; - return new CustomActionParamsMapper(controller, () => "/{" + actionDescriptor.GetParameters()[0].ParameterName + ":int}", actionName); + var urlParamNames = new string[] { FeatherActionInvoker.PagingNamedParameter }; + + return new CustomActionParamsMapper(controller, () => "/{" + actionDescriptor.GetParameters()[0].ParameterName + ":int}", actionName, urlParamNames); } private void SetControllerRouteParam(MvcProxyBase proxyControl) @@ -354,5 +520,15 @@ private void TryLoadTempData(Controller controller) /// 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/MvcTemplateEditorRouteHandler.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcTemplateEditorRouteHandler.cs index c917a09ca..d25764d08 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcTemplateEditorRouteHandler.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/MvcTemplateEditorRouteHandler.cs @@ -10,7 +10,7 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing /// /// Extended version of the TemplateEditorRouteHandler that injects logic handling MVC layout files. /// - internal class MvcTemplateEditorRouteHandler : TemplateEditorRouteHandler + public class MvcTemplateEditorRouteHandler : TemplateEditorRouteHandler { /// /// Builds the handler. diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/PageRelativePathContextRegion.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/PageRelativePathContextRegion.cs index d3478ab45..a732308ad 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/PageRelativePathContextRegion.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/PageRelativePathContextRegion.cs @@ -1,5 +1,6 @@ using System; using System.Web; +using Telerik.Sitefinity.Services; using Telerik.Sitefinity.Web; namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing @@ -22,18 +23,34 @@ public PageRelativePathContextRegion(HttpContextBase 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) + 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); - if (newPath.Equals("Action/Edit/", StringComparison.OrdinalIgnoreCase)) - newPath = string.Empty; 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("~/"); } } 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 index ec54d290b..5ab5b8d00 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/ITaxonUrlEvaluatorAdapter.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/ITaxonUrlEvaluatorAdapter.cs @@ -1,11 +1,9 @@ -using Telerik.Sitefinity.Pages.Model; using Telerik.Sitefinity.Taxonomies.Model; -using Telerik.Sitefinity.Web.UrlEvaluation; namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing { internal interface ITaxonUrlEvaluatorAdapter { - bool TryGetTaxonFromUrl(string url, out ITaxon taxon); + 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/TaxonUrlEvaluatorAdapter.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlEvaluatorAdapter.cs index 39a983e49..809f5ac5f 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlEvaluatorAdapter.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlEvaluatorAdapter.cs @@ -15,9 +15,9 @@ public TaxonUrlEvaluatorAdapter() } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] - public bool TryGetTaxonFromUrl(string url, out ITaxon taxon) + public bool TryGetTaxonFromUrl(string url, string urlKeyPrefix, out ITaxon taxon) { - taxon = this.GetTaxonFromUrl(url, UrlEvaluationMode.UrlPath); + taxon = this.GetTaxonFromUrl(url, UrlEvaluationMode.UrlPath, urlKeyPrefix); return taxon != null; } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlMapper.cs b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlMapper.cs index 2047ee6a4..29461396d 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlMapper.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonUrlMapper.cs @@ -1,8 +1,7 @@ using System; using System.Linq; -using Telerik.Sitefinity.Pages.Model; +using System.Web.Routing; using Telerik.Sitefinity.Taxonomies.Model; -using Telerik.Sitefinity.Web.UrlEvaluation; namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing { @@ -33,33 +32,47 @@ public TaxonUrlMapper(ITaxonUrlEvaluatorAdapter 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, out ITaxon taxon, out int pageIndex) + 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) { - return false; + 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, out taxon)) + 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; } - bool hasPageIndex = this.TryGetLastPageIndex(urlParams, out pageIndex); - return this.CheckForValidFlatTaxonUrl(urlParams, hasPageIndex); } @@ -89,13 +102,13 @@ private bool CheckForValidFlatTaxonUrl(string[] urlParams, bool isPreviousPageIn ITaxon taxon; int pageIndex; - bool hasPageIndex = this.TryGetLastPageIndex(urlParams, out 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, out taxon); + bool hasTaxon = this.taxonomyEvaluator.TryGetTaxonFromUrl(url, null, out taxon); if (!hasPageIndex && hasTaxon) { @@ -118,12 +131,24 @@ private bool CheckForValidFlatTaxonUrl(string[] urlParams, bool isPreviousPageIn /// /// The URL params. /// Index of the page. + /// The taxon which is filtered. /// - private bool TryGetLastPageIndex(string[] urlParams, out int pageIndex) + private bool TryGetPageIndex(string[] urlParams, out int pageIndex, string taxonName = null) { string last = urlParams.LastOrDefault(); - return int.TryParse(last, out pageIndex); + 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 index f13a7cdb7..2c22ea648 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonomyUrlParamsMapper.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Infrastructure/Routing/Taxonomy/TaxonomyUrlParamsMapper.cs @@ -1,12 +1,8 @@ -using System; -using System.Linq; using System.Reflection; using System.Web.Mvc; using System.Web.Routing; -using Telerik.Sitefinity.Pages.Model; using Telerik.Sitefinity.Taxonomies.Model; using Telerik.Sitefinity.Web; -using Telerik.Sitefinity.Web.UrlEvaluation; namespace Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Routing { @@ -29,18 +25,20 @@ public TaxonomyUrlParamsMapper(ControllerBase controller, TaxonUrlMapper taxonUr } /// - protected override bool TryMatchUrl(string[] urlParams, RequestContext requestContext) + protected override bool TryMatchUrl(string[] urlParams, RequestContext requestContext, string urlKeyPrefix) { ITaxon taxon; int pageIndex; - if (!this.taxonUrlEvaluator.TryMatch(urlParams, out taxon, out 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; 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/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 index 218f91754..e5310e302 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Models/ContentDetailsViewModel.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/ContentDetailsViewModel.cs @@ -40,6 +40,7 @@ public class ContentDetailsViewModel /// /// 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 index 7e615a295..15f55174b 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Models/ContentListViewModel.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/ContentListViewModel.cs @@ -27,6 +27,13 @@ public class ContentListViewModel /// 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. /// diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/ContentModelBase.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/ContentModelBase.cs index 675934545..03f4b8b42 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Models/ContentModelBase.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/ContentModelBase.cs @@ -3,19 +3,22 @@ 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 { @@ -79,6 +82,7 @@ public virtual string SerializedSelectedItemsIds /// /// 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; } /// @@ -120,6 +124,25 @@ public virtual int? ItemsPerPage } } + /// + /// 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. /// @@ -155,6 +178,22 @@ public virtual string SortExpression /// 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. @@ -201,6 +240,32 @@ public virtual string SortExpression [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 @@ -214,10 +279,29 @@ public virtual IEnumerable GetLocations() location.ContentType = this.ContentType; location.ProviderName = this.GetManager().Provider.Name; - var filterExpression = this.CompileFilterExpression(); - if (!string.IsNullOrEmpty(filterExpression)) + switch (this.ContentViewDisplayMode) { - location.Filters.Add(new BasicContentLocationFilter(filterExpression)); + 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 }; @@ -235,11 +319,12 @@ public virtual ContentListViewModel CreateListViewModel(ITaxon taxonFilter, int 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 this.CreateListViewModelInstance(); + return viewModel; - var viewModel = this.CreateListViewModelInstance(); if (taxonFilter != null) { var taxonomy = taxonFilter.Taxonomy.RootTaxonomy ?? taxonFilter.Taxonomy; @@ -251,12 +336,6 @@ public virtual ContentListViewModel CreateListViewModel(ITaxon taxonFilter, int var filter = string.Format(CultureInfo.InvariantCulture, "{0}.Contains({{{1}}})", taxonomyField, taxonFilter.Id); query = query.Where(filter); } - else - { - viewModel.Items = Enumerable.Empty(); - this.SetViewModelProperties(viewModel, page, null); - return viewModel; - } } this.PopulateListViewModel(page, query, viewModel); @@ -280,14 +359,14 @@ public virtual ContentListViewModel CreateListViewModelByRelatedItem(IDataItem r throw new ArgumentNullException("relatedItem"); int? totalCount = 0; - var query = this.GetRelatedItems(relatedItem, 1, ref totalCount); + 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; + viewModel.TotalPagesCount = (totalCount + this.ItemsPerPage - 1) / this.ItemsPerPage; viewModel.CurrentPage = page; viewModel.ProviderName = this.ProviderName; @@ -298,6 +377,35 @@ public virtual ContentListViewModel CreateListViewModelByRelatedItem(IDataItem r 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. /// @@ -311,7 +419,6 @@ public virtual ContentDetailsViewModel CreateDetailsViewModel(IDataItem item) viewModel.Item = this.CreateItemViewModelInstance(item); viewModel.ContentType = this.ContentType; viewModel.ProviderName = this.ProviderName; - viewModel.EnableSocialSharing = this.EnableSocialSharing; return viewModel; } @@ -332,7 +439,13 @@ public virtual IList GetKeysOfDependentObjects(ContentListVi { var contentResolvedType = this.ContentType; var result = new List(1); - result.Add(new CacheDependencyKey { Key = null, Type = contentResolvedType }); + 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; } @@ -360,9 +473,11 @@ public virtual IList GetKeysOfDependentObjects(ContentDetail var result = new List(1); if (viewModel.Item != null && viewModel.Item.Fields.Id != Guid.Empty) { - result.Add(new CacheDependencyKey { Key = viewModel.Item.Fields.Id.ToString(), Type = contentResolvedType }); + result.AddRange(OutputCacheDependencyHelper.GetPublishedContentCacheDependencyKeys(contentResolvedType, viewModel.Item.Fields.Id)); } + this.AddCommonDependencies(result, this.ContentType, viewModel.Item); + return result; } else @@ -394,27 +509,57 @@ protected virtual IEnumerable ApplyListSettings(int page, IQuerya throw new ArgumentException("'page' argument has to be at least 1.", "page"); int? itemsToSkip = (page - 1) * this.ItemsPerPage; - itemsToSkip = this.DisplayMode == ListDisplayMode.Paging ? ((page - 1) * this.ItemsPerPage) : null; + itemsToSkip = this.DisplayMode == ListDisplayMode.Paging && this.ContentViewDisplayMode != ContentViewDisplayMode.Detail ? ((page - 1) * this.ItemsPerPage) : null; int? totalCount = 0; - int? take = this.DisplayMode == ListDisplayMode.All ? null : this.ItemsPerPage; + 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 = query.ToArray(); + var queryResult = this.FetchItems(query); + queryResult.SetRelatedDataSourceContext(); + + TaxonomyApplicationState.SetTaxonomyDataSourceContext(queryResult); foreach (var item in queryResult) { result.Add(this.CreateItemViewModelInstance(item)); } - totalPages = (int)Math.Ceiling(totalCount.Value / (double)this.ItemsPerPage.Value); - totalPages = this.DisplayMode == ListDisplayMode.Paging ? totalPages : null; + 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. /// @@ -443,6 +588,21 @@ 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. /// @@ -458,6 +618,11 @@ protected virtual string CompileFilterExpression() 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); } @@ -489,7 +654,7 @@ protected virtual string CompileFilterExpression() protected virtual void PopulateListViewModel(int page, IQueryable query, ContentListViewModel viewModel) { int? totalPages = null; - if (this.SelectionMode == Models.SelectionMode.SelectedItems && this.selectedItemsIds.Count == 0) + if (this.SelectionMode == Models.SelectionMode.SelectedItems && (this.selectedItemsIds.Count == 0 || string.IsNullOrEmpty(this.GetSelectedItemsFilterExpression()))) { viewModel.Items = Enumerable.Empty(); } @@ -586,7 +751,7 @@ protected virtual string AdaptMultilingualFilterExpression(string filterExpressi CultureInfo uiCulture; if (SystemManager.CurrentContext.AppSettings.Multilingual) { - uiCulture = System.Globalization.CultureInfo.CurrentUICulture; + uiCulture = Telerik.Sitefinity.Services.SystemManager.CurrentContext.Culture; } else { @@ -670,6 +835,21 @@ protected virtual IQueryable SetExpression(IQueryable query 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 @@ -696,22 +876,53 @@ private bool TryGetTaxonomyFieldName(Guid taxonomyId, out string taxonomyField) return taxonomyPropertyDescriptor != null; } + /// + /// Gets the selected items filter expression + /// + /// The selected items filter expression. [System.Diagnostics.CodeAnalysis.SuppressMessage("Telerik.Sitefinity", "SF1002:AvoidToListOnIEnumerable")] - private string GetSelectedItemsFilterExpression() + [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 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) - .Distinct(); + var masterAndLiveIds = this.GetMasterAndLiveIdsFromSelection(); - var selectedItemConditions = masterIds.Select(id => "Id = {0} OR OriginalContentId = {0}".Arrange(id.ToString("D"))); + 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(); @@ -729,6 +940,7 @@ private IQueryable GetRelatedItems(IDataItem relatedItem, int page, r return relatedItems; } + #endregion #region Private fields and constants @@ -736,6 +948,8 @@ private IQueryable GetRelatedItems(IDataItem relatedItem, int page, r 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(); diff --git a/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerModel.cs index 69917ebb4..2e389e23f 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerModel.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerModel.cs @@ -8,15 +8,17 @@ 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. /// - internal class DesignerModel : IDesignerModel + internal class DesignerModel : IDesignerModel { /// /// Initializes a new instance of the class. @@ -26,35 +28,52 @@ internal class DesignerModel : IDesignerModel /// 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, Guid controlId, 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) { - this.Caption = widgetName; - - 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).ToArray(); - 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); - } + this.Control = this.LoadControl(controlId, mediaType); + } /// public virtual IEnumerable Views @@ -72,6 +91,20 @@ public virtual IEnumerable ScriptReferences { return this.scriptReferences; } + } + + /// + public virtual IEnumerable ModuleDependencies + { + get + { + return this.moduleDependencies; + } + + private set + { + this.moduleDependencies = value; + } } /// @@ -107,11 +140,15 @@ 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) @@ -123,33 +160,41 @@ protected string ExtractViewName(string filename) } /// - /// Populates the script references. + /// Populates the script references and dependent modules. /// /// Name of the widget. /// The view configs. - protected 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 @@ -159,8 +204,8 @@ protected void PopulateScriptReferences(string widgetName, IEnumerable /// Gets the name of the script file for a given view. /// @@ -201,6 +246,7 @@ protected DesignerViewConfigModel GetViewConfig(string view, IEnumerable var text = streamReader.ReadToEnd(); var designerViewConfigModel = new JavaScriptSerializer().Deserialize(text); + this.PopulateModulesForScripts(designerViewConfigModel.Scripts); this.PopulateComponentsScriptReferences(designerViewConfigModel); return designerViewConfigModel; @@ -210,6 +256,100 @@ protected DesignerViewConfigModel GetViewConfig(string view, IEnumerable 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) { @@ -225,7 +365,7 @@ private void PopulateComponentsScriptReferences(DesignerViewConfigModel designer designerViewConfigModel.Scripts = new List(); } - designerViewConfigModel.Scripts = ScriptDependencyResolver.GetScripts(designerViewConfigModel.Components, designerViewConfigModel.Scripts); + designerViewConfigModel.Scripts = ComponentsDependencyResolver.GetScripts(designerViewConfigModel.Components, designerViewConfigModel.Scripts); } } @@ -246,33 +386,46 @@ private string GetScriptPath(string scriptFileName, string widgetName, string pa return scriptVirtualPath; } - private Control LoadControl(Guid controlId) + private Control LoadControl(Guid controlId, DesignMediaType designMediaType) { if (controlId != Guid.Empty) - { - var pageManager = PageManager.GetManager(); - var objectData = pageManager.GetControl(controlId); - - var controlData = objectData as ControlData; - if (controlData != null && !controlData.Caption.IsNullOrEmpty()) - { - this.Caption = controlData.Caption; - } - - return pageManager.LoadControl(objectData); + { + 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 2c2919cad..f529a48e0 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerViewConfigModel.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/DesignerViewConfigModel.cs @@ -43,6 +43,15 @@ internal class DesignerViewConfigModel /// The components. /// [DataMember(Name = "components")] - public IList Components { get; set; } + 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 index d2bf44fba..2d8f91588 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Models/DynamicDataItemFieldAccessor.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/DynamicDataItemFieldAccessor.cs @@ -1,12 +1,17 @@ using System; -using System.Collections.Generic; using System.ComponentModel; using System.Dynamic; using System.Linq; -using System.Text; +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.RelatedData; +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 { @@ -18,11 +23,16 @@ public class DynamicDataItemFieldAccessor : DynamicObject /// /// Initializes a new instance of the class. /// - /// The data item. + /// The data item. public DynamicDataItemFieldAccessor(ItemViewModel itemViewModel) : base() { this.item = itemViewModel; + + if (this.item.DataItem is IDeferredHtmlFilterContainer deferredFilterContainer) + { + deferredFilterContainer.MarkForDefferedFiltering(); + } } /// @@ -57,7 +67,27 @@ public object GetMemberValue(string fieldName) var relatedDataInfo = propInfo as RelatedDataPropertyDescriptor; if (relatedDataInfo == null) { - return propInfo.GetValue(this.item.DataItem); + 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 { @@ -77,6 +107,48 @@ public object GetMemberValue(string fieldName) } } - private ItemViewModel item; + 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/IDesignerModel.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/IDesignerModel.cs index b52c31c40..b02afae0e 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Models/IDesignerModel.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/IDesignerModel.cs @@ -18,6 +18,14 @@ 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. /// 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 index 40254f639..922281249 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Models/ItemViewModel.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/ItemViewModel.cs @@ -6,14 +6,19 @@ 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 { @@ -229,7 +234,7 @@ public virtual string GetPrice(string fieldName, string format) if (fieldValue == null) return null; - var formattedValue = string.Format(fieldValue.ToString(), format); + var formattedValue = fieldValue.ToString(format); return formattedValue; } @@ -288,7 +293,6 @@ public virtual string GetMultipleChoiceValueString(string fieldName) /// Gets the flat taxons. /// /// Name of the field. - /// The classification identifier. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Taxons")] public virtual IList GetFlatTaxons(string fieldName) @@ -298,15 +302,11 @@ public virtual IList GetFlatTaxons(string fieldName) if (this.cachedFieldValues.TryGetValue(cahcedResultKey, out cachedResult)) return cachedResult as IList; - var taxonIds = this.Fields.GetMemberValue(fieldName) as IList; - TaxonomyManager manager = TaxonomyManager.GetManager(); + var taxa = TaxonomyApplicationState.GetTaxa(this.DataItem, fieldName); - var taxonNames = manager.GetTaxa() - .Where(t => taxonIds.Contains(t.Id) && t.Taxonomy.Name == fieldName).ToList(); + this.cachedFieldValues[cahcedResultKey] = taxa; - this.cachedFieldValues[cahcedResultKey] = taxonNames; - - return taxonNames; + return taxa; } /// @@ -322,21 +322,11 @@ public virtual IList GetHierarchicalTaxons(string fieldName) if (this.cachedFieldValues.TryGetValue(cahcedResultKey, out cachedResult)) return cachedResult as IList; - var taxonIds = this.Fields.GetMemberValue(fieldName) as IList; - string taxonomyName; - TaxonomyManager manager = TaxonomyManager.GetManager(); - if (fieldName == "Category") - taxonomyName = "Categories"; - else if (fieldName == "Department") - taxonomyName = "Departments"; - else - taxonomyName = fieldName; + var taxa = TaxonomyApplicationState.GetTaxa(this.DataItem, fieldName); - var taxonNames = manager.GetTaxa() - .Where(t => taxonIds.Contains(t.Id) && t.Taxonomy.Name == taxonomyName).ToList(); - this.cachedFieldValues[cahcedResultKey] = taxonNames; + this.cachedFieldValues[cahcedResultKey] = taxa; - return taxonNames; + return taxa; } /// @@ -392,6 +382,7 @@ public virtual IEnumerable RelatedItems(string fieldName) else result = null; + AddCacheDependenciesForRelatedItems(relatedItems); this.cachedFieldValues[cahcedResultKey] = result; return result; @@ -414,10 +405,12 @@ public virtual ItemViewModel RelatedItem(string fieldName) 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(); @@ -470,6 +463,55 @@ private string FieldCacheKey(string methodName, string fieldName) /// 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/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 index 41a8bb3d2..5ea80f9f0 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Models/ScriptDependencyConfigModel.cs +++ b/Telerik.Sitefinity.Frontend/Mvc/Models/ScriptDependencyConfigModel.cs @@ -7,7 +7,7 @@ namespace Telerik.Sitefinity.Frontend.Mvc.Models { /// - /// This class represents a JSON configuration for component cefinitions. + /// This class represents a JSON configuration for component definitions. /// internal class ScriptDependencyConfigModel { @@ -28,5 +28,14 @@ internal class ScriptDependencyConfigModel /// [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/ScriptDependencyResolver.cs b/Telerik.Sitefinity.Frontend/Mvc/Models/ScriptDependencyResolver.cs deleted file mode 100644 index 0c9a750ce..000000000 --- a/Telerik.Sitefinity.Frontend/Mvc/Models/ScriptDependencyResolver.cs +++ /dev/null @@ -1,130 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Web.Script.Serialization; -using Telerik.Sitefinity.Abstractions; -using Telerik.Sitefinity.Abstractions.VirtualPath; -using Telerik.Sitefinity.Services; - -namespace Telerik.Sitefinity.Frontend.Mvc.Models -{ - /// - /// This class resolves script dependencies for components. - /// - internal static class ScriptDependencyResolver - { - /// - /// Gets the scripts. - /// - /// The components. - /// - 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(ScriptDependencyResolver.GetComponentScripts(comp)); - } - - return ScriptDependencyResolver.OrderScripts(dependencyScripts, originalScripts); - } - - 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 GetComponentScripts(string component) - { - var allScripts = new List(); - - if (!string.IsNullOrEmpty(component) && ScriptDependencyResolver.ComponentsDefinitionsDictionary.Value.ContainsKey(component)) - { - var componentDefinitionObject = ScriptDependencyResolver.ComponentsDefinitionsDictionary.Value[component]; - - if (componentDefinitionObject.Scripts != null) - { - allScripts.AddRange(componentDefinitionObject.Scripts); - } - - if (componentDefinitionObject.Components != null) - { - foreach (var comp in componentDefinitionObject.Components) - { - allScripts.AddRange(ScriptDependencyResolver.GetComponentScripts(comp)); - } - } - } - else - { - Log.Write(string.Format(System.Globalization.CultureInfo.InvariantCulture, "The component {0} could not be resolved", component)); - } - - return allScripts.Distinct(); - } - - private static Dictionary Initialize() - { - var assemblyPath = FrontendManager.VirtualPathBuilder.GetVirtualPath(typeof(ScriptDependencyResolver).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 readonly Lazy> ComponentsDefinitionsDictionary = - new Lazy>(ScriptDependencyResolver.Initialize, true); - } -} 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 19900d379..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.3.15 - * (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; } @@ -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 @@ -90,7 +102,7 @@ function shallowClearAndCopy(src, dst) { }]); * ``` * - * @param {string} url A parametrized URL template with parameters prefixed by `:` as in + * @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. * @@ -102,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 actions that should extend - * the default set of resource actions. The declaration should be created in the format of {@link - * ng.$http#usage $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: * @@ -131,74 +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 to using `angular.toJson`. To prevent this behavior, set + * 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. - * 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}` – 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 only supported option is - * - * Where: + * 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 @@ -209,155 +252,329 @@ 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. + * + * Calling these methods invokes `$http` on the `url` template with the given HTTP `method`, + * `params` and `headers`. * - * The object returned from this function execution is a resource "class" which has "static" method - * for each action in the definition. + * @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']). - provider('$resource', function() { + info({ angularVersion: '1.8.2' }). + provider('$resource', function ResourceProvider() { + var PROTOCOL_AND_IPV6_REGEX = /^https?:\/\/\[[^\]]*][^/]*/; + var provider = this; + /** + * @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'} + * }; + * }); + * ``` + * + */ this.defaults = { // Strip slashes by default stripTrailingSlashes: true, + // Make non-instance requests cancellable (via `$cancelRequest()`) + cancellable: false, + // Default actions configuration actions: { 'get': {method: 'GET'}, @@ -368,52 +585,18 @@ angular.module('ngResource', ['ng']). } }; - this.$get = ['$http', '$q', function($http, $q) { + this.$get = ['$http', '$log', '$q', '$timeout', function($http, $log, $q, $timeout) { 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, '+'); - } - - - /** - * 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 = "!" / "$" / "&" / "'" / "(" / ")" - * / "*" / "+" / "," / ";" / "=" - */ - function encodeUriQuery(val, pctEncodeSpaces) { - return encodeURIComponent(val). - replace(/%40/gi, '@'). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, (pctEncodeSpaces ? '%20' : '+')); - } + 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; @@ -426,32 +609,43 @@ angular.module('ngResource', ['ng']). var self = this, url = actionUrl || self.template, val, - encodedVal; + encodedVal, + protocolAndIpv6 = ''; - var urlParams = self.urlParams = {}; + 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."); + 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; + 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(_, urlParam) { + forEach(self.urlParams, function(paramInfo, 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) { + if (isDefined(val) && val !== null) { + if (paramInfo.isQueryParamValue) { + encodedVal = encodeUriQuery(val, true); + } else { + 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, + url = url.replace(new RegExp('(/?):' + urlParam + '(\\W|$)', 'g'), function(match, leadingSlashes, tail) { - if (tail.charAt(0) == '/') { + if (tail.charAt(0) === '/') { return tail; } else { return leadingSlashes + tail; @@ -465,11 +659,12 @@ angular.module('ngResource', ['ng']). 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` + // 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(/\/\\\./, '/.'); + // 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 @@ -492,8 +687,8 @@ angular.module('ngResource', ['ng']). var ids = {}; actionParams = extend({}, paramDefaults, actionParams); forEach(actionParams, function(value, key) { - if (isFunction(value)) { value = value(); } - ids[key] = value && value.charAt && value.charAt(0) == '@' ? + if (isFunction(value)) { value = value(data); } + ids[key] = value && value.charAt && value.charAt(0) === '@' ? lookupDottedPath(data, value.substr(1)) : value; }); return ids; @@ -511,89 +706,132 @@ angular.module('ngResource', ['ng']). var data = extend({}, this); delete data.$promise; delete data.$resolved; + delete data.$cancelRequest; return data; }; forEach(actions, function(action, name) { - var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method); + 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; + } Resource[name] = function(a1, a2, a3, a4) { - var params = {}, data, success, error; + var params = {}, data, onSuccess, onError; - /* jshint -W086 */ /* (purposefully fall through case statements) */ switch (arguments.length) { case 4: - error = a4; - success = a3; - //fallthrough + onError = a4; + onSuccess = a3; + // falls through case 3: case 2: if (isFunction(a2)) { if (isFunction(a1)) { - success = a1; - error = a2; + onSuccess = a1; + onError = a2; break; } - success = a2; - error = a3; - //fallthrough + onSuccess = a2; + onError = a3; + // falls through } else { params = a1; data = a2; - success = a3; + onSuccess = a3; break; } + // falls through case 1: - if (isFunction(a1)) success = a1; + if (isFunction(a1)) onSuccess = 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", + '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 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 || - undefined; + $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) { - if (key != 'params' && key != 'isArray' && key != 'interceptor') { - httpConfig[key] = copy(value); + switch (key) { + default: + httpConfig[key] = copy(value); + break; + case 'params': + case 'isArray': + case 'interceptor': + case 'cancellable': + break; } }); + if (!isInstanceCall && cancellable) { + timeoutDeferred = $q.defer(); + httpConfig.timeout = timeoutDeferred.promise; + + if (numericTimeout) { + numericTimeoutPromise = $timeout(timeoutDeferred.resolve, numericTimeout); + } + } + 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; + // 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 - // jshint -W018 - if (angular.isArray(data) !== (!!action.isArray)) { + 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}', name, action.isArray ? 'array' : 'object', - angular.isArray(data) ? 'array' : 'object'); + 'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object', + isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url); } - // jshint +W018 if (action.isArray) { value.length = 0; forEach(data, function(item) { - if (typeof item === "object") { + if (typeof item === 'object') { value.push(new Resource(item)); } else { // Valid JSON values may be string literals, and these should not be converted @@ -603,31 +841,32 @@ angular.module('ngResource', ['ng']). } }); } else { + var promise = value.$promise; // Save the promise shallowClearAndCopy(data, value); - value.$promise = promise; + value.$promise = promise; // Restore the promise } } - value.$resolved = true; - - 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) { + promise = promise['finally'](function() { value.$resolved = true; - - (error || noop)(response); - - return $q.reject(response); + if (!isInstanceCall && cancellable) { + value.$cancelRequest = noop; + $timeout.cancel(numericTimeoutPromise); + timeoutDeferred = numericTimeoutPromise = httpConfig.timeout = null; + } }); - promise = promise.then( - function(response) { - var value = responseInterceptor(response); - (success || noop)(value, response.headers); - return value; - }, - responseErrorInterceptor); + // Run the `success`/`error` callbacks, but do not let them affect the returned promise. + promise.then(successCallback, errorCallback); if (!isInstanceCall) { // we are creating instance / collection @@ -635,12 +874,20 @@ angular.module('ngResource', ['ng']). // - return the instance / collection value.$promise = promise; value.$resolved = false; + if (cancellable) value.$cancelRequest = cancelRequest; return value; } // instance call return promise; + + function cancelRequest(value) { + promise.catch(noop); + if (timeoutDeferred !== null) { + timeoutDeferred.resolve(value); + } + } }; @@ -653,10 +900,6 @@ angular.module('ngResource', ['ng']). }; }); - Resource.bind = function(additionalParamDefaults) { - return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions); - }; - return Resource; } 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 02ec4eea8..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.3.15 - (c) 2010-2014 Google, Inc. http://angularjs.org + AngularJS v1.8.2 + (c) 2010-2020 Google LLC. http://angularjs.org License: MIT */ -(function(I,d,B){'use strict';function D(f,q){q=q||{};d.forEach(q,function(d,h){delete q[h]});for(var h in f)!f.hasOwnProperty(h)||"$"===h.charAt(0)&&"$"===h.charAt(1)||(q[h]=f[h]);return q}var w=d.$$minErr("$resource"),C=/^(\.[a-zA-Z_$][0-9a-zA-Z_$]*)+$/;d.module("ngResource",["ng"]).provider("$resource",function(){var f=this;this.defaults={stripTrailingSlashes:!0,actions:{get:{method:"GET"},save:{method:"POST"},query:{method:"GET",isArray:!0},remove:{method:"DELETE"},"delete":{method:"DELETE"}}}; -this.$get=["$http","$q",function(q,h){function t(d,g){this.template=d;this.defaults=s({},f.defaults,g);this.urlParams={}}function v(x,g,l,m){function c(b,k){var c={};k=s({},g,k);r(k,function(a,k){u(a)&&(a=a());var d;if(a&&a.charAt&&"@"==a.charAt(0)){d=b;var e=a.substr(1);if(null==e||""===e||"hasOwnProperty"===e||!C.test("."+e))throw w("badmember",e);for(var e=e.split("."),n=0,g=e.length;n */ - /* global -ngRouteModule */ -var ngRouteModule = angular.module('ngRoute', ['ng']). - provider('$route', $RouteProvider), - $routeMinErr = angular.$$minErr('ngRoute'); +/* 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 + * @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() { + isArray = angular.isArray; + isObject = angular.isObject; + isDefined = angular.isDefined; + noop = angular.noop; + function inherit(parent, extra) { return angular.extend(Object.create(parent), extra); } @@ -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. + * + * 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. * - * - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()` + * 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). + * + *
+ * **Note:** This option has no effect if `reloadOnUrl` is set to `false`. + *
* - * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive + * - `[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 @@ -147,7 +290,10 @@ function $RouteProvider() { */ this.when = function(path, route) { //copy original route object to preserve params inherited from proto chain - var routeCopy = angular.copy(route); + var routeCopy = shallowCopy(route); + if (angular.isUndefined(routeCopy.reloadOnUrl)) { + routeCopy.reloadOnUrl = true; + } if (angular.isUndefined(routeCopy.reloadOnSearch)) { routeCopy.reloadOnSearch = true; } @@ -156,18 +302,19 @@ function $RouteProvider() { } routes[path] = angular.extend( routeCopy, - path && pathRegExp(path, routeCopy) + {originalPath: path}, + path && routeToRegExp(path, routeCopy) ); // create redirection for trailing slashes if (path) { - var redirectPath = (path[path.length - 1] == '/') + var redirectPath = (path[path.length - 1] === '/') ? path.substr(0, path.length - 1) : path + '/'; routes[redirectPath] = angular.extend( - {redirectTo: path}, - pathRegExp(redirectPath, routeCopy) + {originalPath: path, redirectTo: path}, + routeToRegExp(redirectPath, routeCopy) ); } @@ -185,47 +332,6 @@ function $RouteProvider() { */ this.caseInsensitiveMatch = false; - /** - * @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 method * @name $routeProvider#otherwise @@ -246,6 +352,47 @@ function $RouteProvider() { 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', @@ -254,7 +401,8 @@ function $RouteProvider() { '$injector', '$templateRequest', '$sce', - function($rootScope, $location, $routeParams, $q, $injector, $templateRequest, $sce) { + '$browser', + function($rootScope, $location, $routeParams, $q, $injector, $templateRequest, $sce, $browser) { /** * @ngdoc service @@ -265,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: @@ -273,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 @@ -335,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; * }) * @@ -373,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/); * }); * * @@ -412,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. * @@ -427,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. */ /** @@ -440,9 +596,12 @@ 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, @@ -464,10 +623,18 @@ function $RouteProvider() { */ reload: function() { forceReload = true; + + var fakeLocationEvent = { + defaultPrevented: false, + preventDefault: function fakePreventDefault() { + this.defaultPrevented = true; + forceReload = false; + } + }; + $rootScope.$evalAsync(function() { - // Don't support cancellation of a reload for now... - prepareRoute(); - commitRoute(); + prepareRoute(fakeLocationEvent); + if (!fakeLocationEvent.defaultPrevented) commitRoute(); }); }, @@ -491,7 +658,7 @@ function $RouteProvider() { // interpolate modifies newParams, only query params are left $location.search(newParams); } else { - throw $routeMinErr('norout', 'Tried updating route when with no current route'); + throw $routeMinErr('norout', 'Tried updating route with no current route'); } } }; @@ -539,9 +706,7 @@ function $RouteProvider() { var lastRoute = $route.current; preparedRoute = parseRoute(); - preparedRouteIsUpdateOnly = preparedRoute && lastRoute && preparedRoute.$$route === lastRoute.$$route - && angular.equals(preparedRoute.pathParams, lastRoute.pathParams) - && !preparedRoute.reloadOnSearch && !forceReload; + preparedRouteIsUpdateOnly = isNavigationUpdateOnly(preparedRoute, lastRoute); if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) { if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) { @@ -563,66 +728,145 @@ function $RouteProvider() { } else if (nextRoute || lastRoute) { forceReload = false; $route.current = nextRoute; - if (nextRoute) { - if (nextRoute.redirectTo) { - if (angular.isString(nextRoute.redirectTo)) { - $location.path(interpolate(nextRoute.redirectTo, nextRoute.params)).search(nextRoute.params) - .replace(); - } else { - $location.url(nextRoute.redirectTo(nextRoute.pathParams, $location.path(), $location.search())) - .replace(); + + 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. - $q.when(nextRoute). - then(function() { - if (nextRoute) { - var locals = angular.extend({}, nextRoute.resolve), - template, templateUrl; + $browser.$$completeOutstandingRequest(noop, '$route'); + }); + } + } - angular.forEach(locals, function(value, key) { - locals[key] = angular.isString(value) ? - $injector.get(value) : $injector.invoke(value, null, null, key); - }); + 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(template = nextRoute.template)) { - if (angular.isFunction(template)) { - template = template(nextRoute.params); - } - } else if (angular.isDefined(templateUrl = nextRoute.templateUrl)) { - if (angular.isFunction(templateUrl)) { - templateUrl = templateUrl(nextRoute.params); - } - templateUrl = $sce.getTrustedResourceUrl(templateUrl); - if (angular.isDefined(templateUrl)) { - nextRoute.loadedTemplateUrl = templateUrl; - template = $templateRequest(templateUrl); - } - } - if (angular.isDefined(template)) { - locals['$template'] = template; - } - return $q.all(locals); + if (angular.isDefined(newUrl)) { + data.url = newUrl; + data.hasRedirection = true; } - }). - // after route change - then(function(locals) { - if (nextRoute == $route.current) { - if (nextRoute) { - nextRoute.locals = locals; - angular.copy(nextRoute.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', nextRoute, lastRoute); - } - }, function(error) { - if (nextRoute == $route.current) { - $rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, 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 @@ -642,6 +886,29 @@ 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 */ @@ -663,6 +930,14 @@ function $RouteProvider() { }]; } +instantiateRoute.$inject = ['$injector']; +function instantiateRoute($injector) { + if (isEagerInstantiationEnabled) { + // Instantiate `$route` + $injector.get('$route'); + } +} + ngRouteModule.provider('$routeParams', $RouteParamsProvider); @@ -670,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. @@ -713,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 @@ -722,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. * @@ -793,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; @@ -838,17 +1114,17 @@ ngRouteModule.directive('ngView', ngViewFillContentFactory); $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; }]); @@ -858,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/); }); @@ -909,8 +1185,8 @@ function ngViewFactory($route, $anchorScroll, $animate) { } if (currentElement) { previousLeaveAnimation = $animate.leave(currentElement); - previousLeaveAnimation.then(function() { - previousLeaveAnimation = null; + previousLeaveAnimation.done(function(response) { + if (response !== false) previousLeaveAnimation = null; }); currentElement = null; } @@ -931,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).then(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(); } @@ -979,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 ca3e81b09..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,15 +1,17 @@ /* - AngularJS v1.3.15 - (c) 2010-2014 Google, Inc. http://angularjs.org + AngularJS v1.8.2 + (c) 2010-2020 Google LLC. http://angularjs.org License: MIT */ -(function(q,d,C){'use strict';function v(r,k,h){return{restrict:"ECA",terminal:!0,priority:400,transclude:"element",link:function(a,f,b,c,y){function z(){l&&(h.cancel(l),l=null);m&&(m.$destroy(),m=null);n&&(l=h.leave(n),l.then(function(){l=null}),n=null)}function x(){var b=r.current&&r.current.locals;if(d.isDefined(b&&b.$template)){var b=a.$new(),c=r.current;n=y(b,function(b){h.enter(b,null,n||f).then(function(){!d.isDefined(t)||t&&!a.$eval(t)||k()});z()});m=c.scope=b;m.$emit("$viewContentLoaded"); -m.$eval(w)}else z()}var m,n,l,t=b.autoscroll,w=b.onload||"";a.$on("$routeChangeSuccess",x);x()}}}function A(d,k,h){return{restrict:"ECA",priority:-400,link:function(a,f){var b=h.current,c=b.locals;f.html(c.$template);var y=d(f.contents());b.controller&&(c.$scope=a,c=k(b.controller,c),b.controllerAs&&(a[b.controllerAs]=c),f.data("$ngControllerController",c),f.children().data("$ngControllerController",c));y(a)}}}q=d.module("ngRoute",["ng"]).provider("$route",function(){function r(a,f){return d.extend(Object.create(a), -f)}function k(a,d){var b=d.caseInsensitiveMatch,c={originalPath:a,regexp:a},h=c.keys=[];a=a.replace(/([().])/g,"\\$1").replace(/(\/)?:(\w+)([\?\*])?/g,function(a,d,b,c){a="?"===c?c:null;c="*"===c?c:null;h.push({name:b,optional:!!a});d=d||"";return""+(a?"":d)+"(?:"+(a?d:"")+(c&&"(.+?)"||"([^/]+)")+(a||"")+")"+(a||"")}).replace(/([\/$\*])/g,"\\$1");c.regexp=new RegExp("^"+a+"$",b?"i":"");return c}var h={};this.when=function(a,f){var b=d.copy(f);d.isUndefined(b.reloadOnSearch)&&(b.reloadOnSearch=!0); -d.isUndefined(b.caseInsensitiveMatch)&&(b.caseInsensitiveMatch=this.caseInsensitiveMatch);h[a]=d.extend(b,a&&k(a,b));if(a){var c="/"==a[a.length-1]?a.substr(0,a.length-1):a+"/";h[c]=d.extend({redirectTo:a},k(c,b))}return this};this.caseInsensitiveMatch=!1;this.otherwise=function(a){"string"===typeof a&&(a={redirectTo:a});this.when(null,a);return this};this.$get=["$rootScope","$location","$routeParams","$q","$injector","$templateRequest","$sce",function(a,f,b,c,k,q,x){function m(b){var e=s.current; -(v=(p=l())&&e&&p.$$route===e.$$route&&d.equals(p.pathParams,e.pathParams)&&!p.reloadOnSearch&&!w)||!e&&!p||a.$broadcast("$routeChangeStart",p,e).defaultPrevented&&b&&b.preventDefault()}function n(){var u=s.current,e=p;if(v)u.params=e.params,d.copy(u.params,b),a.$broadcast("$routeUpdate",u);else if(e||u)w=!1,(s.current=e)&&e.redirectTo&&(d.isString(e.redirectTo)?f.path(t(e.redirectTo,e.params)).search(e.params).replace():f.url(e.redirectTo(e.pathParams,f.path(),f.search())).replace()),c.when(e).then(function(){if(e){var a= -d.extend({},e.resolve),b,g;d.forEach(a,function(b,e){a[e]=d.isString(b)?k.get(b):k.invoke(b,null,null,e)});d.isDefined(b=e.template)?d.isFunction(b)&&(b=b(e.params)):d.isDefined(g=e.templateUrl)&&(d.isFunction(g)&&(g=g(e.params)),g=x.getTrustedResourceUrl(g),d.isDefined(g)&&(e.loadedTemplateUrl=g,b=q(g)));d.isDefined(b)&&(a.$template=b);return c.all(a)}}).then(function(c){e==s.current&&(e&&(e.locals=c,d.copy(e.params,b)),a.$broadcast("$routeChangeSuccess",e,u))},function(b){e==s.current&&a.$broadcast("$routeChangeError", -e,u,b)})}function l(){var a,b;d.forEach(h,function(c,h){var g;if(g=!b){var k=f.path();g=c.keys;var m={};if(c.regexp)if(k=c.regexp.exec(k)){for(var l=1,n=k.length;l/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 e488352b2..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.3.15 - * (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,7 +87,7 @@ * 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. @@ -37,122 +98,148 @@ function minErr(module, ErrorConstructor) { ErrorConstructor = ErrorConstructor || Error; + + var url = 'https://errors.angularjs.org/1.8.2/'; + var regex = url.replace('.', '\\.') + '[\\s\\S]*'; + var errRegExp = new RegExp(regex, 'g'); + return function() { var code = arguments[0], - prefix = '[' + (module ? module + ':' : '') + code + '] ', template = arguments[1], - templateArgs = arguments, + message = '[' + (module ? module + ':' : '') + code + '] ', + templateArgs = sliceArgs(arguments, 2).map(function(arg) { + return toDebugString(arg, minErrConfig.objectMaxDepth); + }), + paramPrefix, i; - message, 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 = prefix + template.replace(/\{\d+\}/g, function(match) { - var index = +match.slice(1, -1), arg; + message += template.replace(/\{\d+\}/g, function(match) { + var index = +match.slice(1, -1); - if (index + 2 < templateArgs.length) { - return toDebugString(templateArgs[index + 2]); + if (index < templateArgs.length) { + return templateArgs[index].replace(errRegExp, ''); } + return match; }); - message = message + '\nhttp://errors.angularjs.org/1.3.15/' + - (module ? module + '/' : '') + code; - for (i = 2; i < arguments.length; i++) { - message = message + (i == 2 ? '?' : '&') + 'p' + (i - 2) + '=' + - encodeURIComponent(toDebugString(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 ErrorConstructor(message); }; } -/* We need to tell jshint what variables are being exported */ -/* global angular: true, - msie: true, - jqLite: true, - jQuery: true, - slice: true, - splice: true, - push: true, - toString: true, - ngMinErr: true, - angularModule: true, - uid: true, - REGEX_STRING_REGEXP: true, - VALIDITY_STATE_PROPERTY: true, - - lowercase: true, - uppercase: true, - manualLowercase: true, - manualUppercase: true, - nodeName_: true, - isArrayLike: true, - forEach: true, - sortedKeys: true, - forEachSorted: true, - reverseParams: true, - nextUid: true, - setHashKey: true, - extend: true, - int: true, - inherit: true, - noop: true, - identity: true, - valueFn: true, - isUndefined: true, - isDefined: true, - isObject: true, - isString: true, - isNumber: true, - isDate: true, - isArray: true, - isFunction: true, - isRegExp: true, - isWindow: true, - isScope: true, - isFile: true, - isFormData: true, - isBlob: true, - isBoolean: true, - isPromiseLike: true, - trim: true, - escapeForRegexp: true, - isElement: true, - makeMap: true, - includes: true, - arrayRemove: true, - copy: true, - shallowCopy: true, - equals: true, - csp: true, - concat: true, - sliceArgs: true, - bind: true, - toJsonReplacer: true, - toJson: true, - fromJson: true, - startingTag: true, - tryDecodeURIComponent: true, - parseKeyValue: true, - toKeyValue: true, - encodeUriSegment: true, - encodeUriQuery: true, - angularInit: true, - bootstrap: true, - getTestability: true, - snake_case: true, - bindJQuery: true, - assertArg: true, - assertArgFn: true, - assertNotHasOwnProperty: true, - getter: true, - getBlockNodes: true, - hasOwnProperty: true, - createMap: true, - - NODE_TYPE_ELEMENT: true, - NODE_TYPE_TEXT: true, - NODE_TYPE_COMMENT: true, - NODE_TYPE_DOCUMENT: true, - NODE_TYPE_DOCUMENT_FRAGMENT: true, +/* 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 */ //////////////////////////////////// @@ -161,15 +248,14 @@ function minErr(module, ErrorConstructor) { * @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]*)$/; @@ -178,24 +264,20 @@ var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/; // 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 - * @kind 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; /** - * @ngdoc function - * @name angular.uppercase - * @module ng - * @kind function + * @private * * @description Converts the specified string to uppercase. * @param {string} string String to be converted to uppercase. @@ -204,29 +286,6 @@ var hasOwnProperty = Object.prototype.hasOwnProperty; 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 msie, // holds major version number for IE, or NaN if UA is not IE. jqLite, // delay binding since jQuery could be loaded after us. @@ -235,6 +294,7 @@ var splice = [].splice, push = [].push, toString = Object.prototype.toString, + getPrototypeOf = Object.getPrototypeOf, ngMinErr = minErr('ng'), /** @name angular */ @@ -242,11 +302,12 @@ var angularModule, uid = 0; +// Support: IE 9-11 only /** * documentMode is an IE-only property * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx */ -msie = document.documentMode; +msie = window.document.documentMode; /** @@ -256,18 +317,24 @@ msie = document.documentMode; * 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 === NODE_TYPE_ELEMENT && 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; } /** @@ -287,7 +354,7 @@ function isArrayLike(obj) { * * 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 + * providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just * return the value provided. * ```js @@ -310,9 +377,7 @@ function forEach(obj, iterator, context) { if (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))) { + if (key !== 'prototype' && key !== 'length' && key !== 'name' && obj.hasOwnProperty(key)) { iterator.call(context, obj[key], key, obj); } } @@ -325,23 +390,32 @@ function forEach(obj, iterator, context) { } } else if (obj.forEach && obj.forEach !== forEach) { obj.forEach(iterator, context, obj); - } else { + } 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, 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); + } + } } } return obj; } -function sortedKeys(obj) { - return Object.keys(obj).sort(); -} - function forEachSorted(obj, iterator, context) { - var keys = sortedKeys(obj); + var keys = Object.keys(obj).sort(); for (var i = 0; i < keys.length; i++) { iterator.call(context, obj[keys[i]], keys[i]); } @@ -355,7 +429,7 @@ 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);}; } /** @@ -386,6 +460,43 @@ function setHashKey(obj, h) { } } + +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 @@ -396,34 +507,68 @@ function setHashKey(obj, h) { * 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). + * + * **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; + return baseExtend(dst, slice.call(arguments, 1), false); +} - for (var i = 1, ii = arguments.length; i < ii; i++) { - var obj = arguments[i]; - if (obj) { - var keys = Object.keys(obj); - for (var j = 0, jj = keys.length; j < jj; j++) { - var key = keys[j]; - dst[key] = obj[key]; - } - } - } - 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(Object.create(parent), extra); @@ -460,18 +605,33 @@ noop.$inject = []; * 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. + * + * @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 @@ -522,6 +682,16 @@ function isObject(value) { } +/** + * 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 @@ -587,7 +757,27 @@ function isDate(value) { * @param {*} value Reference to check. * @returns {boolean} True if `value` is an `Array`. */ -var isArray = Array.isArray; +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 @@ -658,6 +848,16 @@ function isPromiseLike(obj) { } +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; }; @@ -666,8 +866,10 @@ var trim = function(value) { // 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) + if (index >= 0) { array.splice(index, 1); - return value; + } + return index; } /** @@ -723,156 +927,236 @@ function arrayRemove(array, value) { * @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 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. + * + *
+ * + *
+ * 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. + *
* - * @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`. + * @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, stackSource, stackDest) { - 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) { - destination = source; - if (source) { - if (isArray(source)) { - destination = copy(source, [], stackSource, stackDest); - } else if (isDate(source)) { - destination = new Date(source.getTime()); - } else if (isRegExp(source)) { - destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]); - destination.lastIndex = source.lastIndex; - } else if (isObject(source)) { - var emptyObject = Object.create(Object.getPrototypeOf(source)); - destination = copy(source, emptyObject, stackSource, stackDest); - } + 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]; + } + }); } - } else { - if (source === destination) throw ngMinErr('cpi', - "Can't copy! Source and destination are identical."); - stackSource = stackSource || []; - stackDest = stackDest || []; + stackSource.push(source); + stackDest.push(destination); + return copyRecurse(source, destination, maxDepth); + } - if (isObject(source)) { - var index = stackSource.indexOf(source); - if (index !== -1) return stackDest[index]; + return copyElement(source, maxDepth); - stackSource.push(source); - stackDest.push(destination); + function copyRecurse(source, destination, maxDepth) { + maxDepth--; + if (maxDepth < 0) { + return '...'; } - - var result; + var h = destination.$$hashKey; + var key; if (isArray(source)) { - destination.length = 0; - for (var i = 0; i < source.length; i++) { - result = copy(source[i], null, stackSource, stackDest); - if (isObject(source[i])) { - stackSource.push(source[i]); - stackDest.push(result); - } - destination.push(result); + for (var i = 0, ii = source.length; i < ii; i++) { + destination.push(copyElement(source[i], maxDepth)); } - } else { - var h = destination.$$hashKey; - if (isArray(destination)) { - destination.length = 0; - } else { - forEach(destination, function(value, key) { - delete destination[key]; - }); + } 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); } - for (var key in source) { + } else if (source && typeof source.hasOwnProperty === 'function') { + // Slow path, which must rely on hasOwnProperty + for (key in source) { if (source.hasOwnProperty(key)) { - result = copy(source[key], null, stackSource, stackDest); - if (isObject(source[key])) { - stackSource.push(source[key]); - stackDest.push(result); - } - destination[key] = result; + destination[key] = copyElement(source[key], maxDepth); + } + } + } else { + // 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; -} -/** - * 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 || []; + function copyElement(source, maxDepth) { + // Simple values + if (!isObject(source)) { + return source; + } - for (var i = 0, ii = src.length; i < ii; i++) { - dst[i] = src[i]; + // Already copied values + var index = stackSource.indexOf(source); + if (index !== -1) { + return stackDest[index]; } - } else if (isObject(src)) { - dst = dst || {}; - for (var key in src) { - if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) { - dst[key] = src[key]; - } + 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); + + 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 || src; + 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()); + + 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 @@ -901,83 +1185,184 @@ 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 < length; key++) { - if (!equals(o1[key], o2[key])) return false; - } - return true; - } - } else if (isDate(o1)) { - if (!isDate(o2)) return false; - return equals(o1.getTime(), o2.getTime()); - } else if (isRegExp(o1)) { - return isRegExp(o2) ? o1.toString() == o2.toString() : false; - } else { - if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || - isArray(o2) || isDate(o2) || isRegExp(o2)) return false; - keySet = {}; - for (key in o1) { - if (key.charAt(0) === '$' || isFunction(o1[key])) continue; + if (t1 === t2 && t1 === 'object') { + if (isArray(o1)) { + if (!isArray(o2)) return false; + if ((length = o1.length) === o2.length) { + for (key = 0; key < length; key++) { if (!equals(o1[key], o2[key])) return false; - keySet[key] = true; - } - for (key in o2) { - if (!keySet.hasOwnProperty(key) && - key.charAt(0) !== '$' && - o2[key] !== undefined && - !isFunction(o2[key])) return false; } return true; } + } else if (isDate(o1)) { + if (!isDate(o2)) return false; + return simpleCompare(o1.getTime(), o2.getTime()); + } else if (isRegExp(o1)) { + if (!isRegExp(o2)) return false; + return o1.toString() === o2.toString(); + } else { + if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || + isArray(o2) || isDate(o2) || isRegExp(o2)) return false; + keySet = createMap(); + for (key in o1) { + if (key.charAt(0) === '$' || isFunction(o1[key])) continue; + if (!equals(o1[key], o2[key])) return false; + keySet[key] = true; + } + for (key in o2) { + if (!(key in keySet) && + key.charAt(0) !== '$' && + isDefined(o2[key]) && + !isFunction(o2[key])) return false; + } + return true; } } return false; } var csp = function() { - if (isDefined(csp.isActive_)) return csp.isActive_; + if (!isDefined(csp.rules)) { + + + var ngCspElement = (window.document.querySelector('[ng-csp]') || + window.document.querySelector('[data-ng-csp]')); + + if (ngCspElement) { + var ngCspAttribute = ngCspElement.getAttribute('ng-csp') || + ngCspElement.getAttribute('data-ng-csp'); + csp.rules = { + noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1), + noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1) + }; + } else { + csp.rules = { + noUnsafeEval: noUnsafeEval(), + noInlineStyle: false + }; + } + } - var active = !!(document.querySelector('[ng-csp]') || - document.querySelector('[data-ng-csp]')); + return csp.rules; - if (!active) { + function noUnsafeEval() { try { - /* jshint -W031, -W054 */ + // eslint-disable-next-line no-new, no-new-func new Function(''); - /* jshint +W031, +W054 */ + return false; } catch (e) { - active = true; + return true; } } - - return (csp.isActive_ = active); }; - - -function concat(array1, array2, index) { - return array1.concat(slice.call(array2, index)); -} - -function sliceArgs(args, startIndex) { - return slice.call(args, startIndex || 0); -} - - -/* jshint -W101 */ /** - * @ngdoc function - * @name angular.bind + * @ngdoc directive + * @module ng + * @name ngJq + * + * @element ANY + * @param {string=} ngJq the name of the library available under `window` + * to be used for angular.element + * @description + * Use this directive to force the angular.element library. This should be + * used to force either jqLite by leaving ng-jq blank or setting the name of + * the jquery variable under window (eg. jQuery). + * + * Since AngularJS looks for this directive when it is loaded (doesn't wait for the + * DOMContentLoaded event), it must be placed on an element that comes before the script + * which loads angular. Also, only the first instance of `ng-jq` will be used and all + * others ignored. + * + * @example + * This example shows how to force jqLite using the `ngJq` directive to the `html` tag. + ```html + + + ... + ... + + ``` + * @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)); +} + +function sliceArgs(args, startIndex) { + return slice.call(args, startIndex || 0); +} + + +/** + * @ngdoc function + * @name angular.bind * @module ng * @kind function * @@ -992,7 +1377,6 @@ 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)) { @@ -1008,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; } } @@ -1021,7 +1405,7 @@ function toJsonReplacer(key, value) { 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'; @@ -1039,15 +1423,36 @@ function toJsonReplacer(key, value) { * * @description * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be - * stripped since angular uses this notation internally. + * stripped since AngularJS uses this notation internally. * - * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON. - * @param {boolean|number=} pretty 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 (the default is 2). + * @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; + if (isUndefined(obj)) return undefined; if (!isNumber(pretty)) { pretty = pretty ? 2 : null; } @@ -1074,22 +1479,42 @@ function fromJson(json) { } +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) {} - var elemHtml = jqLite('
').append(element).html(); + element = jqLite(element).clone().empty(); + var elemHtml = jqLite('
').append(element).html(); try { return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) : elemHtml. match(/^(<[^>]+>)/)[1]. - replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); }); + replace(/^<([\w-]+)/, function(match, nodeName) {return '<' + lowercase(nodeName);}); } catch (e) { return lowercase(elemHtml); } @@ -1111,7 +1536,7 @@ function tryDecodeURIComponent(value) { try { return decodeURIComponent(value); } catch (e) { - // Ignore any invalid uri component + // Ignore any invalid uri component. } } @@ -1121,13 +1546,19 @@ function tryDecodeURIComponent(value) { * @returns {Object.} */ function parseKeyValue(/**string*/keyValue) { - var obj = {}, key_value, key; - forEach((keyValue || "").split('&'), function(keyValue) { + var obj = {}; + forEach((keyValue || '').split('&'), function(keyValue) { + var splitPoint, key, val; if (keyValue) { - key_value = keyValue.replace(/\+/g,'%20').split('='); - key = tryDecodeURIComponent(key_value[0]); + 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)) { - var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true; + val = isDefined(val) ? tryDecodeURIComponent(val) : true; if (!hasOwnProperty.call(obj, key)) { obj[key] = val; } else if (isArray(obj[key])) { @@ -1181,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 @@ -1202,16 +1633,67 @@ var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-']; function getNgAttribute(element, ngAttr) { var attr, i, ii = ngAttrPrefixes.length; - element = jqLite(element); for (i = 0; i < ii; ++i) { attr = ngAttrPrefixes[i] + ngAttr; - if (isString(attr = element.attr(attr))) { + 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 * @name ngApp @@ -1232,10 +1714,17 @@ function getNgAttribute(element, ngAttr) { * 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. It @@ -1246,9 +1735,13 @@ function getNgAttribute(element, ngAttr) { * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` * would not be resolved to `3`. * + * @example + * + * ### Simple Usage + * * `ngApp` is the easiest, and most common way to bootstrap an application. * - +
I can add: {{a}} + {{b}} = {{ a+b }} @@ -1262,9 +1755,13 @@ function getNgAttribute(element, ngAttr) { * + * @example + * + * ### With `ngStrictDi` + * * Using `ngStrictDi`, you would see something like this: * - +
@@ -1313,7 +1810,7 @@ function getNgAttribute(element, ngAttr) { }]) .controller('GoodController2', GoodController2); function GoodController2($scope) { - $scope.name = "World"; + $scope.name = 'World'; } GoodController2.$inject = ['$scope']; @@ -1344,7 +1841,7 @@ function angularInit(element, bootstrap) { module, config = {}; - // The element `element` has priority over any other element + // The element `element` has priority over any other element. forEach(ngAttrPrefixes, function(prefix) { var name = prefix + 'app'; @@ -1363,7 +1860,12 @@ function angularInit(element, bootstrap) { } }); if (appElement) { - config.strictDi = getNgAttribute(appElement, "strict-di") !== null; + if (!isAutoBootstrapAllowed) { + window.console.error('AngularJS: disabling automatic bootstrap.
-
-
+
+
@@ -6367,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!'); }); @@ -6381,7 +8230,7 @@ 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 - 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. @@ -6396,7 +8245,7 @@ function $TemplateCacheProvider() { * * `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. @@ -6408,47 +8257,440 @@ function $TemplateCacheProvider() { * 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 controller instances; if given, it will make the controllers - * available to directives. + * 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. + * 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 @@ -6456,11 +8698,12 @@ var $compileMinErr = minErr('$compile'); * @description */ $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider']; +/** @this */ function $CompileProvider($provide, $$sanitizeUriProvider) { var hasDirectives = {}, Suffix = 'Directive', - COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/, - CLASS_DIRECTIVE_REGEXP = /(([\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 = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/; @@ -6468,20 +8711,29 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { // 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(); - function parseIsolateBindings(scope, directiveName) { - var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/; + function parseIsolateBindings(scope, directiveName, isController) { + var LOCAL_REGEXP = /^([@&]|[=<](\*?))(\??)\s*([\w$]*)$/; - var bindings = {}; + 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 isolate scope definition for directive '{0}'." + - " Definition: {... {1}: '{2}' ...}", - directiveName, scopeName, definition); + 'Invalid {3} for directive \'{0}\'.' + + ' Definition: {... {1}: \'{2}\' ...}', + directiveName, scopeName, definition, + (isController ? 'controller bindings definition' : + 'isolate scope definition')); } bindings[scopeName] = { @@ -6490,11 +8742,79 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { 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 @@ -6503,16 +8823,18 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { * @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. + * @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) { + 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] = []; @@ -6530,11 +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 || 'EA'; - if (isObject(directive.scope)) { - directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name); - } + directive.require = getDirectiveRequire(directive); + directive.restrict = getDirectiveRestrict(directive.restrict, name); + directive.$$moduleName = directiveFactory.$$moduleName; directives.push(directive); } catch (e) { $exceptionHandler(e); @@ -6550,66 +8870,255 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { return this; }; - /** * @ngdoc method - * @name $compileProvider#aHrefSanitizationWhitelist - * @kind function - * + * @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 - * Retrieves or overrides the default regular expression that is used for whitelisting of safe - * urls during a[href] sanitization. + * 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'`). * - * The sanitization is a security measure aimed at preventing XSS attacks via html links. + * 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. * - * 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` - * 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. + * 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. * - * @param {RegExp=} regexp New regexp to whitelist urls with. - * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for - * chaining otherwise. + * 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.aHrefSanitizationWhitelist = function(regexp) { - if (isDefined(regexp)) { - $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp); + this.component = function registerComponent(name, options) { + if (!isString(name)) { + forEach(name, reverseParams(bind(this, registerComponent))); return this; - } else { - return $$sanitizeUriProvider.aHrefSanitizationWhitelist(); } + + 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#imgSrcSanitizationWhitelist + * @name $compileProvider#aHrefSanitizationTrustedUrlList + * @kind function + * + * @description + * 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 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 `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 trust urls with. + * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for + * chaining otherwise. + */ + this.aHrefSanitizationTrustedUrlList = function(regexp) { + if (isDefined(regexp)) { + $$sanitizeUriProvider.aHrefSanitizationTrustedUrlList(regexp); + return this; + } else { + return $$sanitizeUriProvider.aHrefSanitizationTrustedUrlList(); + } + }; + + + /** + * @ngdoc method + * @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 @@ -6625,7 +9134,12 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { * 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. @@ -6641,13 +9155,303 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { 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', '$templateRequest', '$parse', - '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri', + '$controller', '$rootScope', '$sce', '$animate', function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse, - $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) { + $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++; + } + } + - var Attributes = function(element, attributesToCopy) { + 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; @@ -6661,7 +9465,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { } this.$$element = element; - }; + } Attributes.prototype = { /** @@ -6751,12 +9555,12 @@ 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 node = this.$$element[0], booleanKey = getBooleanAttrName(node, key), - aliasedKey = getAliasedAttrName(node, key), + aliasedKey = getAliasedAttrName(key), observer = key, nodeName; @@ -6782,63 +9586,43 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { nodeName = nodeName_(this.$$element); - if ((nodeName === 'a' && key === 'href') || - (nodeName === 'img' && key === 'src')) { - // sanitize a[href] and img[src] values - this[key] = value = $$sanitizeUri(value, key === 'src'); - } else if (nodeName === 'img' && key === 'srcset') { - // sanitize img[srcset] values - 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 += $$sanitizeUri(trim(rawUris[innerIdx]), true); - // 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 += $$sanitizeUri(trim(lastTuple[0]), true); - - // and add the last descriptor if any - if (lastTuple.length === 2) { - result += (" " + trim(lastTuple[1])); - } - this[key] = value = result; + // 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[observer], function(fn) { - try { - fn(value); - } catch (e) { - $exceptionHandler(e); - } - }); + if ($$observers) { + forEach($$observers[observer], function(fn) { + try { + fn(value); + } catch (e) { + $exceptionHandler(e); + } + }); + } }, @@ -6857,7 +9641,8 @@ 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#text-and-attribute-bindings Directives} guide for more info. + * 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) { @@ -6867,7 +9652,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { listeners.push(fn); $rootScope.$evalAsync(function() { - if (!listeners.$$inter && attrs.hasOwnProperty(key)) { + if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) { // no one registered attribute interpolation function, so lets call it manually fn(attrs[key]); } @@ -6879,6 +9664,18 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { } }; + 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 { @@ -6892,12 +9689,13 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { 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') || []; @@ -6924,6 +9722,15 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { 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; //================================ @@ -6935,21 +9742,25 @@ 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 == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) { - $compileNodes[index] = jqLite(node).wrap('').parent()[0]; - } - }); var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority, ignoreDirective, previousCompileContext); 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'); + if (previousCompileContext && previousCompileContext.needsNewScope) { + // A parent directive did a replace and a directive on this element asked + // for transclusion, which caused us to lose a layer of element on which + // we could hold the new transclusion scope, so we will create it manually + // here. + scope = scope.$parent.$new(); + } + options = options || {}; var parentBoundTranscludeFn = options.parentBoundTranscludeFn, transcludeControllers = options.transcludeControllers, @@ -6974,7 +9785,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { // for call to the link function. // Note: This will already clone the nodes... $linkNode = jqLite( - wrapTemplate(namespace, jqLite('
').append($compileNodes).html()) + wrapTemplate(namespace, jqLite('
').append($compileNodes).html()) ); } else if (cloneConnectFn) { // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart @@ -6994,6 +9805,10 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (cloneConnectFn) cloneConnectFn($linkNode, scope); if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn); + + if (!cloneConnectFn) { + $compileNodes = compositeLinkFn = null; + } return $linkNode; }; } @@ -7004,7 +9819,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (!node) { return 'html'; } else { - return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html'; + return nodeName_(node) !== 'foreignobject' && toString.call(node).match(/SVG/) ? 'svg' : 'html'; } } @@ -7026,12 +9841,23 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, previousCompileContext) { var linkFns = [], + // `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); @@ -7078,7 +9904,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { 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) { + for (i = 0; i < linkFns.length; i += 3) { idx = linkFns[i]; stableNodeList[idx] = nodeList[idx]; } @@ -7101,8 +9927,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (nodeLinkFn.transcludeOnThisElement) { childBoundTranscludeFn = createBoundTranscludeFn( - scope, nodeLinkFn.transclude, parentBoundTranscludeFn, - nodeLinkFn.elementTranscludeOnThisElement); + scope, nodeLinkFn.transclude, parentBoundTranscludeFn); } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) { childBoundTranscludeFn = parentBoundTranscludeFn; @@ -7123,9 +9948,34 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { } } - function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) { + 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); + } + } + } - var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) { + function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) { + function boundTranscludeFn(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) { if (!transcludedScope) { transcludedScope = scope.$new(false, containingScope); @@ -7137,7 +9987,18 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { 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 boundTranscludeFn; } @@ -7156,63 +10017,96 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { var nodeType = node.nodeType, attrsMap = attrs.$attr, match, + nodeName, className; switch (nodeType) { case NODE_TYPE_ELEMENT: /* Element */ + + nodeName = nodeName_(node); + // use the node name: addDirective(directives, - directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective); + directiveNormalize(nodeName), 'E', maxPriority, ignoreDirective); // iterate over the attributes - for (var attr, name, nName, ngAttrName, value, isNgAttr, 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]; name = attr.name; - value = trim(attr.value); + 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'; - // support ngAttr attribute binding - ngAttrName = directiveNormalize(name); - if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) { + // Normalize the non-prefixed name name = name.replace(PREFIX_REGEXP, '') - .substr(8).replace(/_(.)/g, function(match, letter) { + .toLowerCase() + .substr(4 + ngPrefixMatch[1].length).replace(/_(.)/g, function(match, letter) { return letter.toUpperCase(); }); + + // 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); } - var directiveNName = ngAttrName.replace(/(Start|End)$/, ''); - if (directiveIsMultiElement(directiveNName)) { - if (ngAttrName === directiveNName + 'Start') { - 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; - nName = directiveNormalize(name.toLowerCase()); - attrsMap[nName] = name; - if (isNgAttr || !attrs.hasOwnProperty(nName)) { + if (isNgAttr || !attrs.hasOwnProperty(nName)) { attrs[nName] = value; if (getBooleanAttrName(node, nName)) { attrs[nName] = true; // presence means true } + } + + addAttrInterpolateDirective(node, directives, value, nName, isNgAttr); + addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName, + attrEndName); } - 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]); @@ -7225,19 +10119,8 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { addTextInterpolateDirective(directives, node.nodeValue); break; case NODE_TYPE_COMMENT: /* 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.) - } + if (!commentDirectivesEnabled) break; + collectCommentDirectives(node, directives, attrs, maxPriority, ignoreDirective); break; } @@ -7245,10 +10128,28 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { return directives; } - /** - * Given a node with an directive-start it collects all of the siblings until it finds - * directive-end. - * @param node + 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 a directive-start it collects all of the siblings until it finds + * directive-end. + * @param node * @param attrStart * @param attrEnd * @returns {*} @@ -7260,10 +10161,10 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { 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 == NODE_TYPE_ELEMENT) { + if (node.nodeType === NODE_TYPE_ELEMENT) { if (node.hasAttribute(attrStart)) depth++; if (node.hasAttribute(attrEnd)) depth--; } @@ -7286,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 @@ -7321,9 +10251,8 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { previousCompileContext = previousCompileContext || {}; var terminalPriority = -Number.MAX_VALUE, - newScopeDirective, + newScopeDirective = previousCompileContext.newScopeDirective, controllerDirectives = previousCompileContext.controllerDirectives, - controllers, newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective, templateDirective = previousCompileContext.templateDirective, nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective, @@ -7337,6 +10266,8 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { replaceDirective = originalReplaceDirective, childTranscludeFn = transcludeFn, linkFn, + didScanForMultipleTransclusion = false, + mightHaveMultipleTransclusionError = false, directiveValue; // executes all directives on the current element @@ -7355,7 +10286,9 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { break; // prevent further processing of directives } - if (directiveValue = directive.scope) { + directiveValue = directive.scope; + + if (directiveValue) { // skip the check for directives with async templates, we'll check the derived sync // directive when the template arrives @@ -7379,15 +10312,37 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { 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. @@ -7398,17 +10353,16 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { nonTlbTranscludeDirective = directive; } - if (directiveValue == 'element') { + if (directiveValue === 'element') { hasElementTranscludeDirective = true; terminalPriority = directive.priority; $template = $compileNode; $compileNode = templateAttrs.$$element = - jqLite(document.createComment(' ' + directiveName + ': ' + - templateAttrs[directiveName] + ' ')); + jqLite(compile.$$createComment(directiveName, templateAttrs[directiveName])); compileNode = $compileNode[0]; 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 @@ -7420,9 +10374,72 @@ 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; } } @@ -7446,9 +10463,9 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { } compileNode = $template[0]; - if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { + 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, ''); } @@ -7464,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); @@ -7485,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, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, { controllerDirectives: controllerDirectives, + newScopeDirective: (newScopeDirective !== directive) && newScopeDirective, newIsolateScopeDirective: newIsolateScopeDirective, templateDirective: templateDirective, nonTlbTranscludeDirective: nonTlbTranscludeDirective @@ -7496,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)); @@ -7515,7 +10538,6 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true; nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective; - nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective; nodeLinkFn.templateOnThisElement = hasTemplate; nodeLinkFn.transclude = childTranscludeFn; @@ -7547,57 +10569,9 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { } } - - function getControllers(directiveName, require, $element, elementControllers) { - var value, retrievalMethod = 'data', optional = false; - var $searchElement = $element; - var match; - if (isString(require)) { - match = require.match(REQUIRE_PREFIX_REGEXP); - require = require.substring(match[0].length); - - if (match[3]) { - if (match[1]) match[3] = null; - else match[1] = match[3]; - } - if (match[1] === '^') { - retrievalMethod = 'inheritedData'; - } else if (match[1] === '^^') { - retrievalMethod = 'inheritedData'; - $searchElement = $element.parent(); - } - if (match[2] === '?') { - optional = true; - } - - value = null; - - if (elementControllers && retrievalMethod === 'data') { - if (value = elementControllers[require]) { - value = value.instance; - } - } - value = value || $searchElement[retrievalMethod]('$' + require + 'Controller'); - - if (!value && !optional) { - throw $compileMinErr('ctreq', - "Controller '{0}', required by directive '{1}', can't be found!", - require, directiveName); - } - return value || null; - } else if (isArray(require)) { - value = []; - forEach(require, function(require) { - value.push(getControllers(directiveName, require, $element, elementControllers)); - }); - } - return value; - } - - function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) { - var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element, - attrs; + var i, ii, linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element, + attrs, scopeBindingInfo; if (compileNode === linkNode) { attrs = templateAttrs; @@ -7607,8 +10581,11 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { attrs = new Attributes($element, templateAttrs); } + controllerScope = scope; if (newIsolateScopeDirective) { isolateScope = scope.$new(true); + } else if (newScopeDirective) { + controllerScope = scope.$parent; } if (boundTranscludeFn) { @@ -7616,130 +10593,78 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { // 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]; + }; } if (controllerDirectives) { - // TODO: merge `controllers` and `elementControllers` into single object. - controllers = {}; - elementControllers = {}; - 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]; - } - - controllerInstance = $controller(controller, locals, true, directive.controllerAs); - - // 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.instance); - } - - controllers[directive.name] = controllerInstance; - }); + elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope, newIsolateScopeDirective); } 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); - - var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name]; - var isolateBindingContext = isolateScope; - if (isolateScopeController && isolateScopeController.identifier && - newIsolateScopeDirective.bindToController === true) { - isolateBindingContext = isolateScopeController.instance; + isolateScope.$$isolateBindings = + newIsolateScopeDirective.$$isolateBindings; + scopeBindingInfo = initializeDirectiveBindings(scope, attrs, isolateScope, + isolateScope.$$isolateBindings, + newIsolateScopeDirective); + if (scopeBindingInfo.removeWatches) { + isolateScope.$on('$destroy', scopeBindingInfo.removeWatches); } + } - forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) { - var attrName = definition.attrName, - optional = definition.optional, - mode = definition.mode, // @, =, or & - lastValue, - parentGet, parentSet, compare; - - switch (mode) { + // Initialize bindToController bindings + for (var name in elementControllers) { + var controllerDirective = controllerDirectives[name]; + var controller = elementControllers[name]; + var bindings = controllerDirective.$$bindings.bindToController; - case '@': - attrs.$observe(attrName, function(value) { - isolateBindingContext[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 - isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope); - } - break; + controller.instance = controller(); + $element.data('$' + controllerDirective.name + 'Controller', controller.instance); + controller.bindingInfo = + initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective); + } - case '=': - if (optional && !attrs[attrName]) { - return; - } - parentGet = $parse(attrs[attrName]); - if (parentGet.literal) { - compare = equals; - } else { - compare = function(a, b) { return a === b || (a !== a && b !== b); }; - } - parentSet = parentGet.assign || function() { - // reset the change, or we will throw this exception on every $digest - lastValue = isolateBindingContext[scopeName] = parentGet(scope); - throw $compileMinErr('nonassign', - "Expression '{0}' used with directive '{1}' is non-assignable!", - attrs[attrName], newIsolateScopeDirective.name); - }; - lastValue = isolateBindingContext[scopeName] = parentGet(scope); - var parentValueWatch = function parentValueWatch(parentValue) { - if (!compare(parentValue, isolateBindingContext[scopeName])) { - // we are out of sync and need to copy - if (!compare(parentValue, lastValue)) { - // parent changed and it has precedence - isolateBindingContext[scopeName] = parentValue; - } else { - // if the parent can be assigned then do so - parentSet(scope, parentValue = isolateBindingContext[scopeName]); - } - } - return lastValue = parentValue; - }; - parentValueWatch.$stateful = true; - var unwatch; - if (definition.collection) { - unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch); - } else { - unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal); - } - isolateScope.$on('$destroy', unwatch); - break; + // 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)); + } + }); - case '&': - parentGet = $parse(attrs[attrName]); - isolateBindingContext[scopeName] = function(locals) { - return parentGet(scope, locals); - }; - break; + // 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 (controllers) { - forEach(controllers, function(controller) { - controller(); - }); - controllers = null; - } + } + 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++) { @@ -7760,7 +10685,9 @@ 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--) { @@ -7774,13 +10701,21 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { ); } + // 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`. // Note: all arguments are optional! - function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) { + function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement, slotName) { var transcludeControllers; - // No scope passed in: if (!isScope(scope)) { + slotName = futureParentElement; futureParentElement = cloneAttachFn; cloneAttachFn = scope; scope = undefined; @@ -7792,15 +10727,115 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (!futureParentElement) { futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element; } - return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild); + 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 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; } - function markDirectivesAsIsolate(directives) { - // mark all directives as needing isolate scope. + // 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}); } } @@ -7825,17 +10860,22 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if (hasDirectives.hasOwnProperty(name)) { for (var directive, directives = $injector.get(name + Suffix), i = 0, ii = directives.length; i < ii; i++) { - try { - directive = directives[i]; - if ((maxPriority === undefined || maxPriority > directive.priority) && - directive.restrict.indexOf(location) != -1) { - if (startAttrName) { - directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName}); + 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; @@ -7873,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 (key.charAt(0) !== '$') { if (src[key] && src[key] !== value) { - value += (key === 'style' ? ';' : ' ') + src[key]; + if (value.length) { + value += (key === 'style' ? ';' : ' ') + src[key]; + } else { + value = src[key]; + } } dst.$set(key, value, true, srcAttr[key]); } @@ -7888,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]; + } } }); } @@ -7922,7 +10963,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { $compileNode.empty(); - $templateRequest($sce.getTrustedResourceUrl(templateUrl)) + $templateRequest(templateUrl) .then(function(content) { var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn; @@ -7936,9 +10977,9 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { } compileNode = $template[0]; - if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) { + 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); } @@ -7947,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); @@ -7962,7 +11005,7 @@ 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]; } }); @@ -7999,6 +11042,10 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { childBoundTranscludeFn); } linkQueue = null; + }).catch(function(error) { + if (isError(error)) { + $exceptionHandler(error); + } }); return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) { @@ -8029,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)); } } @@ -8070,7 +11124,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { switch (type) { case 'svg': case 'math': - var wrapper = document.createElement('div'); + var wrapper = window.document.createElement('div'); wrapper.innerHTML = '<' + type + '>' + template + ''; return wrapper.childNodes[0].childNodes; default: @@ -8079,49 +11133,119 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { } - function getTrustedContext(node, attrNormalizedName) { - if (attrNormalizedName == "srcdoc") { + 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 addAttrInterpolateDirective(node, directives, value, name, allOrNothing) { - var trustedContext = getTrustedContext(node, name); - allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing; + function addEventDirective(directives, attrName, eventName) { + directives.push( + createEventDirective($parse, $rootScope, $exceptionHandler, attrName, eventName, /*forceAsync=*/false) + ); + } - var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing); + 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; + + 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]; @@ -8151,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); @@ -8182,7 +11306,7 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { if ($rootElement) { for (i = 0, ii = $rootElement.length; i < ii; i++) { - if ($rootElement[i] == firstElementToRemove) { + if ($rootElement[i] === firstElementToRemove) { $rootElement[i++] = newNode; for (var j = i, j2 = j + removeCount - 1, jj = $rootElement.length; @@ -8210,39 +11334,33 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { parent.replaceChild(newNode, firstElementToRemove); } - // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it? - var fragment = document.createDocumentFragment(); - fragment.appendChild(firstElementToRemove); + // 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]); + } - // Copy over user data (that includes Angular'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(newNode).data(jqLite(firstElementToRemove).data()); + 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 data of the replaced element. We cannot just call .remove() - // on the element it since that would deallocate scope that is needed - // for the new node. Instead, remove the data "manually". - if (!jQuery) { - delete jqLite.cache[firstElementToRemove[jqLite.expando]]; - } else { - // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after - // the replaced element. The cleanData version monkey-patched by Angular would cause - // the scope to be trashed and we do need the very same scope to work with the new - // element. However, we cannot just cache the non-patched version and use it here as - // that would break if another library patches the method after Angular does (one - // example is jQuery UI). Instead, set a flag indicating scope destroying should be - // skipped this one time. - skipDestroyOnNextJQueryCleanData = true; - jQuery.cleanData([firstElementToRemove]); + // Remove $destroy event listeners from `firstElementToRemove` + jqLite(firstElementToRemove).off('$destroy'); } - 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]; - } + // 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; } @@ -8260,64 +11378,255 @@ function $CompileProvider($provide, $$sanitizeUriProvider) { $exceptionHandler(e, startingTag($element)); } } - }]; -} -var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i; -/** - * Converts all accepted directives format into proper directive name. - * @param name Name to normalize - */ -function directiveNormalize(name) { - return camelCase(name.replace(PREFIX_REGEXP, '')); -} + function strictBindingsCheck(attrName, directiveName) { + if (strictComponentBindingsEnabled) { + throw $compileMinErr('missingattr', + 'Attribute \'{0}\' of \'{1}\' is non-optional and must be set!', + attrName, directiveName); + } + } -/** - * @ngdoc type - * @name $compile.directive.Attributes - * - * @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: - * - * ``` - * - * ``` - */ + // Set up $watches for isolate scope and controller bindings. + function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) { + var removeWatchCollection = []; + var initialChanges = {}; + var changes; -/** - * @ngdoc property - * @name $compile.directive.Attributes#$attr - * - * @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. - */ + forEach(bindings, function initializeBinding(definition, scopeName) { + var attrName = definition.attrName, + optional = definition.optional, + mode = definition.mode, // @, =, <, or & + lastValue, + parentGet, parentSet, compare, removeWatch; + switch (mode) { -/** - * @ngdoc method - * @name $compile.directive.Attributes#$set - * @kind function - * - * @description - * Set DOM element attribute value. - * - * - * @param {string} name Normalized element attribute name of the property to modify. The name is - * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} - * property to the original name. - * @param {string} value Value to set the attribute to. The value can be an interpolated string. - */ + 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; -/** - * Closure compiler type information - */ + 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; -function nodesetLinkingFn( + 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](); + } + } + }; + } + }]; +} + +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. + * @param name Name to normalize + */ +function directiveNormalize(name) { + return name + .replace(PREFIX_REGEXP, '') + .replace(SPECIAL_CHARS_REGEXP, function(_, letter, offset) { + return offset ? letter.toUpperCase() : letter; + }); +} + +/** + * @ngdoc type + * @name $compile.directive.Attributes + * + * @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 AngularJS: + * + * ``` + * + * ``` + */ + +/** + * @ngdoc property + * @name $compile.directive.Attributes#$attr + * + * @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 + * @kind function + * + * @description + * Set DOM element attribute value. + * + * + * @param {string} name Normalized element attribute name of the property to modify. The name is + * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr} + * property to the original name. + * @param {string} value Value to set the attribute to. The value can be an interpolated string. + */ + + + +/** + * Closure compiler type information + */ + +function nodesetLinkingFn( /* angular.Scope */ scope, /* NodeList */ nodeList, /* Element */ rootElement, @@ -8341,7 +11650,7 @@ function tokenDifference(str1, str2) { 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; + if (token === tokens2[j]) continue outer; } values += (values.length > 0 ? ' ' : '') + token; } @@ -8358,8 +11667,9 @@ function removeComments(jqNodes) { while (i--) { var node = jqNodes[i]; - if (node.nodeType === NODE_TYPE_COMMENT) { - splice.call(jqNodes, i, 1); + if (node.nodeType === NODE_TYPE_COMMENT || + (node.nodeType === NODE_TYPE_TEXT && node.nodeValue.trim() === '')) { + splice.call(jqNodes, i, 1); } } return jqNodes; @@ -8367,21 +11677,40 @@ function removeComments(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 = {}, - globals = false, - 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 @@ -8400,17 +11729,7 @@ function $ControllerProvider() { } }; - /** - * @ngdoc method - * @name $controllerProvider#allowGlobals - * @description If called, allows `$controller` to find controller constructors on `window` - */ - this.allowGlobals = function() { - globals = true; - }; - - - this.$get = ['$injector', '$window', function($injector, $window) { + this.$get = ['$injector', function($injector) { /** * @ngdoc service @@ -8423,8 +11742,6 @@ 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 - * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global - * `window` object (not recommended) * * 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 @@ -8439,7 +11756,7 @@ 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, later, ident) { + 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 @@ -8457,15 +11774,19 @@ function $ControllerProvider() { match = expression.match(CNTRL_REG); if (!match) { throw $controllerMinErr('ctrlfmt', - "Badly formed controller string '{0}'. " + - "Must match `__name__ as __id__` or `__name__`.", expression); + 'Badly formed controller string \'{0}\'. ' + + 'Must match `__name__ as __id__` or `__name__`.', expression); } - constructor = match[1], + constructor = match[1]; identifier = identifier || match[3]; expression = controllers.hasOwnProperty(constructor) ? controllers[constructor] - : getter(locals.$scope, constructor, true) || - (globals ? getter($window, constructor, true) : undefined); + : getter(locals.$scope, constructor, true); + + if (!expression) { + throw $controllerMinErr('ctrlreg', + 'The controller with the name \'{0}\' is not registered.', constructor); + } assertArgFn(expression, constructor, true); } @@ -8489,8 +11810,15 @@ function $ControllerProvider() { addIdentifier(locals, identifier, instance, constructor || expression.name); } - return extend(function() { - $injector.invoke(expression, instance, locals, constructor); + 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, @@ -8510,7 +11838,7 @@ function $ControllerProvider() { 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`.", + 'Cannot export controller \'{0}\' as \'{1}\'! No $scope object provided via `locals`.', name, identifier); } @@ -8523,12 +11851,13 @@ 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:

@@ -8550,13 +11879,41 @@ function $DocumentProvider() { }]; } + +/** + * @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. * @@ -8565,18 +11922,21 @@ 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} @@ -8586,7 +11946,7 @@ function $DocumentProvider() { * `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. * */ @@ -8598,6 +11958,29 @@ function $ExceptionHandlerProvider() { }]; } +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 { + 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 = /^\[|^\{(?!\{)/; @@ -8605,7 +11988,131 @@ var JSON_ENDS = { '[': /]$/, '{': /}$/ }; -var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/; +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)) { @@ -8614,8 +12121,18 @@ function defaultHttpResponseTransform(data, headers) { if (tempData) { var contentType = headers('Content-Type'); - if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) { - data = fromJson(tempData); + 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); + } } } } @@ -8635,19 +12152,24 @@ function isJsonLike(str) { * @returns {Object} Parsed headers as key value object */ function parseHeaders(headers) { - var parsed = createMap(), 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)); + 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; } @@ -8662,18 +12184,18 @@ 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) { var value = headersObj[lowercase(name)]; - if (value === void 0) { + if (value === undefined) { value = null; } return value; @@ -8696,8 +12218,9 @@ function headersGetter(headers) { * @returns {*} Transformed data. */ function transformData(data, headers, status, fns) { - if (isFunction(fns)) + if (isFunction(fns)) { return fns(data, headers, status); + } forEach(fns, function(fn) { data = fn(data, headers, status); @@ -8715,9 +12238,11 @@ 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() { /** * @ngdoc property @@ -8726,16 +12251,9 @@ function $HttpProvider() { * * Object containing default values for all {@link ng.$http $http} requests. * - * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`} - * that will provide the cache for all requests who set their `cache` property to `true`. - * If you set the `default.cache = false` then only requests that specify their own custom - * cache object will be cached. See {@link $http#caching $http Caching} for more information. - * - * - **`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'`. + * - **`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 @@ -8745,7 +12263,40 @@ function $HttpProvider() { * - **`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: [defaultHttpResponseTransform], @@ -8766,7 +12317,11 @@ function $HttpProvider() { }, xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN' + xsrfHeaderName: 'X-XSRF-TOKEN', + + paramSerializer: '$httpParamSerializer', + + jsonpCallbackParam: 'callback' }; var useApplyAsync = false; @@ -8780,7 +12335,7 @@ function $HttpProvider() { * significant performance improvement for bigger applications that make many HTTP requests * concurrently (common during application bootstrap). * - * Defaults to false. If no value is specifed, returns the current configured value. + * 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 @@ -8788,7 +12343,7 @@ function $HttpProvider() { * * @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; @@ -8809,13 +12364,81 @@ function $HttpProvider() { * array, on request, but reverse order, on response. * * {@link ng.$http#interceptors Interceptors detailed info} - **/ + */ var interceptorFactories = this.interceptors = []; - this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector', - function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) { - - var defaultCache = $cacheFactory('$http'); + /** + * @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. + */ + Object.defineProperty(this, 'xsrfWhitelistedOrigins', { + get: function() { + return this.xsrfTrustedOrigins; + }, + set: function(origins) { + this.xsrfTrustedOrigins = origins; + } + }); + + 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. @@ -8829,6 +12452,11 @@ function $HttpProvider() { ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory)); }); + /** + * A function to check request URLs against a list of allowed origins. + */ + var urlIsAllowedOrigin = urlIsAllowedOriginFactory(xsrfTrustedOrigins); + /** * @ngdoc service * @kind function @@ -8840,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). * @@ -8856,66 +12484,35 @@ function $HttpProvider() { * * * ## 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`. - * - * ```js - * // Simple GET request example : - * $http.get('/someUrl'). - * success(function(data, status, headers, config) { - * // this callback will be called asynchronously - * // when the response is available - * }). - * error(function(data, status, headers, config) { - * // called asynchronously if an error occurs - * // or server returns response with an error status. - * }); - * ``` + * 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 - * // Simple POST request example (passing data) : - * $http.post('/someUrl', {msg:'hello word!'}). - * 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 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: @@ -8929,6 +12526,17 @@ function $HttpProvider() { * - {@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 * * The $http service will automatically add certain HTTP headers to all requests. These defaults @@ -8936,7 +12544,7 @@ function $HttpProvider() { * 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) @@ -8945,14 +12553,14 @@ 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'; * }); * ``` * @@ -8969,10 +12577,10 @@ function $HttpProvider() { * headers: { * 'Content-Type': undefined * }, - * data: { test: 'test' }, + * data: { test: 'test' } * } * - * $http(req).success(function(){...}).error(function(){...}); + * $http(req).then(function(){...}, function(){...}); * ``` * * ## Transforming Requests and Responses @@ -8982,6 +12590,15 @@ function $HttpProvider() { * 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 @@ -8991,22 +12608,25 @@ function $HttpProvider() { * You can augment or replace the default transformations by modifying these properties by adding to or * replacing the array. * - * Angular provides the following default transformations: + * AngularJS provides the following default transformations: * - * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`): + * 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 (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`): + * 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. + * - 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 override the request/response transformations only for a single request then provide + * 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`. * @@ -9039,26 +12659,35 @@ function $HttpProvider() { * * ## 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. + * + * 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 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. + * + * 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. * - * Note that even if the response is served from cache, delivery of the data is asynchronous in - * the same way that real requests are. + * 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. * - * 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. + * Take note that: * - * You can change the default cache to a new object (built with - * {@link ng.$cacheFactory `$cacheFactory`}) by updating the - * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set - * their `cache` property to `true` will now use this cache object. + * * 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. * - * If you set the default cache to `false` then only requests that specify their own custom - * cache object will be cached. * * ## Interceptors * @@ -9078,7 +12707,7 @@ function $HttpProvider() { * * There are two kinds of interceptors (and two kinds of rejection interceptors): * - * * `request`: interceptors get called with a http `config` object. The function is free to + * * `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 @@ -9152,7 +12781,7 @@ function $HttpProvider() { * - [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. * @@ -9162,7 +12791,7 @@ function $HttpProvider() { * 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 @@ -9175,45 +12804,70 @@ 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 * - * [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)) * 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** – @@ -9228,55 +12882,80 @@ function $HttpProvider() { * 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} - * - **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. + * - **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. + * + * 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}}
@@ -9285,6 +12964,13 @@ function $HttpProvider() { 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'; @@ -9295,13 +12981,12 @@ function $HttpProvider() { $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; + then(function(response) { + $scope.status = response.status; + $scope.data = response.data; + }, function(response) { + $scope.data = response.data || 'Request failed'; + $scope.status = response.status; }); }; @@ -9319,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() { @@ -9331,6 +13015,7 @@ function $HttpProvider() { // 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'); @@ -9349,95 +13034,74 @@ function $HttpProvider() { */ function $http(requestConfig) { - if (!angular.isObject(requestConfig)) { + 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 config = extend({ method: 'get', transformRequest: defaults.transformRequest, - transformResponse: defaults.transformResponse + transformResponse: defaults.transformResponse, + paramSerializer: defaults.paramSerializer, + jsonpCallbackParam: defaults.jsonpCallbackParam }, requestConfig); config.headers = mergeHeaders(requestConfig); config.method = uppercase(config.method); + config.paramSerializer = isString(config.paramSerializer) ? + $injector.get(config.paramSerializer) : config.paramSerializer; - var serverRequest = function(config) { - var headers = config.headers; - var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest); - - // 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); - }; + $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); - } - - promise.success = function(fn) { - promise.then(function(response) { - fn(response.data, response.status, response.headers, config); - }); - return promise; - }; + return promise; - promise.error = function(fn) { - promise.then(null, function(response) { - fn(response.data, response.status, response.headers, config); - }); - return promise; - }; - return promise; + function chainInterceptors(promise, interceptors) { + for (var i = 0, ii = interceptors.length; i < ii;) { + var thenFn = interceptors[i++]; + var rejectFn = interceptors[i++]; - function transformResponse(response) { - // make a copy since the response must be cacheable - var resp = extend({}, response); - if (!response.data) { - resp.data = response.data; - } else { - resp.data = transformData(response.data, response.headers, response.status, config.transformResponse); + promise = promise.then(thenFn, rejectFn); } - return (isSuccess(response.status)) - ? resp - : $q.reject(resp); + + interceptors.length = 0; + + return promise; } - function executeHeaderFns(headers) { + function completeOutstandingRequest() { + $browser.$$completeOutstandingRequest(noop, '$http'); + } + + function executeHeaderFns(headers, config) { var headerContent, processedHeaders = {}; forEach(headers, function(headerFn, header) { if (isFunction(headerFn)) { - headerContent = headerFn(); + headerContent = headerFn(config); if (headerContent != null) { processedHeaders[header] = headerContent; } @@ -9456,7 +13120,7 @@ function $HttpProvider() { defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); - // 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); @@ -9471,7 +13135,38 @@ function $HttpProvider() { } // execute if header value is a function for merged headers - return executeHeaderFns(reqHeaders); + return executeHeaderFns(reqHeaders, shallowCopy(config)); + } + + function serverRequest(config) { + var headers = config.headers; + var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest); + + // 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); } } @@ -9484,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}. */ /** @@ -9496,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}. */ /** @@ -9508,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}. */ /** @@ -9520,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. - * The name of the callback should be the string `JSON_CALLBACK`. - * @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'); @@ -9536,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}. */ /** @@ -9549,8 +13281,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}. */ /** @@ -9562,8 +13295,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}. */ createShortMethodsWithData('post', 'put', 'patch'); @@ -9586,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 })); @@ -9598,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 @@ -9620,16 +13354,33 @@ function $HttpProvider() { cache, cachedResp, reqHeaders = config.headers, - url = buildUrl(config.url, config.params); + 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' || config.method === 'JSONP')) { cache = isObject(config.cache) ? config.cache - : isObject(defaults.cache) ? defaults.cache + : isObject(/** @type {?} */ (defaults).cache) + ? /** @type {?} */ (defaults).cache : defaultCache; } @@ -9642,9 +13393,9 @@ function $HttpProvider() { } else { // serving from cache if (isArray(cachedResp)) { - resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(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 { @@ -9657,19 +13408,43 @@ function $HttpProvider() { // 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 = urlIsSameOrigin(config.url) - ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName] + 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(): @@ -9677,10 +13452,10 @@ 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); @@ -9688,7 +13463,7 @@ function $HttpProvider() { } function resolveHttpPromise() { - resolvePromise(response, status, headersString, statusText); + resolvePromise(response, status, headersString, statusText, xhrStatus); } if (useApplyAsync) { @@ -9703,21 +13478,22 @@ function $HttpProvider() { /** * 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); + resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText, result.xhrStatus); } function removePendingReq() { @@ -9727,42 +13503,76 @@ function $HttpProvider() { } - 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)) { - if (isDate(v)) { - v = v.toISOString(); - } else { - v = toJson(v); - } - } - parts.push(encodeUriQuery(key) + '=' + - encodeUriQuery(v)); - }); - }); - if (parts.length > 0) { - url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&'); + 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() { - return new 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(); + }; + }; } /** * @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 @@ -9775,32 +13585,28 @@ function createXhr() { * $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) { // TODO(vojta): fix the signature - return function(method, url, post, callback, headers, timeout, withCredentials, responseType) { - $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; - callbacks[callbackId].called = true; - }; - - var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId), - callbackId, function(status, text) { - completeRequest(callback, status, callbacks[callbackId].data, "", text); - callbacks[callbackId] = 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(); + var xhr = createXhr(method, url); + var abortedByTimeout = false; xhr.open(method, url, true); forEach(headers, function(value, key) { @@ -9812,7 +13618,7 @@ function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDoc xhr.onload = function requestLoaded() { var statusText = xhr.statusText || ''; - // responseText is the old-school way of retrieving response (supported by IE8 & 9) + // 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; @@ -9823,24 +13629,44 @@ function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDoc // 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; + status = response ? 200 : urlResolve(url).protocol === 'file' ? 404 : 0; } completeRequest(callback, status, response, xhr.getAllResponseHeaders(), - statusText); + 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, ''); + 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.onabort = 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; @@ -9863,56 +13689,72 @@ 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); + var timeoutId = $browserDefer(function() { + timeoutRequest('timeout'); + }, timeout); } else if (isPromiseLike(timeout)) { - timeout.then(timeoutRequest); + timeout.then(function() { + timeoutRequest(isDefined(timeout.$$timeoutId) ? 'timeout' : 'abort'); + }); } - - function timeoutRequest() { - 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 - if (timeoutId !== undefined) { + if (isDefined(timeoutId)) { $browserDefer.cancel(timeoutId); } jsonpDone = xhr = null; - callback(status, response, headersString, statusText); - $browser.$$completeOutstandingRequest(noop); + callback(status, response, headersString, statusText, xhrStatus); } }; - function jsonpReq(url, callbackId, 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'), callback = null; - script.type = "text/javascript"; + script.type = 'text/javascript'; script.src = url; script.async = true; callback = function(event) { - removeEventListenerFn(script, "load", callback); - removeEventListenerFn(script, "error", callback); + script.removeEventListener('load', callback); + script.removeEventListener('error', callback); rawDocument.body.removeChild(script); script = null; var status = -1; - var text = "unknown"; + var text = 'unknown'; if (event) { - if (event.type === "load" && !callbacks[callbackId].called) { - event = { type: "error" }; + if (event.type === 'load' && !callbacks.wasCalled(callbackPath)) { + event = { type: 'error' }; } text = event.type; - status = event.type === "error" ? 404 : 200; + status = event.type === 'error' ? 404 : 200; } if (done) { @@ -9920,25 +13762,44 @@ function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDoc } }; - addEventListenerFn(script, "load", callback); - addEventListenerFn(script, "error", callback); + script.addEventListener('load', callback); + script.addEventListener('error', callback); rawDocument.body.appendChild(script); 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 + * @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//
@@ -9981,9 +13842,8 @@ function $InterpolateProvider() { if (value) { startSymbol = value; return this; - } else { - return startSymbol; } + return startSymbol; }; /** @@ -9999,9 +13859,8 @@ function $InterpolateProvider() { if (value) { endSymbol = value; return this; - } else { - return endSymbol; } + return endSymbol; }; @@ -10015,6 +13874,20 @@ function $InterpolateProvider() { 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 @@ -10034,7 +13907,7 @@ 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 @@ -10052,13 +13925,13 @@ function $InterpolateProvider() { * // "allOrNothing" mode * exp = $interpolate('{{greeting}} {{name}}!', false, null, true); * expect(exp(context)).toBeUndefined(); - * context.name = 'Angular'; - * expect(exp(context)).toEqual('Hello Angular!'); + * context.name = 'AngularJS'; + * expect(exp(context)).toEqual('Hello AngularJS!'); * ``` * * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior. * - * ####Escaped Interpolation + * #### 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 @@ -10079,7 +13952,7 @@ function $InterpolateProvider() { * 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"; \}\} @@ -10094,6 +13967,30 @@ function $InterpolateProvider() { * * * + * @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 * embedded expression in order to return an interpolation function. Strings with no @@ -10110,29 +14007,48 @@ function $InterpolateProvider() { * - `context`: evaluation context for all expressions embedded in the interpolated text */ 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, expressions = [], - parseFns = [], + parseFns, textLength = text.length, exp, concat = [], - expressionPositions = []; + expressionPositions = [], + singleExpression; + while (index < textLength) { - if (((startIndex = text.indexOf(startSymbol, index)) != -1) && - ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) { + 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); - parseFns.push($parse(exp, parseStringifyInterceptor)); index = endIndex + endSymbolLength; expressionPositions.push(concat.length); - concat.push(''); + concat.push(''); // Placeholder that will get replaced with the evaluated expression. } else { // we did not find an interpolation, so we have to add the remainder to the separators array if (index !== textLength) { @@ -10142,18 +14058,25 @@ function $InterpolateProvider() { } } + 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 && concat.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); - } + // single expression be used for some $sce-managed secure contexts (RESOURCE_URLs mostly), + // 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. + + // Note that URL and MEDIA_URL $sce contexts do not need this, since `$sce` can sanitize the values + // passed to it. In that case, `$sce.getTrusted` will be called on either the single expression + // or on the overall concatenated string (losing trusted types used in the mix, by design). + // Both these methods will sanitize plain strings. Also, HTML could be included, but since it's + // only used in srcdoc attributes, this would not be very useful. if (!mustHaveExpression || expressions.length) { var compute = function(values) { @@ -10161,30 +14084,16 @@ function $InterpolateProvider() { if (allOrNothing && isUndefined(values[i])) return; concat[expressionPositions[i]] = values[i]; } - return concat.join(''); - }; - - var getValue = function(value) { - return trustedContext ? - $sce.getTrusted(trustedContext, value) : - $sce.valueOf(value); - }; - var stringify = function(value) { - if (value == null) { // null || undefined - return ''; - } - switch (typeof value) { - case 'string': - break; - case 'number': - value = '' + value; - break; - default: - value = toJson(value); + if (contextAllowsConcatenation) { + // If `singleExpression` then `concat[0]` might be a "trusted" value or `null`, rather than a string + return $sce.getTrusted(trustedContext, singleExpression ? concat[0] : concat.join('')); + } else if (trustedContext && concat.length > 1) { + // This context does not allow more than one part, e.g. expr + string or exp + exp. + $interpolateMinErr.throwNoconcat(text); } - - return value; + // In an unprivileged context or only one part: just concatenate and return. + return concat.join(''); }; return extend(function interpolationFn(context) { @@ -10199,41 +14108,36 @@ function $InterpolateProvider() { return compute(values); } catch (err) { - var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, - err.toString()); - $exceptionHandler(newErr); + $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, objectEquality) { + $$watchDelegate: function(scope, listener) { var lastValue; - return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) { + return scope.$watchGroup(parseFns, /** @this */ function interpolateFnWatcher(values, oldValues) { var currValue = compute(values); - if (isFunction(listener)) { - listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope); - } + listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope); lastValue = currValue; - }, objectEquality); + }); } }); } - function unescapeText(text) { - return text.replace(escapedStartRegexp, startSymbol). - replace(escapedEndRegexp, endSymbol); - } - function parseStringifyInterceptor(value) { try { - value = getValue(value); + // 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) { - var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, - err.toString()); - $exceptionHandler(newErr); + $exceptionHandler($interpolateMinErr.interr(text, err)); } } } @@ -10274,272 +14178,328 @@ function $InterpolateProvider() { }]; } +var $intervalMinErr = minErr('$interval'); + +/** @this */ function $IntervalProvider() { - this.$get = ['$rootScope', '$window', '$q', '$$q', - function($rootScope, $window, $q, $$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, - iteration = 0, - skipApply = (isDefined(invokeApply) && !invokeApply), - deferred = (skipApply ? $$q : $q).defer(), - promise = deferred.promise; + /** + * @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; + }]; +} - }, delay); +/** @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); + } + } - intervals[promise.$$intervalId] = deferred; + function tick() { + if (skipApply) { + $browser.defer(callback); + } else { + $rootScope.$evalAsync(callback); + } + deferred.notify(iteration++); - return promise; - } + if (count > 0 && iteration >= count) { + deferred.resolve(iteration); + clearIntervalFn(promise.$$intervalId); + } + if (!skipApply) $rootScope.$apply(); + } - /** - * @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'); - $window.clearInterval(promise.$$intervalId); - delete intervals[promise.$$intervalId]; - return true; - } - return false; - }; + promise.$$intervalId = setIntervalFn(tick, delay, deferred, skipApply); - return interval; + return promise; + }; + }; }]; } /** * @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', - ERANAMES: [ - "Before Christ", - "Anno Domini" - ], - ERAS: [ - "BC", - "AD" - ] + /** + * @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`) + */ -var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/, +/* global stripHash: true */ + +var PATH_MATCH = /^([^?#]*)(\?([^#]*))?(#(.*))?$/, DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21}; var $locationMinErr = minErr('$location'); @@ -10555,63 +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 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) { + + if (DOUBLE_SLASH_REGEX.test(url)) { + throw $locationMinErr('badpath', 'Invalid url "{0}".', url); + } -function parseAppUrl(relativeUrl, locationObj) { - var prefixed = (relativeUrl.charAt(0) !== '/'); + var prefixed = (url.charAt(0) !== '/'); if (prefixed) { - relativeUrl = '/' + relativeUrl; + url = '/' + url; } - var match = urlResolve(relativeUrl); - 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); -} - -function trimEmptyHash(url) { - return url.replace(/(#.+)|#$/, '$1'); + return index === -1 ? url : url.substr(0, index); } - function stripFile(url) { return url.substr(0, stripHash(url).lastIndexOf('/') + 1); } @@ -10623,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); /** - * Parse given html5 (regular) url string into properties - * @param {string} url 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); + parseAppUrl(pathUrl, this, true); if (!this.$$path) { this.$$path = '/'; @@ -10658,16 +14644,8 @@ 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.$$parseLinkUrl = function(url, relHref) { @@ -10680,16 +14658,17 @@ function LocationHtml5Url(appBase, basePrefix) { 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) { - rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl); + if (basePrefix && isDefined(appUrl = stripBaseUrl(basePrefix, appUrl))) { + rewrittenUrl = appBaseNoFile + (stripBaseUrl('/', appUrl) || appUrl); } else { rewrittenUrl = appBase + prevAppUrl; } - } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) { + } else if (isDefined(appUrl = stripBaseUrl(appBaseNoFile, url))) { rewrittenUrl = appBaseNoFile + appUrl; - } else if (appBaseNoFile == url + '/') { + } else if (appBaseNoFile === url + '/') { rewrittenUrl = appBaseNoFile; } if (rewrittenUrl) { @@ -10701,34 +14680,34 @@ function LocationHtml5Url(appBase, basePrefix) { /** - * 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); /** - * 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 withoutBaseUrl = stripBaseUrl(appBase, url) || stripBaseUrl(appBaseNoFile, url); var withoutHashUrl; - if (withoutBaseUrl.charAt(0) === '#') { + if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') { - // The rest of the url starts with a hash so we have + // The rest of the URL starts with a hash so we have // got either a hashbang path or a plain hash fragment - withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl); + withoutHashUrl = stripBaseUrl(hashPrefix, withoutBaseUrl); if (isUndefined(withoutHashUrl)) { // There was no hashbang prefix so we just have a hash fragment withoutHashUrl = withoutBaseUrl; @@ -10738,10 +14717,18 @@ function LocationHashbangUrl(appBase, hashPrefix) { // 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 - withoutHashUrl = this.$$html5 ? withoutBaseUrl : ''; + if (this.$$html5) { + withoutHashUrl = withoutBaseUrl; + } else { + withoutHashUrl = ''; + if (isUndefined(withoutBaseUrl)) { + appBase = url; + /** @type {?} */ (this).replace(); + } + } } - parseAppUrl(withoutHashUrl, this); + parseAppUrl(withoutHashUrl, this, false); this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase); @@ -10755,7 +14742,7 @@ 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) { @@ -10768,7 +14755,7 @@ function LocationHashbangUrl(appBase, hashPrefix) { var firstPathSegmentMatch; //Get the relative path from the input URL. - if (url.indexOf(base) === 0) { + if (startsWith(url, base)) { url = url.replace(base, ''); } @@ -10782,20 +14769,12 @@ 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.$$parseLinkUrl = function(url, relHref) { - if (stripHash(appBase) == stripHash(url)) { + if (stripHash(appBase) === stripHash(url)) { this.$$parse(url); return true; } @@ -10805,20 +14784,19 @@ function LocationHashbangUrl(appBase, hashPrefix) { /** - * 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: @@ -10830,9 +14808,9 @@ function LocationHashbangInHtml5Url(appBase, hashPrefix) { var rewrittenUrl; var appUrl; - if (appBase == stripHash(url)) { + if (appBase === stripHash(url)) { rewrittenUrl = url; - } else if ((appUrl = beginsWith(appBaseNoFile, url))) { + } else if ((appUrl = stripBaseUrl(appBaseNoFile, url))) { rewrittenUrl = appBase + hashPrefix + appUrl; } else if (appBaseNoFile === url + '/') { rewrittenUrl = appBaseNoFile; @@ -10843,20 +14821,21 @@ function LocationHashbangInHtml5Url(appBase, hashPrefix) { return !!rewrittenUrl; }; - this.$$compose = function() { - var search = toKeyValue(this.$$search), - hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : ''; - - this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash; - // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#' - this.$$absUrl = appBase + hashPrefix + this.$$url; + 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; }; - } var locationPrototype = { + /** + * Ensure absolute URL is initialized. + * @private + */ + $$absUrl:'', + /** * Are we in html5 mode? * @private @@ -10869,6 +14848,16 @@ var locationPrototype = { */ $$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 @@ -10876,17 +14865,17 @@ var locationPrototype = { * @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). * * * ```js - * // given url http://example.com/#/some/path?foo=bar&baz=xoxo + * // 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 + * @return {string} full URL */ absUrl: locationGetter('$$absUrl'), @@ -10897,23 +14886,24 @@ var locationPrototype = { * @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`. * * * ```js - * // given url http://example.com/#/some/path?foo=bar&baz=xoxo + * // 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`) + * @param {string=} url New URL without base prefix (e.g. `/path?a=b#hash`) * @return {string} url */ url: function(url) { - if (isUndefined(url)) + if (isUndefined(url)) { return this.$$url; + } var match = PATH_MATCH.exec(url); if (match[1] || url === '') this.path(decodeURIComponent(match[1])); @@ -10930,16 +14920,16 @@ var locationPrototype = { * @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 + * // 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'), @@ -10950,16 +14940,24 @@ var locationPrototype = { * @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 + * // 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'), @@ -10970,11 +14968,11 @@ var locationPrototype = { * @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 + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo * var port = $location.port(); * // => 80 * ``` @@ -10990,7 +14988,7 @@ var locationPrototype = { * @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`. * @@ -10999,17 +14997,17 @@ var locationPrototype = { * * * ```js - * // given url http://example.com/#/some/path?foo=bar&baz=xoxo + * // 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} path + * @return {(string|object)} path if called with no parameters, or `$location` if called with a parameter */ path: locationGetterSetter('$$path', function(path) { path = path !== null ? path.toString() : ''; - return path.charAt(0) == '/' ? path : '/' + path; + return path.charAt(0) === '/' ? path : '/' + path; }), /** @@ -11019,13 +15017,13 @@ var locationPrototype = { * @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 + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo * var searchObject = $location.search(); * // => {foo: 'bar', baz: 'xoxo'} * @@ -11041,7 +15039,7 @@ var locationPrototype = { * 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. + * 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. @@ -11097,13 +15095,13 @@ var locationPrototype = { * @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 + * // given URL http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue * var hash = $location.hash(); * // => "hashValue" * ``` @@ -11120,8 +15118,8 @@ var locationPrototype = { * @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; @@ -11152,8 +15150,9 @@ forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], fun * @return {object} state */ Location.prototype.state = function(state) { - if (!arguments.length) + if (!arguments.length) { return this.$$state; + } if (Location !== LocationHtml5Url || !this.$$html5) { throw $locationMinErr('nostate', 'History API state support is available only ' + @@ -11163,6 +15162,7 @@ forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], fun // 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; }; @@ -11170,16 +15170,17 @@ forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], fun 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(); @@ -11218,11 +15219,13 @@ 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 = '', + var hashPrefix = '!', html5Mode = { enabled: false, requireBase: true, @@ -11233,6 +15236,7 @@ function $LocationProvider() { * @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 */ @@ -11259,8 +15263,12 @@ function $LocationProvider() { * 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}` - (default: `true`) When html5Mode is enabled, - * enables/disables url rewriting for relative links. + * - **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 */ @@ -11278,7 +15286,7 @@ function $LocationProvider() { html5Mode.requireBase = mode.requireBase; } - if (isBoolean(mode.rewriteLinks)) { + if (isBoolean(mode.rewriteLinks) || isString(mode.rewriteLinks)) { html5Mode.rewriteLinks = mode.rewriteLinks; } @@ -11338,7 +15346,7 @@ function $LocationProvider() { if (html5Mode.enabled) { if (!baseHref && html5Mode.requireBase) { throw $locationMinErr('nobase', - "$location in HTML5 mode requires a tag to be present!"); + '$location in HTML5 mode requires a tag to be present!'); } appBase = serverBase(initialUrl) + (baseHref || '/'); LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url; @@ -11346,13 +15354,22 @@ function $LocationProvider() { appBase = stripHash(initialUrl); LocationMode = LocationHashbangUrl; } - $location = new LocationMode(appBase, '#' + hashPrefix); + 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; @@ -11373,10 +15390,11 @@ function $LocationProvider() { } $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 (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return; + if (!rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which === 2 || event.button === 2) return; var elm = jqLite(event.target); @@ -11386,6 +15404,8 @@ function $LocationProvider() { 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 @@ -11402,15 +15422,13 @@ function $LocationProvider() { if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) { if ($location.$$parseLinkUrl(absHref, relHref)) { - // We do a preventDefault for all urls that are part of the angular application, + // 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 - if ($location.absUrl() != $browser.url()) { + if ($location.absUrl() !== $browser.url()) { $rootScope.$apply(); - // hack to work around FF6 bug 684208 when scenario runner clicks on links - $window.angular['ff-684208-preventDefault'] = true; } } } @@ -11418,7 +15436,7 @@ function $LocationProvider() { // rewrite hashbang url <> html5 url - if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) { + if ($location.absUrl() !== initialUrl) { $browser.url($location.absUrl(), true); } @@ -11426,11 +15444,17 @@ function $LocationProvider() { // update $location when $browser url changes $browser.onUrlChange(function(newUrl, newState) { + + 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; @@ -11455,36 +15479,40 @@ function $LocationProvider() { // update browser $rootScope.$watch(function $locationWatch() { - var oldUrl = trimEmptyHash($browser.url()); - var newUrl = trimEmptyHash($location.absUrl()); - var oldState = $browser.state(); - var currentReplace = $location.$$replace; - var urlOrStateChanged = oldUrl !== newUrl || - ($location.$$html5 && $sniffer.history && oldState !== $location.$$state); + if (initializing || $location.$$urlUpdatedByLocation) { + $location.$$urlUpdatedByLocation = false; - if (initializing || urlOrStateChanged) { - initializing = 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); - $rootScope.$evalAsync(function() { - var newUrl = $location.absUrl(); - var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, - $location.$$state, oldState).defaultPrevented; + if (initializing || urlOrStateChanged) { + initializing = false; - // if the location was changed by a `$locationChangeStart` handler then stop - // processing this location change - if ($location.absUrl() !== newUrl) return; + $rootScope.$evalAsync(function() { + var newUrl = $location.absUrl(); + var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, + $location.$$state, oldState).defaultPrevented; - if (defaultPrevented) { - $location.$$parse(oldUrl); - $location.$$state = oldState; - } else { - if (urlOrStateChanged) { - setBrowserUrlWithFallback(newUrl, currentReplace, - oldState === $location.$$state ? null : $location.$$state); + // 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); } - afterLocationChange(oldUrl, oldState); - } - }); + }); + } } $location.$$replace = false; @@ -11513,11 +15541,19 @@ 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 - + angular.module('logExample', []) .controller('LogController', ['$scope', '$log', function($scope, $log) { @@ -11528,8 +15564,8 @@ function $LocationProvider() {

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

- Message: - + @@ -11543,6 +15579,8 @@ function $LocationProvider() { /** * @ngdoc provider * @name $logProvider + * @this + * * @description * Use the `$logProvider` to configure how the application logs messages */ @@ -11560,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) { + // 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 @@ -11619,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; @@ -11637,29 +15684,17 @@ function $LogProvider() { function consoleLog(type) { var console = $window.console || {}, - logFn = console[type] || console.log || noop, - hasApply = false; + logFn = console[type] || console.log || noop; - // 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) {} - - 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); }; } }]; @@ -11678,138 +15713,45 @@ function $LogProvider() { var $parseMinErr = minErr('$parse'); -// 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")') // -// 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. -// -// 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. -// Similarly we prevent invocations of function known to be dangerous, as well as assignments to -// native objects. +// 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. // // See https://docs.angularjs.org/guide/security -function ensureSafeMemberName(name, fullExpression) { - if (name === "__defineGetter__" || name === "__defineSetter__" - || name === "__lookupGetter__" || name === "__lookupSetter__" - || name === "__proto__") { - throw $parseMinErr('isecfld', - 'Attempting to access a disallowed field in Angular expressions! ' - + 'Expression: {0}', fullExpression); - } - 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.window === obj) { - 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); - } else if (// block Object so that we can't get hold of dangerous Object.* methods - obj === Object) { - throw $parseMinErr('isecobj', - 'Referencing Object in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } - } - return obj; -} - -var CALL = Function.prototype.call; -var APPLY = Function.prototype.apply; -var BIND = Function.prototype.bind; - -function ensureSafeFunction(obj, fullExpression) { - if (obj) { - if (obj.constructor === obj) { - throw $parseMinErr('isecfn', - 'Referencing Function in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } else if (obj === CALL || obj === APPLY || obj === BIND) { - throw $parseMinErr('isecff', - 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}', - fullExpression); - } - } +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 + ''; } -//Keyword constants -var CONSTANTS = createMap(); -forEach({ - 'null': function() { return null; }, - 'true': function() { return true; }, - 'false': function() { return false; }, - 'undefined': function() {} -}, function(constantGetter, name) { - constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true; - CONSTANTS[name] = constantGetter; -}); - -//Not quite a constant, but can be lex/parsed the same -CONSTANTS['this'] = function(self) { return self; }; -CONSTANTS['this'].sharedGetter = true; - -//Operators - will be wrapped by binaryFn/unaryFn/assignment/filter -var OPERATORS = extend(createMap(), { - '+':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);}, - '!==':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(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) {return !a(self, locals);}, - - //Tokenized as operators but parsed as assignment/filters - '=':true, - '|':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', '\'':'\'', '"':'"'}; ///////////////////////////////////////// @@ -11818,7 +15760,7 @@ 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; }; @@ -11832,11 +15774,11 @@ Lexer.prototype = { while (this.index < this.text.length) { var ch = this.text.charAt(this.index); - if (ch === '"' || ch === "'") { + if (ch === '"' || ch === '\'') { this.readString(ch); } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) { this.readNumber(); - } else if (this.isIdent(ch)) { + } else if (this.isIdentifierStart(this.peekMultichar())) { this.readIdent(); } else if (this.is(ch, '(){}[].,;:?')) { this.tokens.push({index: this.index, text: ch}); @@ -11871,7 +15813,7 @@ Lexer.prototype = { }, isNumber: function(ch) { - return ('0' <= ch && ch <= '9') && typeof ch === "string"; + return ('0' <= ch && ch <= '9') && typeof ch === 'string'; }, isWhitespace: function(ch) { @@ -11880,21 +15822,57 @@ 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 === '$'); }, - isExpOperator: function(ch) { - return (ch === '-' || ch === '+' || this.isNumber(ch)); + isIdentifierContinue: function(ch) { + return this.options.isIdentifierContinue ? + this.options.isIdentifierContinue(ch, this.codePointAt(ch)) : + this.isValidIdentifierContinue(ch); }, - throwError: function(error, start, end) { - end = end || this.index; - var colStr = (isDefined(start) - ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']' - : ' ' + end); + 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)); + }, + + throwError: function(error, start, end) { + end = end || this.index; + var colStr = (isDefined(start) + ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']' + : ' ' + end); throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].', error, colStr, this.text); }, @@ -11904,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; @@ -11934,12 +15912,13 @@ Lexer.prototype = { readIdent: function() { var start = this.index; + this.index += this.peekMultichar().length; while (this.index < this.text.length) { - var ch = this.text.charAt(this.index); - if (!(this.isIdent(ch) || this.isNumber(ch))) { + var ch = this.peekMultichar(); + if (!this.isIdentifierContinue(ch)) { break; } - this.index++; + this.index += ch.length; } this.tokens.push({ index: start, @@ -11960,8 +15939,9 @@ 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 { @@ -11989,295 +15969,110 @@ Lexer.prototype = { } }; - -function isConstant(exp) { - return exp.constant; -} - -/** - * @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; -}, { - sharedGetter: true, - constant: true -}); - -Parser.prototype = { - constructor: Parser, - - parse: function(text) { +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; this.tokens = this.lexer.lex(text); - var value = 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 if (this.peek().identifier && this.peek().text in CONSTANTS) { - primary = CONSTANTS[this.consume().text]; - } else if (this.peek().identifier) { - primary = this.identifier(); - } else if (this.peek().constant) { - primary = this.constant(); - } else { - this.throwError('not a primary expression', this.peek()); - } - - 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; - }, - - 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)); - }, - - peekToken: function() { - if (this.tokens.length === 0) - throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); - 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; - } - } - 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; - }, - - consume: function(e1) { - if (this.tokens.length === 0) { - throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); - } - - var token = this.expect(e1); - if (!token) { - this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); - } - return token; - }, - - unaryFn: function(op, right) { - var fn = OPERATORS[op]; - return extend(function $parseUnaryFn(self, locals) { - return fn(self, locals, right); - }, { - constant:right.constant, - inputs: [right] - }); - }, - - binaryFn: function(left, op, right, isBranching) { - var fn = OPERATORS[op]; - return extend(function $parseBinaryFn(self, locals) { - return fn(self, locals, left, right); - }, { - constant: left.constant && right.constant, - inputs: !isBranching && [left, right] - }); - }, - - identifier: function() { - var id = this.consume().text; - - //Continue reading each `.identifier` unless it is a method invocation - while (this.peek('.') && this.peekAhead(1).identifier && !this.peekAhead(2, '(')) { - id += this.consume().text + this.consume().text; - } - - return getterFn(id, this.options, this.text); - }, - - constant: function() { - var value = this.consume().value; - - return extend(function $parseConstant() { - return value; - }, { - constant: true, - literal: true - }); - }, - - statements: function() { - var statements = []; + program: function() { + var body = []; while (true) { if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']')) - statements.push(this.filterChain()); + body.push(this.expressionStatement()); 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 $parseStatements(self, locals) { - var value; - for (var i = 0, ii = statements.length; i < ii; i++) { - value = statements[i](self, locals); - } - return value; - }; + return { type: AST.Program, body: body}; } } }, + expressionStatement: function() { + return { type: AST.ExpressionStatement, expression: this.filterChain() }; + }, + filterChain: function() { var left = this.expression(); - var token; - while ((token = this.expect('|'))) { + while (this.expect('|')) { left = this.filter(left); } return left; }, - filter: function(inputFn) { - var fn = this.$filter(this.consume().text); - var argsFn; - var args; - - if (this.peek(':')) { - argsFn = []; - args = []; // we can safely reuse the array - while (this.expect(':')) { - argsFn.push(this.expression()); - } - } - - var inputs = [inputFn].concat(argsFn || []); - - return extend(function $parseFilter(self, locals) { - var input = inputFn(self, locals); - if (args) { - args[0] = input; - - var i = argsFn.length; - while (i--) { - args[i + 1] = argsFn[i](self, locals); - } - - return fn.apply(undefined, args); - } - - return fn(input); - }, { - constant: !fn.$stateful && inputs.every(isConstant), - inputs: !fn.$stateful && inputs - }); - }, - expression: function() { return this.assignment(); }, assignment: function() { - var left = this.ternary(); - var right; - 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 extend(function $parseAssignment(scope, locals) { - return left.assign(scope, right(scope, locals), locals); - }, { - inputs: [left, right] - }); + 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 left; + return result; }, ternary: function() { - var left = this.logicalOR(); - var middle; - var token; - if ((token = this.expect('?'))) { - middle = this.assignment(); + var test = this.logicalOR(); + var alternate; + var consequent; + if (this.expect('?')) { + alternate = this.expression(); if (this.consume(':')) { - var right = this.assignment(); - - return extend(function $parseTernary(self, locals) { - return left(self, locals) ? middle(self, locals) : right(self, locals); - }, { - constant: left.constant && middle.constant && right.constant - }); + consequent = this.expression(); + return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent}; } } - - return left; + return test; }, logicalOR: function() { var left = this.logicalAND(); - var token; - while ((token = this.expect('||'))) { - left = this.binaryFn(left, token.text, this.logicalAND(), true); + while (this.expect('||')) { + left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() }; } return left; }, logicalAND: function() { var left = this.equality(); - var token; - while ((token = this.expect('&&'))) { - left = this.binaryFn(left, token.text, this.equality(), true); + while (this.expect('&&')) { + left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()}; } return left; }, @@ -12286,7 +16081,7 @@ Parser.prototype = { var left = this.relational(); var token; while ((token = this.expect('==','!=','===','!=='))) { - left = this.binaryFn(left, token.text, this.relational()); + left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() }; } return left; }, @@ -12295,7 +16090,7 @@ Parser.prototype = { var left = this.additive(); var token; while ((token = this.expect('<', '>', '<=', '>='))) { - left = this.binaryFn(left, token.text, this.additive()); + left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() }; } return left; }, @@ -12304,7 +16099,7 @@ Parser.prototype = { var left = this.multiplicative(); var token; while ((token = this.expect('+','-'))) { - left = this.binaryFn(left, token.text, this.multiplicative()); + left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() }; } return left; }, @@ -12313,11656 +16108,16806 @@ Parser.prototype = { var left = this.unary(); var token; while ((token = this.expect('*','/','%'))) { - left = this.binaryFn(left, token.text, this.unary()); + left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() }; } return left; }, unary: function() { var token; - if (this.expect('+')) { - return this.primary(); - } else if ((token = this.expect('-'))) { - return this.binaryFn(Parser.ZERO, token.text, this.unary()); - } else if ((token = this.expect('!'))) { - return this.unaryFn(token.text, this.unary()); + if ((token = this.expect('+', '-', '!'))) { + return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() }; } else { return this.primary(); } }, - fieldAccess: function(object) { - var getter = this.identifier(); + 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 { + this.throwError('not a primary expression', this.peek()); + } - return extend(function $parseFieldAccess(scope, locals, self) { - var o = self || object(scope, locals); - return (o == null) ? undefined : getter(o); - }, { - assign: function(scope, value, locals) { - var o = object(scope, locals); - if (!o) object.assign(scope, o = {}, locals); - return getter.assign(o, value); + 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 { + this.throwError('IMPOSSIBLE'); } - }); + } + return primary; }, - objectIndex: function(obj) { - var expression = this.text; + filter: function(baseExpression) { + var args = [baseExpression]; + var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true}; - var indexFn = this.expression(); - this.consume(']'); + while (this.expect(':')) { + args.push(this.expression()); + } - return extend(function $parseObjectIndex(self, locals) { - var o = obj(self, locals), - i = indexFn(self, locals), - v; - - ensureSafeMemberName(i, expression); - if (!o) return undefined; - v = ensureSafeObject(o[i], expression); - return v; - }, { - assign: function(self, value, locals) { - var key = ensureSafeMemberName(indexFn(self, locals), expression); - // prevent overwriting of Function.constructor which would break ensureSafeObject check - var o = ensureSafeObject(obj(self, locals), expression); - if (!o) obj.assign(self, o = {}, locals); - return o[key] = value; - } - }); + return result; }, - functionCall: function(fnGetter, 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 expressionText = this.text; - // we can safely reuse the array across invocations - var args = argsFn.length ? [] : null; - - return function $parseFunctionCall(scope, locals) { - var context = contextGetter ? contextGetter(scope, locals) : isDefined(contextGetter) ? undefined : scope; - var fn = fnGetter(scope, locals, context) || noop; - - if (args) { - var i = argsFn.length; - while (i--) { - args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText); - } - } - - ensureSafeObject(context, expressionText); - ensureSafeFunction(fn, expressionText); - - // IE doesn't have apply for some native functions - var v = fn.apply - ? fn.apply(context, args) - : fn(args[0], args[1], args[2], args[3], args[4]); + return args; + }, - if (args) { - // Free-up the memory (arguments of the last function call). - args.length = 0; - } + 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, expressionText); - }; + 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 elements = []; if (this.peekToken().text !== ']') { do { if (this.peek(']')) { // Support trailing commas per ES5.1. break; } - elementFns.push(this.expression()); + elements.push(this.expression()); } while (this.expect(',')); } this.consume(']'); - return extend(function $parseArrayLiteral(self, locals) { - var array = []; - for (var i = 0, ii = elementFns.length; i < ii; i++) { - array.push(elementFns[i](self, locals)); - } - return array; - }, { - literal: true, - constant: elementFns.every(isConstant), - inputs: elementFns - }); + return { type: AST.ArrayExpression, elements: elements }; }, object: function() { - var keys = [], valueFns = []; + var properties = [], property; if (this.peekToken().text !== '}') { do { if (this.peek('}')) { // Support trailing commas per ES5.1. break; } - var token = this.consume(); - if (token.constant) { - keys.push(token.value); - } else if (token.identifier) { - keys.push(token.text); + 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", token); + this.throwError('invalid key', this.peek()); } - this.consume(':'); - valueFns.push(this.expression()); + properties.push(property); } while (this.expect(',')); } this.consume('}'); - return extend(function $parseObjectLiteral(self, locals) { - var object = {}; - for (var i = 0, ii = valueFns.length; i < ii; i++) { - object[keys[i]] = valueFns[i](self, locals); - } - return object; - }, { - literal: true, - constant: valueFns.every(isConstant), - inputs: valueFns - }); - } -}; - - -////////////////////////////////////////////////// -// Parser helper functions -////////////////////////////////////////////////// + return {type: AST.ObjectExpression, properties: properties }; + }, -function setter(obj, locals, path, setValue, fullExp) { - ensureSafeObject(obj, fullExp); - ensureSafeObject(locals, fullExp); + 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)); + }, - var element = path.split('.'), key; - for (var i = 0; element.length > 1; i++) { - key = ensureSafeMemberName(element.shift(), fullExp); - var propertyObj = (i === 0 && locals && locals[key]) || obj[key]; - if (!propertyObj) { - propertyObj = {}; - obj[key] = propertyObj; + consume: function(e1) { + if (this.tokens.length === 0) { + throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); } - obj = ensureSafeObject(propertyObj, fullExp); - } - key = ensureSafeMemberName(element.shift(), fullExp); - ensureSafeObject(obj[key], fullExp); - obj[key] = setValue; - return setValue; -} -var getterFnCacheDefault = createMap(); -var getterFnCacheExpensive = createMap(); - -function isPossiblyDangerousMemberName(name) { - return name == 'constructor'; -} - -/** - * 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, expensiveChecks) { - ensureSafeMemberName(key0, fullExp); - ensureSafeMemberName(key1, fullExp); - ensureSafeMemberName(key2, fullExp); - ensureSafeMemberName(key3, fullExp); - ensureSafeMemberName(key4, fullExp); - var eso = function(o) { - return ensureSafeObject(o, fullExp); - }; - var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity; - var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity; - var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity; - var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity; - var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity; + var token = this.expect(e1); + if (!token) { + this.throwError('is unexpected, expecting [' + e1 + ']', this.peek()); + } + return token; + }, - return function cspSafeGetter(scope, locals) { - var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope; + peekToken: function() { + if (this.tokens.length === 0) { + throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text); + } + return this.tokens[0]; + }, - if (pathVal == null) return pathVal; - pathVal = eso0(pathVal[key0]); + peek: function(e1, e2, e3, e4) { + return this.peekAhead(0, e1, e2, e3, e4); + }, - if (!key1) return pathVal; - if (pathVal == null) return undefined; - pathVal = eso1(pathVal[key1]); + 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; + } + } + return false; + }, - if (!key2) return pathVal; - if (pathVal == null) return undefined; - pathVal = eso2(pathVal[key2]); - - if (!key3) return pathVal; - if (pathVal == null) return undefined; - pathVal = eso3(pathVal[key3]); + expect: function(e1, e2, e3, e4) { + var token = this.peek(e1, e2, e3, e4); + if (token) { + this.tokens.shift(); + return token; + } + return false; + }, - if (!key4) return pathVal; - if (pathVal == null) return undefined; - pathVal = eso4(pathVal[key4]); + selfReferential: { + 'this': {type: AST.ThisExpression }, + '$locals': {type: AST.LocalsExpression } + } +}; - return pathVal; - }; +function ifDefined(v, d) { + return typeof v !== 'undefined' ? v : d; } -function getterFnWithEnsureSafeObject(fn, fullExpression) { - return function(s, l) { - return fn(s, l, ensureSafeObject, fullExpression); - }; +function plusFn(l, r) { + if (typeof l === 'undefined') return r; + if (typeof r === 'undefined') return l; + return l + r; } -function getterFn(path, options, fullExp) { - var expensiveChecks = options.expensiveChecks; - var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault); - var fn = getterFnCache[path]; - if (fn) return fn; +function isStateless($filter, filterName) { + var fn = $filter(filterName); + return !fn.$stateful; +} +var PURITY_ABSOLUTE = 1; +var PURITY_RELATIVE = 2; - var pathKeys = path.split('.'), - pathKeysLength = pathKeys.length; +// 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; - // http://jsperf.com/angularjs-parse-getter/6 - if (options.csp) { - if (pathKeysLength < 6) { - fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks); - } else { - fn = function cspSafeGetter(scope, locals) { - var i = 0, val; - do { - val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], - pathKeys[i++], fullExp, expensiveChecks)(scope, locals); + // Unary always convert to primative + case AST.UnaryExpression: + return PURITY_ABSOLUTE; - locals = undefined; // clear after first iteration - scope = val; - } while (i < pathKeysLength); - return val; - }; - } - } else { - var code = ''; - if (expensiveChecks) { - code += 's = eso(s, fe);\nl = eso(l, fe);\n'; - } - var needsEnsureSafeObject = expensiveChecks; - forEach(pathKeys, function(key, index) { - ensureSafeMemberName(key, fullExp); - var lookupJs = (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 - : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key; - if (expensiveChecks || isPossiblyDangerousMemberName(key)) { - lookupJs = 'eso(' + lookupJs + ', fe)'; - needsEnsureSafeObject = true; - } - code += 'if(s == null) return undefined;\n' + - 's=' + lookupJs + ';\n'; - }); - code += 'return s;'; + // The binary + operator can invoke a stateful toString(). + case AST.BinaryExpression: + return node.operator !== '+' ? PURITY_ABSOLUTE : false; - /* jshint -W054 */ - var evaledFnGetter = new Function('s', 'l', 'eso', 'fe', code); // s=scope, l=locals, eso=ensureSafeObject - /* jshint +W054 */ - evaledFnGetter.toString = valueFn(code); - if (needsEnsureSafeObject) { - evaledFnGetter = getterFnWithEnsureSafeObject(evaledFnGetter, fullExp); - } - fn = evaledFnGetter; + // Functions / filters probably read state from within objects + case AST.CallExpression: + return false; } - fn.sharedGetter = true; - fn.assign = function(self, value, locals) { - return setter(self, locals, path, value, path); - }; - getterFnCache[path] = fn; - return fn; + return (undefined === parentIsPure) ? PURITY_RELATIVE : parentIsPure; } -var objectValueOf = Object.prototype.valueOf; +function findConstantAndWatchExpressions(ast, $filter, parentIsPure) { + var allConstants; + var argsToWatch; + var isStatelessFilter; -function getValueOf(value) { - return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value); + 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 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; +} -/** - * @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. - * - */ +function isAssignable(ast) { + return ast.type === AST.Identifier || ast.type === AST.MemberExpression; +} +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: '='}; + } +} -/** - * @ngdoc provider - * @name $parseProvider - * - * @description - * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} - * service. - */ -function $ParseProvider() { - var cacheDefault = createMap(); - var cacheExpensive = createMap(); +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); +} +function isConstant(ast) { + return ast.constant; +} +function ASTCompiler($filter) { + this.$filter = $filter; +} - this.$get = ['$filter', '$sniffer', function($filter, $sniffer) { - var $parseOptions = { - csp: $sniffer.csp, - expensiveChecks: false - }, - $parseOptionsExpensive = { - csp: $sniffer.csp, - expensiveChecks: true - }; +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; + }, - function wrapSharedExpression(exp) { - var wrapped = exp; + USE: 'use', - if (exp.sharedGetter) { - wrapped = function $parseWrapper(self, locals) { - return exp(self, locals); - }; - wrapped.literal = exp.literal; - wrapped.constant = exp.constant; - wrapped.assign = exp.assign; - } + STRICT: 'strict', - return wrapped; + 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(''); + }, - return function $parse(exp, interceptorFn, expensiveChecks) { - var parsedExpression, oneTime, cacheKey; - - switch (typeof exp) { - case 'string': - cacheKey = exp = exp.trim(); + generateFunction: function(name, params) { + return 'function(' + params + '){' + + this.varsPrefix(name) + + this.body(name) + + '};'; + }, - var cache = (expensiveChecks ? cacheExpensive : cacheDefault); - parsedExpression = cache[cacheKey]; + 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 ''; + }, - if (!parsedExpression) { - if (exp.charAt(0) === ':' && exp.charAt(1) === ':') { - oneTime = true; - exp = exp.substring(2); - } + varsPrefix: function(section) { + return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : ''; + }, - var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions; - var lexer = new Lexer(parseOptions); - var parser = new Parser(lexer, $filter, parseOptions); - parsedExpression = parser.parse(exp); + body: function(section) { + return this.state[section].body.join(''); + }, - if (parsedExpression.constant) { - parsedExpression.$$watchDelegate = constantWatchDelegate; - } else if (oneTime) { - //oneTime is not part of the exp passed to the Parser so we may have to - //wrap the parsedExpression before adding a $$watchDelegate - parsedExpression = wrapSharedExpression(parsedExpression); - parsedExpression.$$watchDelegate = parsedExpression.literal ? - oneTimeLiteralWatchDelegate : oneTimeWatchDelegate; - } else if (parsedExpression.inputs) { - parsedExpression.$$watchDelegate = inputsWatchDelegate; + 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; } - - cache[cacheKey] = parsedExpression; } - return addInterceptor(parsedExpression, interceptorFn); - - case 'function': - return addInterceptor(exp, interceptorFn); - - default: - return addInterceptor(noop, interceptorFn); + }, 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); + }); } - }; - - function collectExpressionInputs(inputs, list) { - for (var i = 0, ii = inputs.length; i < ii; i++) { - var input = inputs[i]; - if (!input.constant) { - if (input.inputs) { - collectExpressionInputs(input.inputs, list); - } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better? - list.push(input); - } + 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; + } + }, - return list; + 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]; + }, - function expressionInputDirtyCheck(newValue, oldValueOfValue) { + assign: function(id, value) { + if (!id) return; + this.current().body.push(id, '=', value, ';'); + return id; + }, - if (newValue == null || oldValueOfValue == null) { // null/undefined - return newValue === oldValueOfValue; - } + filter: function(filterName) { + if (!this.state.filters.hasOwnProperty(filterName)) { + this.state.filters[filterName] = this.nextId(true); + } + return this.state.filters[filterName]; + }, - if (typeof newValue === 'object') { + ifDefined: function(id, defaultValue) { + return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')'; + }, - // 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); + plus: function(left, right) { + return 'plus(' + left + ',' + right + ')'; + }, - if (typeof newValue === 'object') { - // objects/arrays are not supported - deep-watching them would be too expensive - return false; - } + return_: function(id) { + this.current().body.push('return ', id, ';'); + }, - // fall-through to the primitive equality check + if_: function(test, alternate, consequent) { + if (test === true) { + alternate(); + } else { + var body = this.current().body; + body.push('if(', test, '){'); + alternate(); + body.push('}'); + if (consequent) { + body.push('else{'); + consequent(); + body.push('}'); } - - //Primitive or NaN - return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue); } + }, - function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) { - var inputExpressions = parsedExpression.$$inputs || - (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, [])); + not: function(expression) { + return '!(' + expression + ')'; + }, - var lastResult; + isNull: function(expression) { + return expression + '==null'; + }, - if (inputExpressions.length === 1) { - var oldInputValue = 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, oldInputValue)) { - lastResult = parsedExpression(scope); - oldInputValue = newInputValue && getValueOf(newInputValue); - } - return lastResult; - }, listener, objectEquality); - } + notNull: function(expression) { + return expression + '!=null'; + }, - var oldInputValueOfValues = []; - for (var i = 0, ii = inputExpressions.length; i < ii; i++) { - oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails - } + 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 left + '["' + right.replace(UNSAFE_CHARACTERS, this.stringEscapeFn) + '"]'; + } + }, - return scope.$watch(function expressionInputsWatch(scope) { - var changed = false; + computedMember: function(left, right) { + return left + '[' + right + ']'; + }, - for (var i = 0, ii = inputExpressions.length; i < ii; i++) { - var newInputValue = inputExpressions[i](scope); - if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) { - oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue); - } - } + member: function(left, right, computed) { + if (computed) return this.computedMember(left, right); + return this.nonComputedMember(left, right); + }, - if (changed) { - lastResult = parsedExpression(scope); - } + getStringValue: function(item) { + this.assign(item, 'getStringValue(' + item + ')'); + }, - return lastResult; - }, listener, objectEquality); - } + lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) { + var self = this; + return function() { + self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck); + }; + }, - function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) { - var unwatch, lastValue; - return unwatch = scope.$watch(function oneTimeWatch(scope) { - return parsedExpression(scope); - }, function oneTimeListener(value, old, scope) { - lastValue = value; - if (isFunction(listener)) { - listener.apply(this, arguments); - } - if (isDefined(value)) { - scope.$$postDigest(function() { - if (isDefined(lastValue)) { - unwatch(); - } - }); - } - }, objectEquality); - } + lazyAssign: function(id, value) { + var self = this; + return function() { + self.assign(id, value); + }; + }, - function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) { - var unwatch, lastValue; - return unwatch = scope.$watch(function oneTimeWatch(scope) { - return parsedExpression(scope); - }, function oneTimeListener(value, old, scope) { - lastValue = value; - if (isFunction(listener)) { - listener.call(this, value, old, scope); - } - if (isAllDefined(value)) { - scope.$$postDigest(function() { - if (isAllDefined(lastValue)) unwatch(); - }); - } - }, objectEquality); + stringEscapeRegex: /[^ a-zA-Z0-9]/g, - function isAllDefined(value) { - var allDefined = true; - forEach(value, function(val) { - if (!isDefined(val)) allDefined = false; - }); - return allDefined; - } + stringEscapeFn: function(c) { + return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4); + }, + + 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'; + + throw $parseMinErr('esc', 'IMPOSSIBLE'); + }, + + nextId: function(skip, init) { + var id = 'v' + (this.state.nextId++); + if (!skip) { + this.current().vars.push(id + (init ? '=' + init : '')); } + return id; + }, - function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) { - var unwatch; - return unwatch = scope.$watch(function constantWatch(scope) { - return parsedExpression(scope); - }, function constantListener(value, old, scope) { - if (isFunction(listener)) { - listener.apply(this, arguments); - } - unwatch(); - }, objectEquality); + current: function() { + return this.state[this.state.computing]; + } +}; + + +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; + }, - function addInterceptor(parsedExpression, interceptorFn) { - if (!interceptorFn) return parsedExpression; - var watchDelegate = parsedExpression.$$watchDelegate; - - var regularWatch = - watchDelegate !== oneTimeLiteralWatchDelegate && - watchDelegate !== oneTimeWatchDelegate; - - var fn = regularWatch ? function regularInterceptedExpression(scope, locals) { - var value = parsedExpression(scope, locals); - return interceptorFn(value, scope, locals); - } : function oneTimeInterceptedExpression(scope, locals) { - var value = parsedExpression(scope, locals); - var result = interceptorFn(value, scope, locals); - // we only return the interceptor's result if the - // initial value is defined (for bind-once) - return isDefined(value) ? result : value; + 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; + }; + } + }, - // Propagate $$watchDelegates other then inputsWatchDelegate - if (parsedExpression.$$watchDelegate && - parsedExpression.$$watchDelegate !== inputsWatchDelegate) { - fn.$$watchDelegate = parsedExpression.$$watchDelegate; - } else if (!interceptorFn.$stateful) { - // If there is an interceptor, but no watchDelegate then treat the interceptor like - // we treat filters - it is assumed to be a pure function unless flagged with $stateful - fn.$$watchDelegate = inputsWatchDelegate; - fn.inputs = [parsedExpression]; + '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(); - return fn; + 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 - * A service that helps you run functions asynchronously, and use their return values (or exceptions) - * when they are done processing. - * - * This is an 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 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 Harmony, - * 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 Harmony 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. * - * 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 - * performed asynchronously, and may or may not be finished at any given point in time. - * - * From the perspective of dealing with error handling, deferred and promise APIs are to - * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming. + * Converts AngularJS {@link guide/expression expression} into a function. * * ```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) { - * var deferred = $q.defer(); - * - * setTimeout(function() { - * deferred.notify('About to greet ' + name + '.'); - * - * if (okToGreet(name)) { - * deferred.resolve('Hello, ' + name + '!'); - * } else { - * deferred.reject('Greeting ' + name + ' is not allowed.'); - * } - * }, 1000); - * - * return deferred.promise; - * } + * var getter = $parse('user.name'); + * var setter = getter.assign; + * var context = {user:{name:'AngularJS'}}; + * var locals = {user:{name:'local'}}; * - * var promise = asyncGreet('Robin Hood'); - * promise.then(function(greeting) { - * alert('Success: ' + greeting); - * }, function(reason) { - * alert('Failed: ' + reason); - * }, function(update) { - * alert('Got notification: ' + update); - * }); + * expect(getter(context)).toEqual('AngularJS'); + * setter(context, 'newValue'); + * expect(context.user.name).toEqual('newValue'); + * expect(getter(context, locals)).toEqual('local'); * ``` * - * At first it might not be obvious why this extra complexity is worth the trouble. The payoff - * comes in the way of guarantees that promise and deferred APIs make, see - * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. - * - * Additionally the promise api allows for composition that is very hard to do with the - * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. - * 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 * - * A new instance of deferred is constructed by calling `$q.defer()`. + * @param {string} expression String expression to compile. + * @returns {function(context, locals)} a function which represents the compiled expression: * - * The purpose of the deferred object is to expose the associated Promise instance as well as APIs - * that can be used for signaling the successful or unsuccessful completion, as well as the status - * of the task. + * * `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`. * - * **Methods** + * 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. * - * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection - * constructed via `$q.reject`, the promise will be rejected instead. - * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to - * resolving it with a rejection constructed via `$q.reject`. - * - `notify(value)` - provides updates on the status of the promise's execution. This may be called - * multiple times before the promise is either resolved or rejected. + */ + + +/** + * @ngdoc provider + * @name $parseProvider + * @this * - * **Properties** - * - * - promise – `{Promise}` – promise object associated with this deferred. - * - * - * # The Promise API - * - * A new promise instance is created when a deferred instance is created and can be retrieved by - * calling `deferred.promise`. - * - * The purpose of the promise object is to allow for interested parties to get access to the result - * of the deferred task when it completes. - * - * **Methods** - * - * - `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 cannot be resolved or rejected from the notifyCallback - * method. - * - * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)` - * - * - `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. - * - * # 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: - * - * ```js - * promiseB = promiseA.then(function(result) { - * return result + 1; - * }); - * - * // promiseB will be resolved immediately after promiseA is resolved and its value - * // will be the result of promiseA incremented by 1 - * ``` - * - * It is possible to create chains of any length and since a promise can be resolved with another - * promise (which will defer its resolution further), it is possible to pause/defer resolution of - * the promises at any point in the chain. This makes it possible to implement powerful APIs like - * $http's response interceptors. - * - * - * # 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 - * 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 - * - * ```js - * it('should simulate promise', inject(function($q, $rootScope) { - * var deferred = $q.defer(); - * var promise = deferred.promise; - * var resolvedValue; - * - * promise.then(function(value) { resolvedValue = value; }); - * expect(resolvedValue).toBeUndefined(); - * - * // Simulate resolving of promise - * deferred.resolve(123); - * // Note that the 'then' function does not get called synchronously. - * // This is because we want the promise API to always be async, whether or not - * // it got called synchronously or asynchronously. - * expect(resolvedValue).toBeUndefined(); - * - * // Propagate promise resolution to 'then' functions using $apply(). - * $rootScope.$apply(); - * 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. - */ -function $QProvider() { - - this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) { - return qFactory(function(callback) { - $rootScope.$evalAsync(callback); - }, $exceptionHandler); - }]; -} - -function $$QProvider() { - this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) { - return qFactory(function(callback) { - $browser.defer(callback); - }, $exceptionHandler); - }]; -} - -/** - * Constructs a promise manager. - * - * @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. - * @returns {object} Promise manager. + * @description + * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse} + * service. */ -function qFactory(nextTick, exceptionHandler) { - var $qMinErr = minErr('$q', TypeError); - function callOnce(self, resolveFn, rejectFn) { - var called = false; - function wrap(fn) { - return function(value) { - if (called) return; - called = true; - fn.call(self, value); - }; - } - - return [wrap(resolveFn), wrap(rejectFn)]; - } +function $ParseProvider() { + var cache = createMap(); + var literals = { + 'true': true, + 'false': false, + 'null': null, + 'undefined': undefined + }; + var identStart, identContinue; /** * @ngdoc method - * @name ng.$q#defer - * @kind function - * + * @name $parseProvider#addLiteral * @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() { - return new Deferred(); + * 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; }; - function Promise() { - this.$$state = { status: 0 }; - } + /** + * @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; + }; - Promise.prototype = { - then: function(onFulfilled, onRejected, progressBack) { - var result = new Deferred(); + 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; - this.$$state.pending = this.$$state.pending || []; - this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]); - if (this.$$state.status > 0) scheduleProcessQueue(this.$$state); + function $parse(exp, interceptorFn) { + var parsedExpression, cacheKey; - return result.promise; - }, + switch (typeof exp) { + case 'string': + exp = exp.trim(); + cacheKey = exp; - "catch": function(callback) { - return this.then(null, callback); - }, + parsedExpression = cache[cacheKey]; - "finally": function(callback, progressBack) { - return this.then(function(value) { - return handleCallback(value, true, callback); - }, function(error) { - return handleCallback(error, false, callback); - }, progressBack); + 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); + } } - }; - //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native - function simpleBind(context, fn) { - return function(value) { - fn.call(context, value); - }; - } + function $$getAst(exp) { + var lexer = new Lexer($parseOptions); + var parser = new Parser(lexer, $filter, $parseOptions); + return parser.getAst(exp).ast; + } - function processQueue(state) { - var fn, promise, pending; + function expressionInputDirtyCheck(newValue, oldValueOfValue, compareObjectIdentity) { - pending = state.pending; - state.processScheduled = false; - state.pending = undefined; - for (var i = 0, ii = pending.length; i < ii; ++i) { - promise = pending[i][0]; - fn = pending[i][state.status]; - try { - if (isFunction(fn)) { - promise.resolve(fn(state.value)); - } else if (state.status === 1) { - promise.resolve(state.value); - } else { - promise.reject(state.value); + 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; } - } catch (e) { - promise.reject(e); - exceptionHandler(e); + + // 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 scheduleProcessQueue(state) { - if (state.processScheduled || !state.pending) return; - state.processScheduled = true; - nextTick(function() { processQueue(state); }); - } + function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) { + var inputExpressions = parsedExpression.inputs; + var lastResult; - function Deferred() { - this.promise = new Promise(); - //Necessary to support unbound execution :/ - this.resolve = simpleBind(this, this.resolve); - this.reject = simpleBind(this, this.reject); - this.notify = simpleBind(this, this.notify); - } + 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); + } - Deferred.prototype = { - resolve: function(val) { - if (this.promise.$$state.status) return; - if (val === this.promise) { - this.$$reject($qMinErr( - 'qcycle', - "Expected promise to be resolved with value other than itself '{0}'", - val)); - } else { - this.$$resolve(val); + 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; - $$resolve: function(val) { - var then, fns; + 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); + } + } - fns = callOnce(this, this.$$resolve, this.$$reject); - try { - if ((isObject(val) || isFunction(val))) then = val && val.then; - if (isFunction(then)) { - this.promise.$$state.status = -1; - then.call(val, fns[0], fns[1], this.notify); - } else { - this.promise.$$state.value = val; - this.promise.$$state.status = 1; - scheduleProcessQueue(this.promise.$$state); + 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(); } - } catch (e) { - fns[1](e); - exceptionHandler(e); } - }, - reject: function(reason) { - if (this.promise.$$state.status) return; - this.$$reject(reason); - }, + 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); + } + } - $$reject: function(reason) { - this.promise.$$state.value = reason; - this.promise.$$state.status = 2; - scheduleProcessQueue(this.promise.$$state); - }, + function isAllDefined(value) { + var allDefined = true; + forEach(value, function(val) { + if (!isDefined(val)) allDefined = false; + }); + return allDefined; + } - notify: function(progress) { - var callbacks = this.promise.$$state.pending; + function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) { + var unwatch = scope.$watch(function constantWatch(scope) { + unwatch(); + return parsedExpression(scope); + }, listener, objectEquality); + return unwatch; + } - if ((this.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 { - result.notify(isFunction(callback) ? callback(progress) : progress); - } catch (e) { - exceptionHandler(e); - } - } - }); + 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; } - }; - /** - * @ngdoc method - * @name $q#reject - * @kind function - * - * @description - * Creates a promise that is resolved as rejected with the specified `reason`. This api should be - * used to forward rejection in a chain of promises. If you are dealing with the last promise in - * a promise chain, you don't need to worry about it. - * - * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of - * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via - * a promise error callback and you want to forward the error to the promise derived from the - * current promise, you have to "rethrow" the error by returning a rejection constructed via - * `reject`. - * - * ```js - * promiseB = promiseA.then(function(result) { - * // success: do something and resolve promiseB - * // with the old or a new result - * return result; - * }, function(reason) { - * // error: handle the error if possible and - * // resolve promiseB with newPromiseOrValue, - * // otherwise forward the rejection to promiseB - * if (canHandle(reason)) { - * // handle the error and recover - * return newPromiseOrValue; - * } - * return $q.reject(reason); - * }); - * ``` - * - * @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 = new Deferred(); - result.reject(reason); - return result.promise; - }; - - var makePromise = function makePromise(value, resolved) { - var result = new Deferred(); - if (resolved) { - result.resolve(value); - } else { - result.reject(value); - } - return result.promise; - }; - - var handleCallback = function handleCallback(value, isResolved, callback) { - var callbackOutput = null; - try { - if (isFunction(callback)) callbackOutput = callback(); - } catch (e) { - return makePromise(e, false); - } - if (isPromiseLike(callbackOutput)) { - return callbackOutput.then(function() { - return makePromise(value, isResolved); - }, function(error) { - return makePromise(error, false); - }); - } else { - return makePromise(value, isResolved); - } - }; - - /** - * @ngdoc method - * @name $q#when - * @kind function - * - * @description - * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. - * This is useful when you are dealing with an object that might or might not be a promise, or if - * the promise comes from a source that can't be trusted. - * - * @param {*} value Value or a promise - * @returns {Promise} Returns a promise of the passed value or promise - */ - - - var when = function(value, callback, errback, progressBack) { - var result = new Deferred(); - result.resolve(value); - return result.promise.then(callback, errback, progressBack); - }; - - /** - * @ngdoc method - * @name $q#all - * @kind function - * - * @description - * Combines multiple promises into a single promise that is resolved when all of the input - * promises are resolved. - * - * @param {Array.|Object.} promises An array or hash of promises. - * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, - * each value corresponding to the promise at the same index/key in the `promises` array/hash. - * 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 = new Deferred(), - counter = 0, - results = isArray(promises) ? [] : {}; - - forEach(promises, function(promise, key) { - counter++; - when(promise).then(function(value) { - if (results.hasOwnProperty(key)) return; - results[key] = value; - if (!(--counter)) deferred.resolve(results); - }, function(reason) { - if (results.hasOwnProperty(key)) return; - deferred.reject(reason); - }); - }); - - if (counter === 0) { - deferred.resolve(results); - } - - return deferred.promise; - } - - var $Q = function Q(resolver) { - if (!isFunction(resolver)) { - throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver); - } - - if (!(this instanceof Q)) { - // More useful when $Q is the Promise itself. - return new Q(resolver); - } - - var deferred = new Deferred(); - - function resolveFn(value) { - deferred.resolve(value); - } + function chainInterceptors(first, second) { + function chainedInterceptor(value) { + return second(first(value)); + } + chainedInterceptor.$stateful = first.$stateful || second.$stateful; + chainedInterceptor.$$pure = first.$$pure && second.$$pure; - function rejectFn(reason) { - deferred.reject(reason); + return chainedInterceptor; } - resolver(resolveFn, rejectFn); - - return deferred.promise; - }; - - $Q.defer = defer; - $Q.reject = reject; - $Q.when = when; - $Q.all = all; + function addInterceptor(parsedExpression, interceptorFn) { + if (!interceptorFn) return parsedExpression; - return $Q; -} + // 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; + } -function $$RAFProvider() { //rAF - this.$get = ['$window', '$timeout', function($window, $timeout) { - var requestAnimationFrame = $window.requestAnimationFrame || - $window.webkitRequestAnimationFrame; + var useInputs = false; - var cancelAnimationFrame = $window.cancelAnimationFrame || - $window.webkitCancelAnimationFrame || - $window.webkitCancelRequestAnimationFrame; + var fn = function interceptedExpression(scope, locals, assign, inputs) { + var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs); + return interceptorFn(value); + }; - var rafSupported = !!requestAnimationFrame; - var raf = rafSupported - ? function(fn) { - var id = requestAnimationFrame(fn); - return function() { - cancelAnimationFrame(id); - }; + // 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; + }); } - : function(fn) { - var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 - return function() { - $timeout.cancel(timer); - }; - }; - - raf.supported = rafSupported; + } - return raf; + return addWatchDelegate(fn); + } }]; } /** - * DESIGN NOTES + * @ngdoc service + * @name $q + * @requires $rootScope * - * The design decisions behind the scope are heavily favored for speed and memory consumption. + * @description + * A service that helps you run functions asynchronously, and use their return values (or exceptions) + * when they are done processing. * - * The typical use of scope is to watch the expressions, which most of the time return the same - * value as last time so we optimize the operation. + * 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). * - * Closures construction is expensive in terms of speed as well as memory: - * - No closures, instead use prototypical inheritance for API - * - Internal state needs to be stored on scope directly, which means that private state is - * exposed as $$____ properties + * $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. * - * 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 (unshift) instead of at the end (push) + * ## $q constructor * - * Child scopes are created and removed often - * - Using an array would be slow since inserts in middle are expensive so we use linked list + * 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). * - * 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. - */ - - -/** - * @ngdoc provider - * @name $rootScopeProvider - * @description + * While the constructor-style use is supported, not all of the supporting methods from ES6 promises are + * available yet. * - * Provider for the $rootScope service. - */ - -/** - * @ngdoc method - * @name $rootScopeProvider#digestTtl - * @description + * It can be used like so: * - * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and - * assuming that the model is unstable. + * ```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). * - * The current default is 10 iterations. + * 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); + * }); + * } * - * In complex applications it's possible that the dependencies between `$watch`s will result in - * several digest iterations. However if an application needs more than the default 10 digest - * iterations for its model to stabilize then you should investigate what is causing the model to - * continuously change during the digest. + * var promise = asyncGreet('Robin Hood'); + * promise.then(function(greeting) { + * alert('Success: ' + greeting); + * }, function(reason) { + * alert('Failed: ' + reason); + * }); + * ``` * - * Increasing the TTL could have performance implications, so you should not change it without - * proper justification. + * Note: progress/notify callbacks are not currently supported via the ES6-style interface. * - * @param {number} limit The number of digest iterations. - */ - - -/** - * @ngdoc service - * @name $rootScope - * @description + * Note: unlike ES6 behavior, an exception thrown in the constructor function will NOT implicitly reject the promise. * - * 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 - * {@link guide/scope developer guide on scopes}. - */ -function $RootScopeProvider() { - var TTL = 10; - var $rootScopeMinErr = minErr('$rootScope'); - var lastDirtyWatch = null; - var applyAsyncId = null; - - this.digestTtl = function(value) { - if (arguments.length) { - TTL = value; - } - return TTL; - }; - - 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; + * 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 + * performed asynchronously, and may or may not be finished at any given point in time. + * + * From the perspective of dealing with error handling, deferred and promise APIs are to + * 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` 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() { + * deferred.notify('About to greet ' + name + '.'); + * + * if (okToGreet(name)) { + * deferred.resolve('Hello, ' + name + '!'); + * } else { + * deferred.reject('Greeting ' + name + ' is not allowed.'); + * } + * }, 1000); + * + * return deferred.promise; + * } + * + * var promise = asyncGreet('Robin Hood'); + * promise.then(function(greeting) { + * alert('Success: ' + greeting); + * }, function(reason) { + * alert('Failed: ' + reason); + * }, function(update) { + * alert('Got notification: ' + update); + * }); + * ``` + * + * At first it might not be obvious why this extra complexity is worth the trouble. The payoff + * comes in the way of guarantees that promise and deferred APIs make, see + * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md. + * + * Additionally the promise api allows for composition that is very hard to do with the + * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach. + * 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 + * + * A new instance of deferred is constructed by calling `$q.defer()`. + * + * The purpose of the deferred object is to expose the associated Promise instance as well as APIs + * that can be used for signaling the successful or unsuccessful completion, as well as the status + * of the task. + * + * **Methods** + * + * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection + * constructed via `$q.reject`, the promise will be rejected instead. + * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to + * resolving it with a rejection constructed via `$q.reject`. + * - `notify(value)` - provides updates on the status of the promise's execution. This may be called + * multiple times before the promise is either resolved or rejected. + * + * **Properties** + * + * - promise – `{Promise}` – promise object associated with this deferred. + * + * + * ## The Promise API + * + * A new promise instance is created when a deferred instance is created and can be retrieved by + * calling `deferred.promise`. + * + * The purpose of the promise object is to allow for interested parties to get access to the result + * of the deferred task when it completes. + * + * **Methods** + * + * - `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` (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, 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. + * + * ## 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: + * + * ```js + * promiseB = promiseA.then(function(result) { + * return result + 1; + * }); + * + * // promiseB will be resolved immediately after promiseA is resolved and its value + * // will be the result of promiseA incremented by 1 + * ``` + * + * It is possible to create chains of any length and since a promise can be resolved with another + * promise (which will defer its resolution further), it is possible to pause/defer resolution of + * the promises at any point in the chain. This makes it possible to implement powerful APIs like + * $http's response interceptors. + * + * + * ## 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 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 + * + * ```js + * it('should simulate promise', inject(function($q, $rootScope) { + * var deferred = $q.defer(); + * var promise = deferred.promise; + * var resolvedValue; + * + * promise.then(function(value) { resolvedValue = value; }); + * expect(resolvedValue).toBeUndefined(); + * + * // Simulate resolving of promise + * deferred.resolve(123); + * // Note that the 'then' function does not get called synchronously. + * // This is because we want the promise API to always be async, whether or not + * // it got called synchronously or asynchronously. + * expect(resolvedValue).toBeUndefined(); + * + * // Propagate promise resolution to 'then' functions using $apply(). + * $rootScope.$apply(); + * 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, 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; } - ChildScope.prototype = parent; - return ChildScope; + }; +} + +/** @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(...*)} 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, errorOnUnhandledRejections) { + var $qMinErr = minErr('$q', TypeError); + var queueSize = 0; + var checkQueue = []; + + /** + * @ngdoc method + * @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. + */ + function defer() { + return new Deferred(); + } + + 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); }; } - this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser', - function($injector, $exceptionHandler, $parse, $browser) { - function destroyChildScope($event) { - $event.currentScope.$$destroyed = true; + function Promise() { + this.$$state = { status: 0 }; + } + + 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); + + return result; + }, + + 'catch': function(callback) { + return this.then(null, callback); + }, + + 'finally': function(callback, progressBack) { + return this.then(function(value) { + return handleCallback(value, resolve, callback); + }, function(error) { + return handleCallback(error, reject, callback); + }, progressBack); } + }); - /** - * @ngdoc type - * @name $rootScope.Scope - * - * @description - * 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.) - * - * Here is a simple scope snippet to show how you can interact with the scope. - * ```html - * - * ``` - * - * # Inheritance - * A scope can inherit from a parent scope, as in this example: - * ```js - var parent = $rootScope; - var child = parent.$new(); + function processQueue(state) { + var fn, promise, pending; + + 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 { + 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); + } + } + } + + 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); + } + } + } + } + + 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 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 $$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); + } + + 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); + } + + 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 + * @kind function + * + * @description + * Creates a promise that is resolved as rejected with the specified `reason`. This api should be + * used to forward rejection in a chain of promises. If you are dealing with the last promise in + * a promise chain, you don't need to worry about it. + * + * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of + * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via + * a promise error callback and you want to forward the error to the promise derived from the + * current promise, you have to "rethrow" the error by returning a rejection constructed via + * `reject`. + * + * ```js + * promiseB = promiseA.then(function(result) { + * // success: do something and resolve promiseB + * // with the old or a new result + * return result; + * }, function(reason) { + * // error: handle the error if possible and + * // resolve promiseB with newPromiseOrValue, + * // otherwise forward the rejection to promiseB + * if (canHandle(reason)) { + * // handle the error and recover + * return newPromiseOrValue; + * } + * return $q.reject(reason); + * }); + * ``` + * + * @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`. + */ + 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 + * @kind function + * + * @description + * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. + * This is useful when you are dealing with an object that might or might not be a promise, or if + * the promise comes from a source that can't be trusted. + * + * @param {*} value Value or a promise + * @param {Function=} successCallback + * @param {Function=} errorCallback + * @param {Function=} progressCallback + * @returns {Promise} Returns a promise of the passed value or promise + */ + + + 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 + * @kind function + * + * @description + * Combines multiple promises into a single promise that is resolved when all of the input + * promises are resolved. + * + * @param {Array.|Object.} promises An array or hash of promises. + * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values, + * each value corresponding to the promise at the same index/key in the `promises` array/hash. + * 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 result = new Promise(), + counter = 0, + results = isArray(promises) ? [] : {}; + + forEach(promises, function(promise, key) { + counter++; + when(promise).then(function(value) { + results[key] = value; + if (!(--counter)) resolvePromise(result, results); + }, function(reason) { + rejectPromise(result, reason); + }); + }); + + if (counter === 0) { + 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; + } + + 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); + } +} + +/** @this */ +function $$RAFProvider() { //rAF + this.$get = ['$window', '$timeout', function($window, $timeout) { + var requestAnimationFrame = $window.requestAnimationFrame || + $window.webkitRequestAnimationFrame; + + var cancelAnimationFrame = $window.cancelAnimationFrame || + $window.webkitCancelAnimationFrame || + $window.webkitCancelRequestAnimationFrame; + + var rafSupported = !!requestAnimationFrame; + var raf = rafSupported + ? function(fn) { + var id = requestAnimationFrame(fn); + return function() { + cancelAnimationFrame(id); + }; + } + : function(fn) { + var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666 + return function() { + $timeout.cancel(timer); + }; + }; + + raf.supported = rafSupported; + + return raf; + }]; +} + +/** + * DESIGN NOTES + * + * The design decisions behind the scope are heavily favored for speed and memory consumption. + * + * The typical use of scope is to watch the expressions, which most of the time return the same + * value as last time so we optimize the operation. + * + * Closures construction is expensive in terms of speed as well as memory: + * - No closures, instead use prototypical inheritance for API + * - Internal state needs to be stored on scope directly, which means that private state is + * 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 (unshift) instead of at the end (push) + * + * Child scopes are created and removed often + * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists + * + * 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. + */ + + +/** + * @ngdoc provider + * @name $rootScopeProvider + * @description + * + * Provider for the $rootScope service. + */ + +/** + * @ngdoc method + * @name $rootScopeProvider#digestTtl + * @description + * + * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and + * assuming that the model is unstable. + * + * The current default is 10 iterations. + * + * In complex applications it's possible that the dependencies between `$watch`s will result in + * several digest iterations. However if an application needs more than the default 10 digest + * iterations for its model to stabilize then you should investigate what is causing the model to + * continuously change during the digest. + * + * Increasing the TTL could have performance implications, so you should not change it without + * proper justification. + * + * @param {number} limit The number of digest iterations. + */ + + +/** + * @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 event emission/broadcast and subscription facility. See the + * {@link guide/scope developer guide on scopes}. + */ +function $RootScopeProvider() { + var TTL = 10; + var $rootScopeMinErr = minErr('$rootScope'); + var lastDirtyWatch = null; + var applyAsyncId = null; + + this.digestTtl = function(value) { + if (arguments.length) { + TTL = value; + } + return TTL; + }; + + 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 + * @name $rootScope.Scope + * + * @description + * 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.) See also the {@link guide/scope Scopes guide} for + * an in-depth introduction and usage examples. + * + * + * ## Inheritance + * A scope can inherit from a parent scope, as in this example: + * ```js + var parent = $rootScope; + var child = parent.$new(); + + parent.salutation = "Hello"; + expect(child.salutation).toEqual('Hello'); + + child.salutation = "Welcome"; + expect(child.salutation).toEqual('Welcome'); + 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}. + * @param {Object.=} instanceCache Provides pre-instantiated services which should + * append/override services provided by `providers`. This is handy + * when unit-testing and having the need to override a default + * service. + * @returns {Object} Newly created scope. + * + */ + function Scope() { + this.$id = nextUid(); + this.$$phase = this.$parent = this.$$watchers = + this.$$nextSibling = this.$$prevSibling = + this.$$childHead = this.$$childTail = null; + this.$root = this; + this.$$destroyed = false; + this.$$suspended = false; + this.$$listeners = {}; + this.$$listenerCount = {}; + this.$$watchersCount = 0; + this.$$isolateBindings = null; + } + + /** + * @ngdoc property + * @name $rootScope.Scope#$id + * + * @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 + * @kind function + * + * @description + * Creates a new child {@link ng.$rootScope.Scope scope}. + * + * 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 + * thus stop participating in model change detection and listener notification by invoking. + * + * @param {boolean} isolate If true, then the scope does not prototypically inherit from the + * parent scope. The scope is isolated, as it can not see parent scope properties. + * 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, parent) { + var child; + + parent = parent || this; + + if (isolate) { + child = new Scope(); + child.$root = this.$root; + } else { + // 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 { + 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 + * @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. (`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). 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`. (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 + * watcher. In rare cases, this is undesirable because the listener is called when the result + * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you + * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the + * listener was called due to initialization. + * + * + * + * @example + * ```js + // let's assume that scope was dependency injected as the $rootScope + var scope = $rootScope; + scope.name = 'misko'; + scope.counter = 0; + + expect(scope.counter).toEqual(0); + scope.$watch('name', function(newValue, oldValue) { + scope.counter = scope.counter + 1; + }); + expect(scope.counter).toEqual(0); + + scope.$digest(); + // the listener is always called during the first $digest loop after it was registered + expect(scope.counter).toEqual(1); + + 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 function as a watchExpression + var food; + scope.foodCounter = 0; + expect(scope.foodCounter).toEqual(0); + scope.$watch( + // This function returns the value being watched. It is called for each turn of the $digest loop + function() { return food; }, + // 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 + scope.foodCounter = scope.foodCounter + 1; + } + } + ); + // No digest has been run so the counter will be zero + expect(scope.foodCounter).toEqual(0); + + // Run the digest but since food has not changed count will still be zero + scope.$digest(); + expect(scope.foodCounter).toEqual(0); + + // Update food and run digest. Now the counter will increment + food = 'cheeseburger'; + scope.$digest(); + expect(scope.foodCounter).toEqual(1); + + * ``` + * + * + * + * @param {(function()|string)} watchExpression Expression that is evaluated on each + * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers + * a call to the `listener`. + * + * - `string`: Evaluated as {@link guide/expression expression} + * - `function(scope)`: called with current `scope` as a parameter. + * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value + * of `watchExpression` changes. + * + * - `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, 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, + array = scope.$$watchers, + watcher = { + fn: fn, + last: initWatchVal, + get: get, + exp: prettyPrintExpression || watchExp, + eq: !!objectEquality + }; + + lastDirtyWatch = null; + + 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); + 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 + * @kind function + * + * @description + * Shallow watches the properties of an object and fires whenever any of the properties change + * (for arrays, this implies watching the array items; for object maps, this implies watching + * the properties). If a change is detected, the `listener` callback is fired. + * + * - The `obj` collection is observed via standard $watch operation and is examined on every + * call to $digest() to see if any items have been added, removed, or moved. + * - The `listener` is called whenever anything within the `obj` has changed. Examples include + * adding, removing, and moving items belonging to an object or array. + * + * + * @example + * ```js + $scope.names = ['igor', 'matias', 'misko', 'james']; + $scope.dataCount = 4; + + $scope.$watchCollection('names', function(newNames, oldNames) { + $scope.dataCount = newNames.length; + }); + + expect($scope.dataCount).toEqual(4); + $scope.$digest(); + + //still at 4 ... no changes + expect($scope.dataCount).toEqual(4); + + $scope.names.pop(); + $scope.$digest(); + + //now there's been a change + expect($scope.dataCount).toEqual(3); + * ``` + * + * + * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The + * expression value should evaluate to an object or an array which is observed on each + * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the + * collection will trigger a call to the `listener`. + * + * @param {function(newCollection, oldCollection, scope)} listener a callback function called + * when a change is detected. + * - The `newCollection` object is the newly modified data obtained from the `obj` expression + * - The `oldCollection` object is a copy of the former collection data. + * Due to performance considerations, the`oldCollection` value is computed only if the + * `listener` function declares two or more arguments. + * - The `scope` argument refers to the current scope. + * + * @returns {function()} Returns a de-registration function for this listener. When the + * 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; + // a shallow copy of the newValue from the last dirty-check run, + // updated to match newValue during dirty-check run + var oldValue; + // a shallow copy of the newValue from when the last change happened + var veryOldValue; + // only track veryOldValue if the listener is asking for it + var trackVeryOldValue = (listener.length > 1); + var changeDetected = 0; + var changeDetector = $parse(obj, $watchCollectionInterceptor); + var internalArray = []; + var internalObject = {}; + var initRun = true; + var oldLength = 0; + + 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) { + oldValue = newValue; + changeDetected++; + } + } else if (isArrayLike(newValue)) { + if (oldValue !== internalArray) { + // we are transitioning from something which was not an array into array. + oldValue = internalArray; + oldLength = oldValue.length = 0; + changeDetected++; + } + + newLength = newValue.length; + + if (oldLength !== newLength) { + // if lengths do not match we need to trigger change notification + changeDetected++; + oldValue.length = oldLength = newLength; + } + // copy the items to oldValue and look for changes. + for (var i = 0; i < newLength; 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] = newItem; + } + } + } else { + if (oldValue !== internalObject) { + // we are transitioning from something which was not an object into object. + oldValue = internalObject = {}; + oldLength = 0; + changeDetected++; + } + // copy the items to oldValue and look for changes. + newLength = 0; + for (key in newValue) { + if (hasOwnProperty.call(newValue, key)) { + newLength++; + 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] = newItem; + } + } else { + oldLength++; + oldValue[key] = newItem; + changeDetected++; + } + } + } + if (oldLength > newLength) { + // we used to have more keys, need to find them and destroy them. + changeDetected++; + for (key in oldValue) { + if (!hasOwnProperty.call(newValue, key)) { + oldLength--; + delete oldValue[key]; + } + } + } + } + return changeDetected; + } + + function $watchCollectionAction() { + if (initRun) { + initRun = false; + listener(newValue, newValue, self); + } else { + listener(newValue, veryOldValue, self); + } + + // make a copy for the next time a collection is changed + if (trackVeryOldValue) { + if (!isObject(newValue)) { + //primitive + veryOldValue = newValue; + } else if (isArrayLike(newValue)) { + veryOldValue = new Array(newValue.length); + for (var i = 0; i < newValue.length; i++) { + veryOldValue[i] = newValue[i]; + } + } else { // if object + veryOldValue = {}; + for (var key in newValue) { + if (hasOwnProperty.call(newValue, key)) { + veryOldValue[key] = newValue[key]; + } + } + } + } + } + + return this.$watch(changeDetector, $watchCollectionAction); + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$digest + * @kind function + * + * @description + * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and + * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change + * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} + * until no more listeners are firing. This means that it is possible to get into an infinite + * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of + * iterations exceeds 10. + * + * Usually, you don't call `$digest()` directly in + * {@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 directive}), which will force a `$digest()`. + * + * If you want to be notified whenever `$digest()` is called, + * you can register a `watchExpression` function with + * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. + * + * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. + * + * @example + * ```js + var scope = ...; + scope.name = 'misko'; + scope.counter = 0; + + expect(scope.counter).toEqual(0); + scope.$watch('name', function(newValue, oldValue) { + scope.counter = scope.counter + 1; + }); + expect(scope.counter).toEqual(0); + + scope.$digest(); + // the listener is always called during the first $digest loop after it was registered + expect(scope.counter).toEqual(1); + + 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, fn, get, + watchers, + dirty, ttl = TTL, + next, current, target = asyncQueue.length ? $rootScope : this, + watchLog = [], + 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; + + do { // "while dirty" loop + dirty = false; + current = target; + + // 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[asyncQueuePosition]; + fn = asyncTask.fn; + fn(asyncTask.scope, asyncTask.locals); + } catch (e) { + $exceptionHandler(e); + } + lastDirtyWatch = null; + } + asyncQueue.length = 0; + + traverseScopesLoop: + do { // "traverse the scopes" loop + if ((watchers = !current.$$suspended && current.$$watchers)) { + // process our watches + watchers.$$digestWatchIndex = watchers.length; + while (watchers.$$digestWatchIndex--) { + try { + 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) { + get = watch.get; + if ((value = get(current)) !== (last = watch.last) && + !(watch.eq + ? equals(value, last) + : (isNumberNaN(value) && isNumberNaN(last)))) { + dirty = true; + lastDirtyWatch = watch; + 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] = []; + 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 + // have already been tested. + dirty = false; + break traverseScopesLoop; + } + } + } catch (e) { + $exceptionHandler(e); + } + } + } + + // 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 + // (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)) { + current = current.$parent; + } + } + } while ((current = next)); + + // `break traverseScopesLoop;` takes us to here + + if ((dirty || asyncQueue.length) && !(ttl--)) { + clearPhase(); + throw $rootScopeMinErr('infdig', + '{0} $digest() iterations reached. Aborting!\n' + + 'Watchers fired in the last 5 iterations: {1}', + TTL, watchLog); + } + + } while (dirty || asyncQueue.length); + + clearPhase(); + + // postDigestQueuePosition isn't local here because this loop can be reentered recursively. + while (postDigestQueuePosition < postDigestQueue.length) { + try { + 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 method + * @name $rootScope.Scope#$suspend + * @kind function + * + * @description + * Suspend watchers of this scope subtree so that they will not be invoked during digest. + * + * 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#$isSuspended + * @kind function + * + * @description + * 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: + * + * ``` + * 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 + * perform any necessary cleanup. + * + * 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. + */ + $destroy: function() { + // 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) { + //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 && 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; + + // 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 = {}; + + // Disconnect the next sibling to prevent `cleanUpScope` destroying those too + this.$$nextSibling = null; + cleanUpScope(this); + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$eval + * @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 AngularJS + * expressions. + * + * @example + * ```js + var scope = ng.$rootScope.Scope(); + scope.a = 1; + scope.b = 2; + + expect(scope.$eval('a+b')).toEqual(3); + expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); + * ``` + * + * @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. + * @returns {*} The result of evaluating the expression. + */ + $eval: function(expr, locals) { + return $parse(expr)(this, locals); + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$evalAsync + * @kind function + * + * @description + * Executes the expression on the current scope at a later point in time. + * + * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only + * that: + * + * - it will execute after the function that scheduled the evaluation (preferably before DOM + * rendering). + * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after + * `expression` execution. + * + * Any exceptions from the execution of the expression are forwarded to the + * {@link ng.$exceptionHandler $exceptionHandler} service. + * + * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle + * 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 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, 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 && !asyncQueue.length) { + $browser.defer(function() { + if (asyncQueue.length) { + $rootScope.$digest(); + } + }, null, '$evalAsync'); + } + + asyncQueue.push({scope: this, fn: $parse(expr), locals: locals}); + }, + + $$postDigest: function(fn) { + postDigestQueue.push(fn); + }, + + /** + * @ngdoc method + * @name $rootScope.Scope#$apply + * @kind function + * + * @description + * `$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 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: Pseudo-Code of `$apply()`** + * + * ```js + function $apply(expr) { + try { + return $eval(expr); + } catch (e) { + $exceptionHandler(e); + } finally { + $root.$digest(); + } + } + * ``` + * + * + * Scope's `$apply()` method transitions through the following stages: + * + * 1. The {@link guide/expression expression} is executed using the + * {@link ng.$rootScope.Scope#$eval $eval()} method. + * 2. Any exceptions from the execution of the expression are forwarded to the + * {@link ng.$exceptionHandler $exceptionHandler} service. + * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the + * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. + * + * + * @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. + * + * @returns {*} The result of evaluating the expression. + */ + $apply: function(expr) { + try { + beginPhase('$apply'); + try { + return this.$eval(expr); + } finally { + clearPhase(); + } + } catch (e) { + $exceptionHandler(e); + } finally { + 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 + * @kind function + * + * @description + * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for + * discussion of event life cycle. + * + * The event listener function format is: `function(event, args...)`. The `event` object + * passed into the listener has the following attributes: + * + * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or + * `$broadcast`-ed. + * - `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). + * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag + * to true. + * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. + * + * @param {string} name Event name to listen on. + * @param {function(event, ...args)} listener Function to call when the event is emitted. + * @returns {function()} Returns a deregistration function for this listener. + */ + $on: function(name, listener) { + var namedListeners = this.$$listeners[name]; + if (!namedListeners) { + this.$$listeners[name] = namedListeners = []; + } + namedListeners.push(listener); + + var current = this; + do { + if (!current.$$listenerCount[name]) { + current.$$listenerCount[name] = 0; + } + current.$$listenerCount[name]++; + } while ((current = current.$parent)); + + var self = this; + return function() { + 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); + } + }; + }, + + + /** + * @ngdoc method + * @name $rootScope.Scope#$emit + * @kind function + * + * @description + * Dispatches an event `name` upwards through the scope hierarchy notifying the + * registered {@link ng.$rootScope.Scope#$on} listeners. + * + * The event life cycle starts at the scope on which `$emit` was called. All + * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get + * notified. Afterwards, the event traverses upwards toward the root scope and calls all + * registered listeners along the way. The event will stop propagating if one of the listeners + * cancels it. + * + * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed + * onto the {@link ng.$exceptionHandler $exceptionHandler} service. + * + * @param {string} name Event name to emit. + * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. + * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). + */ + $emit: function(name, args) { + var empty = [], + namedListeners, + scope = this, + stopPropagation = false, + event = { + name: name, + targetScope: scope, + stopPropagation: function() {stopPropagation = true;}, + preventDefault: function() { + event.defaultPrevented = true; + }, + defaultPrevented: false + }, + listenerArgs = concat([event], arguments, 1), + i, length; + + do { + namedListeners = scope.$$listeners[name] || empty; + event.currentScope = scope; + for (i = 0, length = namedListeners.length; i < length; i++) { + + // if listeners were deregistered, defragment the array + if (!namedListeners[i]) { + namedListeners.splice(i, 1); + i--; + length--; + continue; + } + try { + //allow all listeners attached to the current scope to run + namedListeners[i].apply(null, listenerArgs); + } catch (e) { + $exceptionHandler(e); + } + } + //if any listener on the current scope stops propagation, prevent bubbling + if (stopPropagation) { + break; + } + //traverse upwards + scope = scope.$parent; + } while (scope); + + event.currentScope = null; + + return event; + }, + + + /** + * @ngdoc method + * @name $rootScope.Scope#$broadcast + * @kind function + * + * @description + * Dispatches an event `name` downwards to all child scopes (and their children) notifying the + * registered {@link ng.$rootScope.Scope#$on} listeners. + * + * The event life cycle starts at the scope on which `$broadcast` was called. All + * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get + * notified. Afterwards, the event propagates to all direct and indirect scopes of the current + * scope and calls all registered listeners along the way. The event cannot be canceled. + * + * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed + * onto the {@link ng.$exceptionHandler $exceptionHandler} service. + * + * @param {string} name Event name to broadcast. + * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. + * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} + */ + $broadcast: function(name, args) { + var target = this, + current = target, + next = target, + event = { + name: name, + targetScope: target, + preventDefault: function() { + event.defaultPrevented = true; + }, + defaultPrevented: false + }; + + if (!target.$$listenerCount[name]) return event; + + var listenerArgs = concat([event], arguments, 1), + listeners, i, length; + + //down while you can, then up and next sibling or up and next sibling until back at root + while ((current = next)) { + event.currentScope = current; + listeners = current.$$listeners[name] || []; + for (i = 0, length = listeners.length; i < length; i++) { + // if listeners were deregistered, defragment the array + if (!listeners[i]) { + listeners.splice(i, 1); + i--; + length--; + continue; + } + + try { + listeners[i].apply(null, listenerArgs); + } catch (e) { + $exceptionHandler(e); + } + } + + // 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 $digest + // (though it differs due to having the extra check for $$listenerCount and + // does not check $$suspended) + if (!(next = ((current.$$listenerCount[name] && current.$$childHead) || + (current !== target && current.$$nextSibling)))) { + while (current !== target && !(next = current.$$nextSibling)) { + current = current.$parent; + } + } + } + + event.currentScope = null; + return event; + } + }; + + var $rootScope = new Scope(); + + //The internal queues. Expose them on the $rootScope for debugging/testing purposes. + var asyncQueue = $rootScope.$$asyncQueue = []; + var postDigestQueue = $rootScope.$$postDigestQueue = []; + var applyAsyncQueue = $rootScope.$$applyAsyncQueue = []; + + var postDigestQueuePosition = 0; + + return $rootScope; + + + function beginPhase(phase) { + if ($rootScope.$$phase) { + throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase); + } + + $rootScope.$$phase = phase; + } + + function clearPhase() { + $rootScope.$$phase = null; + } + + function incrementWatchersCount(current, count) { + do { + current.$$watchersCount += count; + } while ((current = current.$parent)); + } + + function decrementListenerCount(current, count, name) { + do { + current.$$listenerCount[name] -= count; + + if (current.$$listenerCount[name] === 0) { + delete current.$$listenerCount[name]; + } + } while ((current = current.$parent)); + } + + /** + * function used as an initial value for watchers. + * because it's unique we can easily tell it apart from other values + */ + function initWatchVal() {} + + function flushApplyAsync() { + while (applyAsyncQueue.length) { + try { + applyAsyncQueue.shift()(); + } catch (e) { + $exceptionHandler(e); + } + } + applyAsyncId = null; + } + + function scheduleApplyAsync() { + if (applyAsyncId === null) { + applyAsyncId = $browser.defer(function() { + $rootScope.$apply(flushApplyAsync); + }, null, '$applyAsync'); + } + } + }]; +} + +/** + * @ngdoc service + * @name $rootElement + * + * @description + * The root element of AngularJS application. This is either the element where {@link + * ng.directive:ngApp ngApp} was declared or the element passed into + * {@link angular.bootstrap}. The element represents the root element of application. It is also the + * location where the application's {@link auto.$injector $injector} service gets + * published, and can be retrieved using `$rootElement.injector()`. + */ + + +// the implementation is in angular.bootstrap + +/** + * @this + * @description + * Private service to sanitize uris for links and images. Used by $compile and $sanitize. + */ +function $$SanitizeUriProvider() { + + var aHrefSanitizationTrustedUrlList = /^\s*(https?|s?ftp|mailto|tel|file):/, + imgSrcSanitizationTrustedUrlList = /^\s*((https?|ftp|file|blob):|data:image\/)/; + + /** + * @description + * 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 anchor links. + * + * Any url due to be assigned to an `a[href]` attribute via interpolation is marked as requiring + * the $sce.URL security context. When interpolation occurs a call is made to `$sce.trustAsUrl(url)` + * which in turn may call `$$sanitizeUri(url, isMedia)` to sanitize the potentially malicious URL. + * + * If the URL matches the `aHrefSanitizationTrustedUrlList` regular expression, it is returned unchanged. + * + * If there is no match the URL is returned prefixed with `'unsafe:'` to ensure that when it is written + * to the DOM it is inactive and potentially malicious code will not be executed. + * + * @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.aHrefSanitizationTrustedUrlList = function(regexp) { + if (isDefined(regexp)) { + aHrefSanitizationTrustedUrlList = regexp; + return this; + } + return aHrefSanitizationTrustedUrlList; + }; + + + /** + * @description + * 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 image src links. + * + * Any URL due to be assigned to an `img[src]` attribute via interpolation is marked as requiring + * the $sce.MEDIA_URL security context. When interpolation occurs a call is made to + * `$sce.trustAsMediaUrl(url)` which in turn may call `$$sanitizeUri(url, isMedia)` to sanitize + * the potentially malicious URL. + * + * If the URL matches the `imgSrcSanitizationTrustedUrlList` regular expression, it is returned + * unchanged. + * + * If there is no match the URL is returned prefixed with `'unsafe:'` to ensure that when it is written + * to the DOM it is inactive and potentially malicious code will not be executed. + * + * @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.imgSrcSanitizationTrustedUrlList = function(regexp) { + if (isDefined(regexp)) { + imgSrcSanitizationTrustedUrlList = regexp; + return this; + } + return imgSrcSanitizationTrustedUrlList; + }; + + this.$get = function() { + 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 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. + +var UNDERSCORE_LOWERCASE_REGEXP = /_([a-z])/g; + +function snakeToCamel(name) { + return name + .replace(UNDERSCORE_LOWERCASE_REGEXP, fnCamelCaseReplace); +} + +function adjustMatcher(matcher) { + if (matcher === 'self') { + return matcher; + } else if (isString(matcher)) { + // Strings match exactly except for 2 wildcards - '*' and '**'. + // '*' matches any character except those from the set ':/.?&'. + // '**' matches any character (like .* in a RegExp). + // More than 2 *'s raises an error as it's ill defined. + if (matcher.indexOf('***') > -1) { + throw $sceMinErr('iwcard', + 'Illegal sequence *** in string matcher. String: {0}', matcher); + } + matcher = escapeForRegexp(matcher). + replace(/\\\*\\\*/g, '.*'). + replace(/\\\*/g, '[^:/.?&;]*'); + return new RegExp('^' + matcher + '$'); + } else if (isRegExp(matcher)) { + // The only other type of matcher allowed is a Regexp. + // Match entire URL / disallow partial matches. + // Flags are reset (i.e. no global, ignoreCase or multiline) + return new RegExp('^' + matcher.source + '$'); + } else { + throw $sceMinErr('imatcher', + 'Matchers may only be "self", string patterns or RegExp objects'); + } +} + + +function adjustMatchers(matchers) { + var adjustedMatchers = []; + if (isDefined(matchers)) { + forEach(matchers, function(matcher) { + adjustedMatchers.push(adjustMatcher(matcher)); + }); + } + return adjustedMatchers; +} + + +/** + * @ngdoc service + * @name $sceDelegate + * @kind function + * + * @description + * + * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict + * Contextual Escaping (SCE)} services to AngularJS. + * + * For an overview of this service and the functionnality it provides in AngularJS, see the main + * page for {@link ng.$sce SCE}. The current page is targeted for developers who need to alter how + * SCE works in their application, which shouldn't be needed in most cases. + * + *
+ * 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 + * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things + * work because `$sce` delegates to `$sceDelegate` for these operations. + * + * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. + * + * 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 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}, 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 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. + * - 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.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 trustedResourceUrlList = ['self'], + bannedResourceUrlList = []; + + /** + * @ngdoc method + * @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. + * + * @return {Array} The currently set trusted resource URL array. + * + * @description + * Sets/Gets the list trusted of resource URLs. + * + * The **default value** when no `trustedResourceUrlList` has been explicitly set is `['self']` + * allowing only same origin resource requests. + * + *
+ * **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.trustedResourceUrlList = function(value) { + if (arguments.length) { + trustedResourceUrlList = adjustMatchers(value); + } + return trustedResourceUrlList; + }; + + /** + * @ngdoc method + * @name $sceDelegateProvider#resourceUrlWhitelist + * @kind function + * + * @deprecated + * sinceVersion="1.8.1" + * + * 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 + * + * @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. + * + * @return {Array} The currently set `bannedResourceUrlList` array. + * + * @description + * 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.bannedResourceUrlList = function(value) { + if (arguments.length) { + bannedResourceUrlList = adjustMatchers(value); + } + return bannedResourceUrlList; + }; + + /** + * @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.'); + }; + + if ($injector.has('$sanitize')) { + htmlSanitizer = $injector.get('$sanitize'); + } + + + function matchUrl(matcher, parsedUrl) { + if (matcher === 'self') { + return urlIsSameOrigin(parsedUrl) || urlIsSameOriginAsBaseUrl(parsedUrl); + } else { + // definitely a regex. See adjustMatchers() + return !!matcher.exec(parsedUrl.href); + } + } + + function isResourceUrlAllowedByPolicy(url) { + var parsedUrl = urlResolve(url.toString()); + var i, n, allowed = false; + // 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 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; + } + } + } + return allowed; + } + + function generateHolderType(Base) { + var holderType = function TrustedValueHolderType(trustedValue) { + this.$$unwrapTrustedValue = function() { + return trustedValue; + }; + }; + if (Base) { + holderType.prototype = new Base(); + } + holderType.prototype.valueOf = function sceValueOf() { + return this.$$unwrapTrustedValue(); + }; + holderType.prototype.toString = function sceToString() { + return this.$$unwrapTrustedValue().toString(); + }; + return holderType; + } + + var trustedValueHolderBase = generateHolderType(), + byType = {}; + + byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); + byType[SCE_CONTEXTS.CSS] = 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]); + + /** + * @ngdoc method + * @name $sceDelegate#trustAs + * + * @description + * 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); + if (!Constructor) { + throw $sceMinErr('icontext', + 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', + type, 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 + // mutable objects, we ensure here that the value passed in is actually a string. + if (typeof trustedValue !== 'string') { + throw $sceMinErr('itype', + 'Attempted to trust a non-string value in a content requiring a string: Context: {0}', + type); + } + return new Constructor(trustedValue); + } + + /** + * @ngdoc method + * @name $sceDelegate#valueOf + * + * @description + * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs + * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link + * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. + * + * If the passed parameter is not a value that had been returned by {@link + * 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. + * @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. + */ + function valueOf(maybeTrusted) { + if (maybeTrusted instanceof trustedValueHolderBase) { + return maybeTrusted.$$unwrapTrustedValue(); + } else { + return maybeTrusted; + } + } + + /** + * @ngdoc method + * @name $sceDelegate#getTrusted + * + * @description + * 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 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, 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 || 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 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 { + throw $sceMinErr('insecurl', + 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', + 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.'); + } + + return { trustAs: trustAs, + getTrusted: getTrusted, + valueOf: valueOf }; + }]; +} + + +/** + * @ngdoc provider + * @name $sceProvider + * @this + * + * @description + * + * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. + * - enable/disable Strict Contextual Escaping (SCE) in a module + * - override the default implementation with a custom delegate + * + * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. + */ + +/** + * @ngdoc service + * @name $sce + * @kind function + * + * @description + * + * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. + * + * ## 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 + * + * 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. + * + * 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. + * + * As of version 1.2, AngularJS ships with SCE enabled by default. + * + * ### 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, 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. + * + * How would you ensure that every place that used these types of bindings was bound to a value that + * was sanitized by your library (or returned as safe for rendering by your server?) How can you + * 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, 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 + * build the trusted versions of your values. + * + * ### 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. 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 || ''); + * }); + * }; + * }]; + * ``` + * + * ### 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, 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 add them to the {@link ng.$sceDelegateProvider#trustedResourceUrlList + * trustedResourceUrlList} or {@link ng.$sce#trustAsResourceUrl wrap them} into trusted values. + * + * *Please note*: + * 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 apply in addition to this and may further restrict whether the template is successfully + * loaded. This means that without the right CORS policy, loading templates from a different domain + * won't work on all browsers. Also, loading templates from `file://` URL does not work on some + * browsers. + * + * ### 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 (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#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? + * + * | 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. 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.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. | + * + * + *
+ * 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: + * + * - **'self'** + * - The special **string**, `'self'`, can be used to match against all URLs of the **same + * domain** as the application document using the **same protocol**. + * - **String** (except the special value `'self'`) + * - The string is matched against the full *normalized / absolute URL* of the resource + * being tested (substring matches are not good enough.) + * - 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 + * for matching resource URL lists. + * - `**`: matches zero or more occurrences of *any* character. As such, it's not + * 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.) 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 + * 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 + * 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 + * present on the RegExp (such as multiline, global, ignoreCase) are ignored. + * - If you are generating your JavaScript from some other templating engine (not + * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), + * 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 + * [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 + * Closure library's [goog.string.regExpEscape(s)]( + * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). + * + * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. + * + * ### Show me an example using SCE. + * + * + * + *
+ *

+ * 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.'); + * }); + * }); + * + *
+ * + * + * + * ## Can I disable SCE completely? + * + * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits + * 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. 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 or libraries. + * $sceProvider.enabled(false); + * }); + * ``` + * + */ + +function $SceProvider() { + var enabled = true; + + /** + * @ngdoc method + * @name $sceProvider#enabled + * @kind function + * + * @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) { + if (arguments.length) { + enabled = !!value; + } + return enabled; + }; + + + /* Design notes on the default implementation for SCE. + * + * The API contract for the SCE delegate + * ------------------------------------- + * The SCE delegate object must provide the following 3 methods: + * + * - trustAs(contextEnum, value) + * This method is used to tell the SCE service that the provided value is OK to use in the + * contexts specified by contextEnum. It must return an object that will be accepted by + * getTrusted() for a compatible contextEnum and return this value. + * + * - valueOf(value) + * For values that were not produced by trustAs(), return them as is. For values that were + * produced by trustAs(), return the corresponding input value to trustAs. Basically, if + * trustAs is wrapping the given values into some type, this operation unwraps it when given + * such a value. + * + * - getTrusted(contextEnum, value) + * 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 + * opaque or wrapped in some holder object. That happens to be an implementation detail. For + * instance, an implementation could maintain a registry of all trusted objects by context. In + * such a case, trustAs() would return the same object that was passed in. getTrusted() would + * return the same object passed in if it was found in the registry under a compatible context or + * throw an exception otherwise. An implementation might only wrap values some of the time based + * on some criteria. getTrusted() might return a value and not throw an exception for special + * constants or objects even if not wrapped. All such implementations fulfill this contract. + * + * + * A note on the inheritance model for SCE contexts + * ------------------------------------------------ + * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This + * is purely an implementation details. + * + * The contract is simply this: + * + * 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. + */ + + 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 && msie < 8) { + throw $sceMinErr('iequirks', + '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.'); + } - parent.salutation = "Hello"; - expect(child.salutation).toEqual('Hello'); + var sce = shallowCopy(SCE_CONTEXTS); - child.salutation = "Welcome"; - expect(child.salutation).toEqual('Welcome'); - 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. - * + /** + * @ngdoc method + * @name $sce#isEnabled + * @kind function * - * @param {Object.=} providers Map of service factory which need to be - * provided for the current scope. Defaults to {@link ng}. - * @param {Object.=} instanceCache Provides pre-instantiated services which should - * append/override services provided by `providers`. This is handy - * when unit-testing and having the need to override a default - * service. - * @returns {Object} Newly created scope. + * @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. */ - function Scope() { - this.$id = nextUid(); - this.$$phase = this.$parent = this.$$watchers = - this.$$nextSibling = this.$$prevSibling = - this.$$childHead = this.$$childTail = null; - this.$root = this; - this.$$destroyed = false; - this.$$listeners = {}; - this.$$listenerCount = {}; - this.$$isolateBindings = null; + sce.isEnabled = function() { + return enabled; + }; + sce.trustAs = $sceDelegate.trustAs; + sce.getTrusted = $sceDelegate.getTrusted; + sce.valueOf = $sceDelegate.valueOf; + + if (!enabled) { + sce.trustAs = sce.getTrusted = function(type, value) { return value; }; + sce.valueOf = identity; } /** - * @ngdoc property - * @name $rootScope.Scope#$id + * @ngdoc method + * @name $sce#parseAs * * @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 - * @kind function - * - * @description - * Creates a new child {@link ng.$rootScope.Scope scope}. - * - * 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 - * thus stop participating in model change detection and listener notification by invoking. - * - * @param {boolean} isolate If true, then the scope does not prototypically inherit from the - * parent scope. The scope is isolated, as it can not see parent scope properties. - * 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, parent) { - var child; - - parent = parent || this; - - if (isolate) { - child = new Scope(); - child.$root = this.$root; - } else { - // 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 { - 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 - * @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.) - * - 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). 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. - * - 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.) - * - * After a watcher is registered with the scope, the `listener` fn is called asynchronously - * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the - * watcher. In rare cases, this is undesirable because the listener is called when the result - * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you - * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the - * listener was called due to initialization. - * - * - * - * # Example - * ```js - // let's assume that scope was dependency injected as the $rootScope - var scope = $rootScope; - scope.name = 'misko'; - scope.counter = 0; - - expect(scope.counter).toEqual(0); - scope.$watch('name', function(newValue, oldValue) { - scope.counter = scope.counter + 1; - }); - expect(scope.counter).toEqual(0); - - scope.$digest(); - // the listener is always called during the first $digest loop after it was registered - expect(scope.counter).toEqual(1); - - 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 function as a watchExpression - var food; - scope.foodCounter = 0; - expect(scope.foodCounter).toEqual(0); - scope.$watch( - // This function returns the value being watched. It is called for each turn of the $digest loop - function() { return food; }, - // 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 - scope.foodCounter = scope.foodCounter + 1; - } - } - ); - // No digest has been run so the counter will be zero - expect(scope.foodCounter).toEqual(0); - - // Run the digest but since food has not changed count will still be zero - scope.$digest(); - expect(scope.foodCounter).toEqual(0); - - // Update food and run digest. Now the counter will increment - food = 'cheeseburger'; - scope.$digest(); - expect(scope.foodCounter).toEqual(1); - - * ``` - * - * - * - * @param {(function()|string)} watchExpression Expression that is evaluated on each - * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers - * a call to the `listener`. - * - * - `string`: Evaluated as {@link guide/expression expression} - * - `function(scope)`: called with current `scope` as a parameter. - * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value - * of `watchExpression` changes. - * - * - `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 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) { - var get = $parse(watchExp); - - if (get.$$watchDelegate) { - return get.$$watchDelegate(this, listener, objectEquality, get); - } - var scope = this, - array = scope.$$watchers, - watcher = { - fn: listener, - last: initWatchVal, - get: get, - exp: watchExp, - eq: !!objectEquality - }; - - lastDirtyWatch = null; + * 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 SCE context in which this result will be used. + * @param {string} expression String expression to compile. + * @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`. + */ + sce.parseAs = function sceParseAs(type, expr) { + var parsed = $parse(expr); + if (parsed.literal && parsed.constant) { + return parsed; + } else { + return $parse(expr, function(value) { + return sce.getTrusted(type, value); + }); + } + }; - if (!isFunction(listener)) { - watcher.fn = noop; - } + /** + * @ngdoc method + * @name $sce#trustAs + * + * @description + * 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 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. + */ - if (!array) { - array = scope.$$watchers = []; - } - // we use unshift since we use a while loop in $digest for speed. - // the while loop reads in reverse order. - array.unshift(watcher); + /** + * @ngdoc method + * @name $sce#trustAsHtml + * + * @description + * Shorthand method. `$sce.trustAsHtml(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`} + * + * @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`). + */ - return function deregisterWatch() { - arrayRemove(array, watcher); - lastDirtyWatch = null; - }; - }, + /** + * @ngdoc method + * @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 $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 standard $watch operation and are examined on every - * call to $digest() to see if any items changes. - * - 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; + /** + * @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 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. + */ - 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; - }; - } + /** + * @ngdoc method + * @name $sce#trustAsResourceUrl + * + * @description + * Shorthand method. `$sce.trustAsResourceUrl(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`} + * + * @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, ...) + */ - 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); - }); - } + /** + * @ngdoc method + * @name $sce#trustAsJs + * + * @description + * Shorthand method. `$sce.trustAsJs(value)` → + * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`} + * + * @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. + */ - forEach(watchExpressions, function(expr, i) { - var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) { - newValues[i] = value; - oldValues[i] = oldValue; - if (!changeReactionScheduled) { - changeReactionScheduled = true; - self.$evalAsync(watchGroupAction); - } - }); - deregisterFns.push(unwatchFn); - }); + /** + * @ngdoc method + * @name $sce#getTrusted + * + * @description + * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such, + * 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. + */ - function watchGroupAction() { - changeReactionScheduled = false; + /** + * @ngdoc method + * @name $sce#getTrustedHtml + * + * @description + * Shorthand method. `$sce.getTrustedHtml(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @return {*} The return value of `$sce.getTrusted($sce.HTML, value)` + */ - if (firstRun) { - firstRun = false; - listener(newValues, newValues, self); - } else { - listener(newValues, oldValues, self); - } - } + /** + * @ngdoc method + * @name $sce#getTrustedCss + * + * @description + * Shorthand method. `$sce.getTrustedCss(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @return {*} The return value of `$sce.getTrusted($sce.CSS, value)` + */ - return function deregisterWatchGroup() { - while (deregisterFns.length) { - deregisterFns.shift()(); - } - }; - }, + /** + * @ngdoc method + * @name $sce#getTrustedUrl + * + * @description + * Shorthand method. `$sce.getTrustedUrl(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @return {*} The return value of `$sce.getTrusted($sce.URL, value)` + */ + /** + * @ngdoc method + * @name $sce#getTrustedResourceUrl + * + * @description + * Shorthand method. `$sce.getTrustedResourceUrl(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`} + * + * @param {*} value The value to pass to `$sceDelegate.getTrusted`. + * @return {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)` + */ - /** - * @ngdoc method - * @name $rootScope.Scope#$watchCollection - * @kind function - * - * @description - * Shallow watches the properties of an object and fires whenever any of the properties change - * (for arrays, this implies watching the array items; for object maps, this implies watching - * the properties). If a change is detected, the `listener` callback is fired. - * - * - The `obj` collection is observed via standard $watch operation and is examined on every - * call to $digest() to see if any items have been added, removed, or moved. - * - The `listener` is called whenever anything within the `obj` has changed. Examples include - * adding, removing, and moving items belonging to an object or array. - * - * - * # Example - * ```js - $scope.names = ['igor', 'matias', 'misko', 'james']; - $scope.dataCount = 4; + /** + * @ngdoc method + * @name $sce#getTrustedJs + * + * @description + * Shorthand method. `$sce.getTrustedJs(value)` → + * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`} + * + * @param {*} value The value to pass to `$sce.getTrusted`. + * @return {*} The return value of `$sce.getTrusted($sce.JS, value)` + */ - $scope.$watchCollection('names', function(newNames, oldNames) { - $scope.dataCount = newNames.length; - }); + /** + * @ngdoc method + * @name $sce#parseAsHtml + * + * @description + * Shorthand method. `$sce.parseAsHtml(expression string)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`} + * + * @param {string} expression String expression to compile. + * @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`. + */ - expect($scope.dataCount).toEqual(4); - $scope.$digest(); + /** + * @ngdoc method + * @name $sce#parseAsCss + * + * @description + * Shorthand method. `$sce.parseAsCss(value)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`} + * + * @param {string} expression String expression to compile. + * @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`. + */ - //still at 4 ... no changes - expect($scope.dataCount).toEqual(4); + /** + * @ngdoc method + * @name $sce#parseAsUrl + * + * @description + * Shorthand method. `$sce.parseAsUrl(value)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`} + * + * @param {string} expression String expression to compile. + * @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`. + */ - $scope.names.pop(); - $scope.$digest(); + /** + * @ngdoc method + * @name $sce#parseAsResourceUrl + * + * @description + * Shorthand method. `$sce.parseAsResourceUrl(value)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`} + * + * @param {string} expression String expression to compile. + * @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`. + */ - //now there's been a change - expect($scope.dataCount).toEqual(3); - * ``` - * - * - * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The - * expression value should evaluate to an object or an array which is observed on each - * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the - * collection will trigger a call to the `listener`. - * - * @param {function(newCollection, oldCollection, scope)} listener a callback function called - * when a change is detected. - * - The `newCollection` object is the newly modified data obtained from the `obj` expression - * - The `oldCollection` object is a copy of the former collection data. - * Due to performance considerations, the`oldCollection` value is computed only if the - * `listener` function declares two or more arguments. - * - The `scope` argument refers to the current scope. - * - * @returns {function()} Returns a de-registration function for this listener. When the - * de-registration function is executed, the internal watch operation is terminated. - */ - $watchCollection: function(obj, listener) { - $watchCollectionInterceptor.$stateful = true; + /** + * @ngdoc method + * @name $sce#parseAsJs + * + * @description + * Shorthand method. `$sce.parseAsJs(value)` → + * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`} + * + * @param {string} expression String expression to compile. + * @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`. + */ - var self = this; - // the current value, updated on each dirty-check run - var newValue; - // a shallow copy of the newValue from the last dirty-check run, - // updated to match newValue during dirty-check run - var oldValue; - // a shallow copy of the newValue from when the last change happened - var veryOldValue; - // only track veryOldValue if the listener is asking for it - var trackVeryOldValue = (listener.length > 1); - var changeDetected = 0; - var changeDetector = $parse(obj, $watchCollectionInterceptor); - var internalArray = []; - var internalObject = {}; - var initRun = true; - var oldLength = 0; + // Shorthand delegations. + var parse = sce.parseAs, + getTrusted = sce.getTrusted, + trustAs = sce.trustAs; - function $watchCollectionInterceptor(_value) { - newValue = _value; - var newLength, key, bothNaN, newItem, oldItem; + forEach(SCE_CONTEXTS, function(enumValue, name) { + var lName = lowercase(name); + sce[snakeToCamel('parse_as_' + lName)] = function(expr) { + return parse(enumValue, expr); + }; + sce[snakeToCamel('get_trusted_' + lName)] = function(value) { + return getTrusted(enumValue, value); + }; + sce[snakeToCamel('trust_as_' + lName)] = function(value) { + return trustAs(enumValue, value); + }; + }); - // If the new value is undefined, then return undefined as the watch may be a one-time watch - if (isUndefined(newValue)) return; + return sce; + }]; +} - if (!isObject(newValue)) { // if primitive - if (oldValue !== newValue) { - oldValue = newValue; - changeDetected++; - } - } else if (isArrayLike(newValue)) { - if (oldValue !== internalArray) { - // we are transitioning from something which was not an array into array. - oldValue = internalArray; - oldLength = oldValue.length = 0; - changeDetected++; - } +/* exported $SnifferProvider */ - newLength = newValue.length; +/** + * !!! 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} transitions Does the browser support CSS transition events ? + * @property {boolean} animations Does the browser support CSS animation events ? + * + * @description + * This is very simple implementation of testing browser's features. + */ +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 = + toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), + boxee = /Boxee/i.test(($window.navigator || {}).userAgent), + document = $document[0] || {}, + bodyStyle = document.body && document.body.style, + transitions = false, + animations = false; - if (oldLength !== newLength) { - // if lengths do not match we need to trigger change notification - changeDetected++; - oldValue.length = oldLength = newLength; - } - // copy the items to oldValue and look for changes. - for (var i = 0; i < newLength; i++) { - oldItem = oldValue[i]; - newItem = newValue[i]; + if (bodyStyle) { + // 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); + } - bothNaN = (oldItem !== oldItem) && (newItem !== newItem); - if (!bothNaN && (oldItem !== newItem)) { - changeDetected++; - oldValue[i] = newItem; - } - } - } else { - if (oldValue !== internalObject) { - // we are transitioning from something which was not an object into object. - oldValue = internalObject = {}; - oldLength = 0; - changeDetected++; - } - // copy the items to oldValue and look for changes. - newLength = 0; - for (key in newValue) { - if (newValue.hasOwnProperty(key)) { - newLength++; - newItem = newValue[key]; - oldItem = oldValue[key]; - if (key in oldValue) { - bothNaN = (oldItem !== oldItem) && (newItem !== newItem); - if (!bothNaN && (oldItem !== newItem)) { - changeDetected++; - oldValue[key] = newItem; - } - } else { - oldLength++; - oldValue[key] = newItem; - changeDetected++; - } - } - } - if (oldLength > newLength) { - // we used to have more keys, need to find them and destroy them. - changeDetected++; - for (key in oldValue) { - if (!newValue.hasOwnProperty(key)) { - oldLength--; - delete oldValue[key]; - } - } - } - } - return changeDetected; - } + return { + // Android has history.pushState, but it does not update location correctly + // so let's not use the history API at all. + // http://code.google.com/p/android/issues/detail?id=17471 + // https://github.com/angular/angular.js/issues/904 - function $watchCollectionAction() { - if (initRun) { - initRun = false; - listener(newValue, newValue, self); - } else { - listener(newValue, veryOldValue, self); - } + // 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 + 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. + // 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; - // make a copy for the next time a collection is changed - if (trackVeryOldValue) { - if (!isObject(newValue)) { - //primitive - veryOldValue = newValue; - } else if (isArrayLike(newValue)) { - veryOldValue = new Array(newValue.length); - for (var i = 0; i < newValue.length; i++) { - veryOldValue[i] = newValue[i]; - } - } else { // if object - veryOldValue = {}; - for (var key in newValue) { - if (hasOwnProperty.call(newValue, key)) { - veryOldValue[key] = newValue[key]; - } - } - } - } + if (isUndefined(eventSupport[event])) { + var divElm = document.createElement('div'); + eventSupport[event] = 'on' + event in divElm; } - return this.$watch(changeDetector, $watchCollectionAction); + return eventSupport[event]; }, + csp: csp(), + transitions: transitions, + animations: animations, + android: android + }; + }]; +} - /** - * @ngdoc method - * @name $rootScope.Scope#$digest - * @kind function - * - * @description - * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and - * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change - * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} - * until no more listeners are firing. This means that it is possible to get into an infinite - * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of - * iterations exceeds 10. - * - * Usually, you don't call `$digest()` directly in - * {@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 directive}), which will force a `$digest()`. - * - * If you want to be notified whenever `$digest()` is called, - * you can register a `watchExpression` function with - * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`. - * - * In unit tests, you may need to call `$digest()` to simulate the scope life cycle. - * - * # Example - * ```js - var scope = ...; - scope.name = 'misko'; - scope.counter = 0; - - expect(scope.counter).toEqual(0); - scope.$watch('name', function(newValue, oldValue) { - scope.counter = scope.counter + 1; - }); - expect(scope.counter).toEqual(0); +/** + * ! 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); }); +} - scope.$digest(); - // the listener is always called during the first $digest loop after it was registered - expect(scope.counter).toEqual(1); +function TaskTracker(log) { + var self = this; + var taskCounts = {}; + var taskCallbacks = []; - scope.$digest(); - // but now it will not be called unless the value changes - expect(scope.counter).toEqual(1); + var ALL_TASKS_TYPE = self.ALL_TASKS_TYPE = '$$all$$'; + var DEFAULT_TASK_TYPE = self.DEFAULT_TASK_TYPE = '$$default$$'; - scope.name = 'adam'; - scope.$digest(); - expect(scope.counter).toEqual(2); - * ``` - * - */ - $digest: function() { - var watch, value, last, - watchers, - length, - dirty, ttl = TTL, - next, current, target = this, - watchLog = [], - logIdx, logMsg, asyncTask; + /** + * 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; - beginPhase('$digest'); - // Check for changes to browser url that happened in sync before the call to $digest - $browser.$$checkUrlChange(); + /** + * 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; - 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(); - } + /** + * 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; - lastDirtyWatch = null; + function completeTask(fn, taskType) { + taskType = taskType || DEFAULT_TASK_TYPE; - do { // "while dirty" loop - dirty = false; - current = target; + try { + fn(); + } finally { + decTaskCount(taskType); - while (asyncQueue.length) { - try { - asyncTask = asyncQueue.shift(); - asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals); - } catch (e) { - $exceptionHandler(e); - } - lastDirtyWatch = null; + 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); } + } + } + } + } - traverseScopesLoop: - do { // "traverse the scopes" loop - if ((watchers = current.$$watchers)) { - // process our watches - length = watchers.length; - while (length--) { - try { - watch = watchers[length]; - // 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) && - !(watch.eq - ? equals(value, last) - : (typeof value === 'number' && typeof last === 'number' - && isNaN(value) && isNaN(last)))) { - dirty = true; - lastDirtyWatch = watch; - watch.last = watch.eq ? copy(value, null) : value; - watch.fn(value, ((last === initWatchVal) ? value : last), current); - if (ttl < 5) { - logIdx = 4 - ttl; - if (!watchLog[logIdx]) watchLog[logIdx] = []; - 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 - // have already been tested. - dirty = false; - break traverseScopesLoop; - } - } - } catch (e) { - $exceptionHandler(e); - } - } - } + function decTaskCount(taskType) { + taskType = taskType || DEFAULT_TASK_TYPE; + if (taskCounts[taskType]) { + taskCounts[taskType]--; + taskCounts[ALL_TASKS_TYPE]--; + } + } - // 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 || - (current !== target && current.$$nextSibling)))) { - while (current !== target && !(next = current.$$nextSibling)) { - current = current.$parent; - } - } - } while ((current = next)); + function getLastCallback() { + var cbInfo = taskCallbacks.pop(); + return cbInfo && cbInfo.cb; + } - // `break traverseScopesLoop;` takes us to here + 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; + } + } + } - if ((dirty || asyncQueue.length) && !(ttl--)) { - clearPhase(); - throw $rootScopeMinErr('infdig', - '{0} $digest() iterations reached. Aborting!\n' + - 'Watchers fired in the last 5 iterations: {1}', - TTL, watchLog); - } + function incTaskCount(taskType) { + taskType = taskType || DEFAULT_TASK_TYPE; + taskCounts[taskType] = (taskCounts[taskType] || 0) + 1; + taskCounts[ALL_TASKS_TYPE] = (taskCounts[ALL_TASKS_TYPE] || 0) + 1; + } - } while (dirty || asyncQueue.length); + function notifyWhenNoPendingTasks(callback, taskType) { + taskType = taskType || ALL_TASKS_TYPE; + if (!taskCounts[taskType]) { + callback(); + } else { + taskCallbacks.push({type: taskType, cb: callback}); + } + } +} - clearPhase(); +var $templateRequestMinErr = minErr('$templateRequest'); - while (postDigestQueue.length) { - try { - postDigestQueue.shift()(); - } catch (e) { - $exceptionHandler(e); +/** + * @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; - /** - * @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. - */ + return handleRequestFn; + } + ]; +} - /** - * @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 - * perform any necessary cleanup. - * - * 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. - */ - $destroy: function() { - // we can't destroy the root scope or a scope that has been already destroyed - if (this.$$destroyed) return; - var parent = this.$parent; +/** @this */ +function $$TestabilityProvider() { + this.$get = ['$rootScope', '$browser', '$location', + function($rootScope, $browser, $location) { - this.$broadcast('$destroy'); - this.$$destroyed = true; - if (this === $rootScope) return; + /** + * @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; + }; - for (var eventName in this.$$listenerCount) { - decrementListenerCount(this, this.$$listenerCount[eventName], eventName); + /** + * @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; } + } + }; - // 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 (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling; - if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling; + /** + * @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(); + }; - // 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 = {}; + /** + * @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(); + } + }; - // 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 + /** + * @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); + }; - this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead = - this.$$childTail = this.$root = this.$$watchers = null; - }, + return testability; + }]; +} - /** - * @ngdoc method - * @name $rootScope.Scope#$eval - * @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 - * expressions. - * - * # Example - * ```js - var scope = ng.$rootScope.Scope(); - scope.a = 1; - scope.b = 2; +var $timeoutMinErr = minErr('$timeout'); - expect(scope.$eval('a+b')).toEqual(3); - expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3); - * ``` - * - * @param {(string|function())=} expression An angular 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. - * @returns {*} The result of evaluating the expression. - */ - $eval: function(expr, locals) { - return $parse(expr)(this, locals); - }, +/** @this */ +function $TimeoutProvider() { + this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler', + function($rootScope, $browser, $q, $$q, $exceptionHandler) { - /** - * @ngdoc method - * @name $rootScope.Scope#$evalAsync - * @kind function - * - * @description - * Executes the expression on the current scope at a later point in time. - * - * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only - * that: - * - * - it will execute after the function that scheduled the evaluation (preferably before DOM - * rendering). - * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after - * `expression` execution. - * - * Any exceptions from the execution of the expression are forwarded to the - * {@link ng.$exceptionHandler $exceptionHandler} service. - * - * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle - * 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. - * - * - `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, 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 && !asyncQueue.length) { - $browser.defer(function() { - if (asyncQueue.length) { - $rootScope.$digest(); - } - }); - } + var deferreds = {}; - asyncQueue.push({scope: this, expression: expr, locals: locals}); - }, - $$postDigest: function(fn) { - postDigestQueue.push(fn); - }, + /** + * @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) { + if (!isFunction(fn)) { + invokeApply = delay; + delay = fn; + fn = noop; + } - /** - * @ngdoc method - * @name $rootScope.Scope#$apply - * @kind function - * - * @description - * `$apply()` is used to execute an expression in angular from outside of the angular - * 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 - * cycle of {@link ng.$exceptionHandler exception handling}, - * {@link ng.$rootScope.Scope#$digest executing watches}. - * - * ## Life cycle - * - * # Pseudo-Code of `$apply()` - * ```js - function $apply(expr) { - try { - return $eval(expr); - } catch (e) { - $exceptionHandler(e); - } finally { - $root.$digest(); - } - } - * ``` - * - * - * Scope's `$apply()` method transitions through the following stages: - * - * 1. The {@link guide/expression expression} is executed using the - * {@link ng.$rootScope.Scope#$eval $eval()} method. - * 2. Any exceptions from the execution of the expression are forwarded to the - * {@link ng.$exceptionHandler $exceptionHandler} service. - * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the - * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method. - * - * - * @param {(string|function())=} exp An angular 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. - * - * @returns {*} The result of evaluating the expression. - */ - $apply: function(expr) { + var args = sliceArgs(arguments, 3), + skipApply = (isDefined(invokeApply) && !invokeApply), + deferred = (skipApply ? $$q : $q).defer(), + promise = deferred.promise, + timeoutId; + + timeoutId = $browser.defer(function() { try { - beginPhase('$apply'); - return this.$eval(expr); + deferred.resolve(fn.apply(null, args)); } catch (e) { + deferred.reject(e); $exceptionHandler(e); } finally { - clearPhase(); - try { - $rootScope.$digest(); - } catch (e) { - $exceptionHandler(e); - throw e; - } + delete deferreds[promise.$$timeoutId]; } - }, - /** - * @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 angular 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; - expr && applyAsyncQueue.push($applyAsyncExpression); - scheduleApplyAsync(); + if (!skipApply) $rootScope.$apply(); + }, delay, '$timeout'); + + promise.$$timeoutId = timeoutId; + deferreds[timeoutId] = deferred; + + return promise; + } + + + /** + * @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) return false; - function $applyAsyncExpression() { - scope.$eval(expr); - } - }, + if (!promise.hasOwnProperty('$$timeoutId')) { + throw $timeoutMinErr('badprom', + '`$timeout.cancel()` called with a promise that was not generated by `$timeout()`.'); + } - /** - * @ngdoc method - * @name $rootScope.Scope#$on - * @kind function - * - * @description - * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for - * discussion of event life cycle. - * - * The event listener function format is: `function(event, args...)`. The `event` object - * passed into the listener has the following attributes: - * - * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or - * `$broadcast`-ed. - * - `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). - * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag - * to true. - * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called. - * - * @param {string} name Event name to listen on. - * @param {function(event, ...args)} listener Function to call when the event is emitted. - * @returns {function()} Returns a deregistration function for this listener. - */ - $on: function(name, listener) { - var namedListeners = this.$$listeners[name]; - if (!namedListeners) { - this.$$listeners[name] = namedListeners = []; - } - namedListeners.push(listener); + if (!deferreds.hasOwnProperty(promise.$$timeoutId)) return false; - var current = this; - do { - if (!current.$$listenerCount[name]) { - current.$$listenerCount[name] = 0; - } - current.$$listenerCount[name]++; - } while ((current = current.$parent)); + var id = promise.$$timeoutId; + var deferred = deferreds[id]; - var self = this; - return function() { - var indexOfListener = namedListeners.indexOf(listener); - if (indexOfListener !== -1) { - namedListeners[indexOfListener] = null; - decrementListenerCount(self, 1, name); - } - }; - }, + // Timeout cancels should not report an unhandled promise. + markQExceptionHandled(deferred.promise); + deferred.reject('canceled'); + delete deferreds[id]; + return $browser.defer.cancel(id); + }; - /** - * @ngdoc method - * @name $rootScope.Scope#$emit - * @kind function - * - * @description - * Dispatches an event `name` upwards through the scope hierarchy notifying the - * registered {@link ng.$rootScope.Scope#$on} listeners. - * - * The event life cycle starts at the scope on which `$emit` was called. All - * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get - * notified. Afterwards, the event traverses upwards toward the root scope and calls all - * registered listeners along the way. The event will stop propagating if one of the listeners - * cancels it. - * - * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed - * onto the {@link ng.$exceptionHandler $exceptionHandler} service. - * - * @param {string} name Event name to emit. - * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. - * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}). - */ - $emit: function(name, args) { - var empty = [], - namedListeners, - scope = this, - stopPropagation = false, - event = { - name: name, - targetScope: scope, - stopPropagation: function() {stopPropagation = true;}, - preventDefault: function() { - event.defaultPrevented = true; - }, - defaultPrevented: false - }, - listenerArgs = concat([event], arguments, 1), - i, length; + return timeout; + }]; +} - do { - namedListeners = scope.$$listeners[name] || empty; - event.currentScope = scope; - for (i = 0, length = namedListeners.length; i < length; i++) { +// NOTE: The usage of window and document instead of $window and $document here is +// deliberate. This service depends on the specific behavior of anchor nodes created by the +// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and +// cause us to break tests. In addition, when the browser resolves a URL for XHR, it +// 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 = window.document.createElement('a'); +var originUrl = urlResolve(window.location.href); +var baseUrlParsingNode; - // if listeners were deregistered, defragment the array - if (!namedListeners[i]) { - namedListeners.splice(i, 1); - i--; - length--; - continue; - } - try { - //allow all listeners attached to the current scope to run - namedListeners[i].apply(null, listenerArgs); - } catch (e) { - $exceptionHandler(e); - } - } - //if any listener on the current scope stops propagation, prevent bubbling - if (stopPropagation) { - event.currentScope = null; - return event; - } - //traverse upwards - scope = scope.$parent; - } while (scope); +urlParsingNode.href = 'http://[::1]'; - event.currentScope = null; +// 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]'; - return event; - }, +/** + * + * Implementation Notes for non-IE browsers + * ---------------------------------------- + * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, + * results both in the normalizing and parsing of the URL. Normalizing means that a relative + * 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+ etc. See + * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * + * Implementation Notes for IE + * --------------------------- + * 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. + * + * References: + * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement + * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * http://url.spec.whatwg.org/#urlutils + * https://github.com/angular/angular.js/pull/2902 + * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ + * + * @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 | + * |---------------|------------------------------------------------------------------------| + * | href | A normalized version of the provided URL if it was not an absolute URL | + * | 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 "/" | + * + */ +function urlResolve(url) { + if (!isString(url)) return url; + var href = url; - /** - * @ngdoc method - * @name $rootScope.Scope#$broadcast - * @kind function - * - * @description - * Dispatches an event `name` downwards to all child scopes (and their children) notifying the - * registered {@link ng.$rootScope.Scope#$on} listeners. - * - * The event life cycle starts at the scope on which `$broadcast` was called. All - * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get - * notified. Afterwards, the event propagates to all direct and indirect scopes of the current - * scope and calls all registered listeners along the way. The event cannot be canceled. - * - * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed - * onto the {@link ng.$exceptionHandler $exceptionHandler} service. - * - * @param {string} name Event name to broadcast. - * @param {...*} args Optional one or more arguments which will be passed onto the event listeners. - * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on} - */ - $broadcast: function(name, args) { - var target = this, - current = target, - next = target, - event = { - name: name, - targetScope: target, - preventDefault: function() { - event.defaultPrevented = true; - }, - defaultPrevented: false - }; + // 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); + href = urlParsingNode.href; + } - if (!target.$$listenerCount[name]) return event; + urlParsingNode.setAttribute('href', href); + + 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: hostname, + port: urlParsingNode.port, + pathname: (urlParsingNode.pathname.charAt(0) === '/') + ? urlParsingNode.pathname + : '/' + urlParsingNode.pathname + }; +} + +/** + * 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) { + return urlsAreSameOrigin(requestUrl, originUrl); +} + +/** + * Parse a request URL and determine whether it is same-origin as the current document base URL. + * + * Note: The base URL is usually the same as the document location (`location.href`) but can + * be overriden by using the `` tag. + * + * @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. + * + * @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)); + }; +} - var listenerArgs = concat([event], arguments, 1), - listeners, i, length; +/** + * 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); - //down while you can, then up and next sibling or up and next sibling until back at root - while ((current = next)) { - event.currentScope = current; - listeners = current.$$listeners[name] || []; - for (i = 0, length = listeners.length; i < length; i++) { - // if listeners were deregistered, defragment the array - if (!listeners[i]) { - listeners.splice(i, 1); - i--; - length--; - continue; - } + return (url1.protocol === url2.protocol && + url1.host === url2.host); +} - try { - listeners[i].apply(null, listenerArgs); - } catch (e) { - $exceptionHandler(e); - } - } +/** + * Returns the current document base URL. + * @returns {string} + */ +function getBaseUrl() { + if (window.document.baseURI) { + return window.document.baseURI; + } - // 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 $digest - // (though it differs due to having the extra check for $$listenerCount) - if (!(next = ((current.$$listenerCount[name] && current.$$childHead) || - (current !== target && current.$$nextSibling)))) { - while (current !== target && !(next = current.$$nextSibling)) { - current = current.$parent; - } - } - } + // `document.baseURI` is available everywhere except IE + if (!baseUrlParsingNode) { + baseUrlParsingNode = window.document.createElement('a'); + baseUrlParsingNode.href = '.'; - event.currentScope = null; - return event; - } - }; + // 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; +} - var $rootScope = new Scope(); +/** + * @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() { + element(by.model('greeting')).sendKeys('Hello, E2E Tests'); + // If we click the button it will block the test runner + // element(':button').click(); + }); + +
+ */ +function $WindowProvider() { + this.$get = valueFn(window); +} - //The internal queues. Expose them on the $rootScope for debugging/testing purposes. - var asyncQueue = $rootScope.$$asyncQueue = []; - var postDigestQueue = $rootScope.$$postDigestQueue = []; - var applyAsyncQueue = $rootScope.$$applyAsyncQueue = []; +/** + * @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 = ''; - return $rootScope; + function safeGetCookie(rawDocument) { + try { + return rawDocument.cookie || ''; + } catch (e) { + return ''; + } + } + function safeDecodeURIComponent(str) { + try { + return decodeURIComponent(str); + } catch (e) { + return str; + } + } - function beginPhase(phase) { - if ($rootScope.$$phase) { - throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase); + 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)); + } + } } - - $rootScope.$$phase = phase; } + return lastCookies; + }; +} - function clearPhase() { - $rootScope.$$phase = null; - } +$$CookieReader.$inject = ['$document']; +/** @this */ +function $$CookieReaderProvider() { + this.$get = $$CookieReader; +} - function decrementListenerCount(current, count, name) { - do { - current.$$listenerCount[name] -= count; +/* global currencyFilter: true, + dateFilter: true, + filterFilter: true, + jsonFilter: true, + limitToFilter: true, + lowercaseFilter: true, + numberFilter: true, + orderByFilter: true, + uppercaseFilter: true, + */ - if (current.$$listenerCount[name] === 0) { - delete current.$$listenerCount[name]; - } - } while ((current = current.$parent)); - } +/** + * @ngdoc provider + * @name $filterProvider + * @description + * + * Filters are just functions which transform input to an output. However filters need to be + * Dependency Injected. To achieve this a filter definition consists of a factory function which is + * annotated with dependencies and is responsible for creating a filter function. + * + *
+ * **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) { + * // create a service to demonstrate injection (not always needed) + * $provide.value('greet', function(name){ + * return 'Hello ' + name + '!'; + * }); + * + * // register a filter factory which uses the + * // greet service to demonstrate DI. + * $filterProvider.register('greet', function(greet){ + * // return the filter function which uses the greet service + * // to generate salutation + * return function(text) { + * // filters need to be forgiving so check input validity + * return text && greet(text) || text; + * }; + * }); + * } + * ``` + * + * The filter function is registered with the `$injector` under the filter name suffix with + * `Filter`. + * + * ```js + * it('should be the same instance', inject( + * function($filterProvider) { + * $filterProvider.register('reverse', function(){ + * return ...; + * }); + * }, + * function($filter, reverseFilter) { + * expect($filter('reverse')).toBe(reverseFilter); + * }); + * ``` + * + * + * 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. + */ - /** - * function used as an initial value for watchers. - * because it's unique we can easily tell it apart from other values - */ - function initWatchVal() {} +/** + * @ngdoc service + * @name $filter + * @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: + * + * ```html + * {{ expression [| filter_name[:parameter_value] ... ] }} + * ``` + * + * @param {String} name Name of the filter function to retrieve + * @return {Function} the filter function + * @example + + +
+

{{ originalText }}

+

{{ filteredText }}

+
+
- function flushApplyAsync() { - while (applyAsyncQueue.length) { - try { - applyAsyncQueue.shift()(); - } catch (e) { - $exceptionHandler(e); - } - } - applyAsyncId = null; + + 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 $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)) { + var filters = {}; + forEach(name, function(filter, key) { + filters[key] = register(key, filter); + }); + return filters; + } else { + return $provide.factory(name + suffix, factory); } + } + this.register = register; - function scheduleApplyAsync() { - if (applyAsyncId === null) { - applyAsyncId = $browser.defer(function() { - $rootScope.$apply(flushApplyAsync); - }); - } - } + this.$get = ['$injector', function($injector) { + return function(name) { + return $injector.get(name + suffix); + }; }]; + + //////////////////////////////////////// + + /* global + currencyFilter: false, + dateFilter: false, + filterFilter: false, + jsonFilter: false, + limitToFilter: false, + lowercaseFilter: false, + numberFilter: false, + orderByFilter: false, + uppercaseFilter: false + */ + + register('currency', currencyFilter); + register('date', dateFilter); + register('filter', filterFilter); + register('json', jsonFilter); + register('limitTo', limitToFilter); + register('lowercase', lowercaseFilter); + register('number', numberFilter); + register('orderBy', orderByFilter); + register('uppercase', uppercaseFilter); } /** + * @ngdoc filter + * @name filter + * @kind function + * * @description - * Private service to sanitize uris for links and images. Used by $compile and $sanitize. + * 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 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 (`$` 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(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. + * + * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`. + * This is essentially strict comparison of expected and actual. + * + * - `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). + * + * + * Defaults to `false`. + * + * @param {string} [anyPropertyKey] The special property name that matches against any property. + * By default `$`. + * + * @example + + +
+ + + + + + + + +
NamePhone
{{friend.name}}{{friend.phone}}
+
+
+
+
+
+ + + + + + +
NamePhone
{{friendObj.name}}{{friendObj.phone}}
+
+ + var expectFriendNames = function(expectedNames, key) { + element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) { + arr.forEach(function(wd, i) { + expect(wd.getText()).toMatch(expectedNames[i]); + }); + }); + }; + + it('should search across all fields when filtering with a string', function() { + var searchText = element(by.model('searchText')); + searchText.clear(); + searchText.sendKeys('m'); + expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend'); + + searchText.clear(); + searchText.sendKeys('76'); + expectFriendNames(['John', 'Julie'], 'friend'); + }); + + it('should search in specific fields when filtering with a predicate object', function() { + var searchAny = element(by.model('search.$')); + searchAny.clear(); + searchAny.sendKeys('i'); + expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj'); + }); + it('should use a equal comparison when comparator is true', function() { + var searchName = element(by.model('search.name')); + var strict = element(by.model('strict')); + searchName.clear(); + searchName.sendKeys('Julie'); + strict.click(); + expectFriendNames(['Julie'], 'friendObj'); + }); + +
*/ -function $$SanitizeUriProvider() { - var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/, - imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/; - /** - * @description - * Retrieves or overrides the default regular expression that is used for whitelisting of safe - * urls during a[href] sanitization. - * - * The sanitization is a security measure aimed at prevent 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` - * 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. - * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for - * chaining otherwise. - */ - this.aHrefSanitizationWhitelist = function(regexp) { - if (isDefined(regexp)) { - aHrefSanitizationWhitelist = regexp; - return this; +function filterFilter() { + return function(array, expression, comparator, anyPropertyKey) { + if (!isArrayLike(array)) { + if (array == null) { + return array; + } else { + throw minErr('filter')('notarray', 'Expected array but received: {0}', array); + } } - return aHrefSanitizationWhitelist; - }; + anyPropertyKey = anyPropertyKey || '$'; + var expressionType = getTypeForFilter(expression); + var predicateFn; + var matchAgainstAnyProp; - /** - * @description - * Retrieves or overrides the default regular expression that is used for whitelisting of 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` - * 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. - * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for - * chaining otherwise. - */ - this.imgSrcSanitizationWhitelist = function(regexp) { - if (isDefined(regexp)) { - imgSrcSanitizationWhitelist = regexp; - return this; + switch (expressionType) { + case 'function': + 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; } - return imgSrcSanitizationWhitelist; - }; - this.$get = function() { - return function sanitizeUri(uri, isImage) { - var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist; - var normalizedVal; - normalizedVal = urlResolve(uri).href; - if (normalizedVal !== '' && !normalizedVal.match(regex)) { - return 'unsafe:' + normalizedVal; - } - return uri; - }; + return Array.prototype.filter.call(array, predicateFn); }; } -/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * - * 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 $sceMinErr = minErr('$sce'); - -var SCE_CONTEXTS = { - HTML: 'html', - CSS: 'css', - 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: 'resourceUrl', - JS: 'js' -}; - -// Helper functions follow. +// Helper functions for `filterFilter` +function createPredicateFn(expression, comparator, anyPropertyKey, matchAgainstAnyProp) { + var shouldMatchPrimitives = isObject(expression) && (anyPropertyKey in expression); + var predicateFn; -function adjustMatcher(matcher) { - if (matcher === 'self') { - return matcher; - } else if (isString(matcher)) { - // Strings match exactly except for 2 wildcards - '*' and '**'. - // '*' matches any character except those from the set ':/.?&'. - // '**' matches any character (like .* in a RegExp). - // More than 2 *'s raises an error as it's ill defined. - if (matcher.indexOf('***') > -1) { - throw $sceMinErr('iwcard', - 'Illegal sequence *** in string matcher. String: {0}', matcher); - } - matcher = escapeForRegexp(matcher). - replace('\\*\\*', '.*'). - replace('\\*', '[^:/.?&;]*'); - return new RegExp('^' + matcher + '$'); - } else if (isRegExp(matcher)) { - // The only other type of matcher allowed is a Regexp. - // Match entire URL / disallow partial matches. - // Flags are reset (i.e. no global, ignoreCase or multiline) - return new RegExp('^' + matcher.source + '$'); - } else { - throw $sceMinErr('imatcher', - 'Matchers may only be "self", string patterns or RegExp objects'); + 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 deepCompare(item, expression, comparator, anyPropertyKey, matchAgainstAnyProp); + }; + + return predicateFn; } +function deepCompare(actual, expected, comparator, anyPropertyKey, matchAgainstAnyProp, dontMatchWholeObject) { + var actualType = getTypeForFilter(actual); + var expectedType = getTypeForFilter(expected); -function adjustMatchers(matchers) { - var adjustedMatchers = []; - if (isDefined(matchers)) { - forEach(matchers, function(matcher) { - adjustedMatchers.push(adjustMatcher(matcher)); + 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); }); } - return adjustedMatchers; + + 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 service - * @name $sceDelegate + * @ngdoc filter + * @name currency * @kind function * * @description + * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default + * symbol for current locale is used. * - * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict - * Contextual Escaping (SCE)} services to AngularJS. - * - * 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 - * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things - * work because `$sce` delegates to `$sceDelegate` for these operations. + * @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. * - * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service. * - * 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} + * @example + + + +
+
+ default currency symbol ($): {{amount | currency}}
+ 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.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') { + // 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.id('currency-custom')).getText()).toBe('-USD$1,234.00'); + expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234'); + }); + +
*/ +currencyFilter.$inject = ['$locale']; +function currencyFilter($locale) { + var formats = $locale.NUMBER_FORMATS; + 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 provider - * @name $sceDelegateProvider + * @ngdoc filter + * @name number + * @kind function + * * @description + * Formats a number as text. * - * 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} + * 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. * - * For the general details about this service in Angular, read the main page for {@link ng.$sce - * Strict Contextual Escaping (SCE)}. * - * **Example**: Consider the following case. + * @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 `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). * - * - 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. - * - and you have an open redirect at `http://myapp.example.com/clickThru?...`. + * @example + + + +
+
+ Default formatting: {{val | number}}
+ No fractions: {{val | number:0}}
+ Negative number: {{-val | number:4}} +
+
+ + it('should format numbers', function() { + expect(element(by.id('number-default')).getText()).toBe('1,234.568'); + expect(element(by.binding('val | number:0')).getText()).toBe('1,235'); + expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679'); + }); + + it('should update', function() { + element(by.model('val')).clear(); + element(by.model('val')).sendKeys('3374.333'); + expect(element(by.id('number-default')).getText()).toBe('3,374.333'); + expect(element(by.binding('val | number:0')).getText()).toBe('3,374'); + expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330'); + }); + +
+ */ +numberFilter.$inject = ['$locale']; +function numberFilter($locale) { + var formats = $locale.NUMBER_FORMATS; + return function(number, fractionSize) { + + // if null or undefined pass it through + return (number == null) + ? number + : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, + fractionSize); + }; +} + +/** + * Parse a number (as a string) into three components that can be used + * for formatting the number. * - * Here is what a secure configuration for this scenario might look like: + * (Significant bits of this parse algorithm came from https://github.com/MikeMcl/big.js/) * - * ``` - * 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/**' - * ]); + * @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` * - * // The blacklist overrides the whitelist so the open redirect here is blocked. - * $sceDelegateProvider.resourceUrlBlacklist([ - * 'http://myapp.example.com/clickThru**' - * ]); - * }); - * ``` */ +function parse(numStr) { + var exponent = 0, digits, numberOfIntegerDigits; + var i, j, zeros; -function $SceDelegateProvider() { - this.SCE_CONTEXTS = SCE_CONTEXTS; + // Decimal point? + if ((numberOfIntegerDigits = numStr.indexOf(DECIMAL_SEP)) > -1) { + numStr = numStr.replace(DECIMAL_SEP, ''); + } - // Resource URLs can also be trusted by policy. - var resourceUrlWhitelist = ['self'], - resourceUrlBlacklist = []; + // 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; + } - /** - * @ngdoc method - * @name $sceDelegateProvider#resourceUrlWhitelist - * @kind 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. - * - * 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 whitelist array. - * - * The **default value** when no whitelist has been explicitly set is `['self']` allowing only - * same origin resource requests. - * - * @description - * Sets/Gets the whitelist of trusted resource URLs. - */ - this.resourceUrlWhitelist = function(value) { - if (arguments.length) { - resourceUrlWhitelist = adjustMatchers(value); + // Count the number of leading zeros. + for (i = 0; numStr.charAt(i) === ZERO_CHAR; i++) { /* empty */ } + + 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); } - return resourceUrlWhitelist; - }; + } - /** - * @ngdoc method - * @name $sceDelegateProvider#resourceUrlBlacklist - * @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. - * - * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items - * allowed in this array. - * - * The typical usage for the blacklist 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 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.) - * - * @description - * Sets/Gets the blacklist of trusted resource URLs. - */ + // 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; + } + + return { d: digits, e: exponent, i: numberOfIntegerDigits }; +} + +/** + * 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; + + // 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]; - this.resourceUrlBlacklist = function(value) { - if (arguments.length) { - resourceUrlBlacklist = adjustMatchers(value); + 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; + } + + 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]++; + } } - return resourceUrlBlacklist; - }; - this.$get = ['$injector', function($injector) { + // Pad out with zeros to get the required fraction length + for (; fractionLen < Math.max(0, fractionSize); fractionLen++) digits.push(0); - var htmlSanitizer = function htmlSanitizer(html) { - throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); - }; - if ($injector.has('$sanitize')) { - htmlSanitizer = $injector.get('$sanitize'); + // 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) { - function matchUrl(matcher, parsedUrl) { - if (matcher === 'self') { - return urlIsSameOrigin(parsedUrl); - } else { - // definitely a regex. See adjustMatchers() - return !!matcher.exec(parsedUrl.href); - } - } + if (!(isString(number) || isNumber(number)) || isNaN(number)) return ''; - 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)) { - 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)) { - allowed = false; - break; - } - } - } - return allowed; + 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); + + 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++; } - function generateHolderType(Base) { - var holderType = function TrustedValueHolderType(trustedValue) { - this.$$unwrapTrustedValue = function() { - return trustedValue; - }; - }; - if (Base) { - holderType.prototype = new Base(); - } - holderType.prototype.valueOf = function sceValueOf() { - return this.$$unwrapTrustedValue(); - }; - holderType.prototype.toString = function sceToString() { - return this.$$unwrapTrustedValue().toString(); - }; - return holderType; + // extract decimals digits + if (integerLen > 0) { + decimals = digits.splice(integerLen, digits.length); + } else { + decimals = digits; + digits = [0]; } - var trustedValueHolderBase = generateHolderType(), - byType = {}; + // 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); - byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase); - byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase); - byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase); - byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase); - byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]); + // append the decimal digits + if (decimals.length) { + formattedText += decimalSep + decimals.join(''); + } - /** - * @ngdoc method - * @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. - */ - function trustAs(type, trustedValue) { - var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null); - if (!Constructor) { - throw $sceMinErr('icontext', - 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}', - type, trustedValue); - } - if (trustedValue === null || trustedValue === undefined || trustedValue === '') { - return trustedValue; - } - // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting - // mutable objects, we ensure here that the value passed in is actually a string. - if (typeof trustedValue !== 'string') { - throw $sceMinErr('itype', - 'Attempted to trust a non-string value in a content requiring a string: Context: {0}', - type); - } - return new Constructor(trustedValue); + if (exponent) { + formattedText += 'e+' + exponent; } + } + if (number < 0 && !isZero) { + return pattern.negPre + formattedText + pattern.negSuf; + } else { + return pattern.posPre + formattedText + pattern.posSuf; + } +} - /** - * @ngdoc method - * @name $sceDelegate#valueOf - * - * @description - * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs - * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link - * 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. - * - * @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 - * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns - * `value` unchanged. - */ - function valueOf(maybeTrusted) { - if (maybeTrusted instanceof trustedValueHolderBase) { - return maybeTrusted.$$unwrapTrustedValue(); - } else { - return maybeTrusted; - } +function padNumber(num, digits, trim, negWrap) { + var neg = ''; + if (num < 0 || (negWrap && num <= 0)) { + if (negWrap) { + num = -num + 1; + } else { + num = -num; + neg = '-'; } + } + num = '' + num; + while (num.length < digits) num = ZERO_CHAR + num; + if (trim) { + num = num.substr(num.length - digits); + } + return neg + num; +} - /** - * @ngdoc method - * @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. - * - * @param {string} type The kind of context in which this value is to be used. - * @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. - */ - function getTrusted(type, maybeTrusted) { - if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') { - return maybeTrusted; - } - var constructor = (byType.hasOwnProperty(type) ? byType[type] : null); - 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 (isResourceUrlAllowedByPolicy(maybeTrusted)) { - return maybeTrusted; - } else { - throw $sceMinErr('insecurl', - 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}', - maybeTrusted.toString()); - } - } else if (type === SCE_CONTEXTS.HTML) { - return htmlSanitizer(maybeTrusted); - } - throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.'); + +function dateGetter(name, size, offset, trim, negWrap) { + offset = offset || 0; + return function(date) { + var value = date['get' + name](); + if (offset > 0 || value > -offset) { + value += offset; } + if (value === 0 && offset === -12) value = 12; + return padNumber(value, size, trim, negWrap); + }; +} - return { trustAs: trustAs, - getTrusted: getTrusted, - valueOf: valueOf }; - }]; +function dateStrGetter(name, shortForm, standAlone) { + return function(date, formats) { + var value = date['get' + name](); + var propPrefix = (standAlone ? 'STANDALONE' : '') + (shortForm ? 'SHORT' : ''); + var get = uppercase(propPrefix + name); + + return formats[get][value]; + }; } +function timeZoneGetter(date, formats, offset) { + var zone = -1 * offset; + var paddedZone = (zone >= 0) ? '+' : ''; -/** - * @ngdoc provider - * @name $sceProvider - * @description - * - * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service. - * - enable/disable Strict Contextual Escaping (SCE) in a module - * - override the default implementation with a custom delegate - * - * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}. - */ + paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + + padNumber(Math.abs(zone % 60), 2); -/* jshint maxlen: false*/ + return paddedZone; +} -/** - * @ngdoc service - * @name $sce +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]; +} + +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), + H: dateGetter('Hours', 1), + hh: dateGetter('Hours', 2, -12), + h: dateGetter('Hours', 1, -12), + mm: dateGetter('Minutes', 2), + m: dateGetter('Minutes', 1), + ss: dateGetter('Seconds', 2), + s: dateGetter('Seconds', 1), + // while ISO 8601 requires fractions to be prefixed with `.` or `,` + // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions + sss: dateGetter('Milliseconds', 3), + EEEE: dateStrGetter('Day'), + EEE: dateStrGetter('Day', true), + a: ampmGetter, + Z: timeZoneGetter, + ww: weekGetter(2), + w: weekGetter(1), + G: eraGetter, + GG: eraGetter, + GGG: eraGetter, + GGGG: longEraGetter +}; + +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 * @kind function * * @description + * Formats `date` to a string based on the requested `format`. * - * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS. - * - * # Strict Contextual Escaping - * - * 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. - * - * As of version 1.2, Angular ships with SCE enabled by default. - * - * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow - * 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. - * - * 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. - * - * 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.) - * - * 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. - * - * How would you ensure that every place that used these types of bindings was bound to a value that - * was sanitized by your library (or returned as safe for rendering by your server?) How can you - * 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. - * - * 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. - * - * - * ## 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#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. - * - * 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 || ''); - * }); - * }; - * }]; - * ``` - * - * ## 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 - * 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. - * - * *Please note*: - * 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 apply in addition to this and may further restrict whether the template is successfully - * loaded. This means that without the right CORS policy, loading templates from a different domain - * won't work on all browsers. Also, loading templates from `file://` URL does not work on some - * browsers. - * - * ## 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. - * - * 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. - * - * 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? - * - * | 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. 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.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}
- * - * Each element in these arrays must be one of the following: - * - * - **'self'** - * - The special **string**, `'self'`, can be used to match against all URLs of the **same - * domain** as the application document using the **same protocol**. - * - **String** (except the special value `'self'`) - * - The string is matched against the full *normalized / absolute URL* of the resource - * being tested (substring matches are not good enough.) - * - 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. - * - `**`: 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. - * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might - * 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 - * 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. - * - 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 - * present on the RegExp (such as multiline, global, ignoreCase) are ignored. - * - If you are generating your JavaScript from some other templating engine (not - * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)), - * 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 - * [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 - * Closure library's [goog.string.regExpEscape(s)]( - * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962). - * - * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example. - * - * ## Show me an example using SCE. - * - * - * - *
- *

- * 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($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.all(by.css('.htmlComment')).first().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.'); - * }); - * }); - * - *
+ * `format` string can be composed of the following elements: * + * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) + * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) + * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) + * * `'MMMM'`: Month in year (January-December) + * * `'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) + * * `'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'`: 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}: * - * ## Can I disable SCE completely? + * * `'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. 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) * - * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits - * 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. + * `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'"`). * - * That said, here's how you can completely disable SCE: + * Any other characters in the `format` string will be output as-is. * - * ``` - * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) { - * // Completely disable SCE. For demonstration purposes only! - * // Do not use in new projects. - * $sceProvider.enabled(false); - * }); - * ``` + * @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 + * 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'}}
+ {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: + {{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}/); + 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)/); + }); + +
*/ -/* jshint maxlen: 100 */ +dateFilter.$inject = ['$locale']; +function dateFilter($locale) { -function $SceProvider() { - var enabled = true; - /** - * @ngdoc method - * @name $sceProvider#enabled - * @kind function - * - * @param {boolean=} value If provided, then enables/disables SCE. - * @return {boolean} true if SCE is enabled, false otherwise. - * - * @description - * Enables/disables SCE and returns the current value. - */ - this.enabled = function(value) { - if (arguments.length) { - enabled = !!value; + var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; + // 1 2 3 4 5 6 7 8 9 10 11 + function jsonStringToDate(string) { + var match; + if ((match = string.match(R_ISO8601_STR))) { + var date = new Date(0), + tzHour = 0, + tzMin = 0, + dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, + timeSetter = match[8] ? date.setUTCHours : date.setHours; + + if (match[9]) { + 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; } - return enabled; - }; + return string; + } - /* Design notes on the default implementation for SCE. - * - * The API contract for the SCE delegate - * ------------------------------------- - * The SCE delegate object must provide the following 3 methods: - * - * - trustAs(contextEnum, value) - * This method is used to tell the SCE service that the provided value is OK to use in the - * contexts specified by contextEnum. It must return an object that will be accepted by - * getTrusted() for a compatible contextEnum and return this value. - * - * - valueOf(value) - * For values that were not produced by trustAs(), return them as is. For values that were - * produced by trustAs(), return the corresponding input value to trustAs. Basically, if - * trustAs is wrapping the given values into some type, this operation unwraps it when given - * such a value. - * - * - getTrusted(contextEnum, value) - * This function should return the a 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 - * opaque or wrapped in some holder object. That happens to be an implementation detail. For - * instance, an implementation could maintain a registry of all trusted objects by context. In - * such a case, trustAs() would return the same object that was passed in. getTrusted() would - * return the same object passed in if it was found in the registry under a compatible context or - * throw an exception otherwise. An implementation might only wrap values some of the time based - * on some criteria. getTrusted() might return a value and not throw an exception for special - * constants or objects even if not wrapped. All such implementations fulfill this contract. - * - * - * A note on the inheritance model for SCE contexts - * ------------------------------------------------ - * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This - * is purely an implementation details. - * - * The contract is simply this: - * - * 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. - */ + return function(date, format, timezone) { + var text = '', + parts = [], + fn, match; - this.$get = ['$parse', '$sceDelegate', function( - $parse, $sceDelegate) { - // 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 && msie < 8) { - throw $sceMinErr('iequirks', - '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.'); + format = format || 'mediumDate'; + format = $locale.DATETIME_FORMATS[format] || format; + if (isString(date)) { + date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date); } - var sce = shallowCopy(SCE_CONTEXTS); - - /** - * @ngdoc method - * @name $sce#isEnabled - * @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}. - * - * @description - * Returns a boolean indicating if SCE is enabled. - */ - sce.isEnabled = function() { - return enabled; - }; - sce.trustAs = $sceDelegate.trustAs; - sce.getTrusted = $sceDelegate.getTrusted; - sce.valueOf = $sceDelegate.valueOf; + if (isNumber(date)) { + date = new Date(date); + } - if (!enabled) { - sce.trustAs = sce.getTrusted = function(type, value) { return value; }; - sce.valueOf = identity; + if (!isDate(date) || !isFinite(date.getTime())) { + return date; } - /** - * @ngdoc method - * @name $sce#parseAs - * - * @description - * Converts Angular {@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} 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`. - */ - sce.parseAs = function sceParseAs(type, expr) { - var parsed = $parse(expr); - if (parsed.literal && parsed.constant) { - return parsed; + while (format) { + match = DATE_FORMATS_SPLIT.exec(format); + if (match) { + parts = concat(parts, match, 1); + format = parts.pop(); } else { - return $parse(expr, function(value) { - return sce.getTrusted(type, value); - }); + parts.push(format); + format = null; } - }; - - /** - * @ngdoc method - * @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. - * - * @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. - */ - - /** - * @ngdoc method - * @name $sce#trustAsHtml - * - * @description - * 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}.) - */ - - /** - * @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}.) - */ + } - /** - * @ngdoc method - * @name $sce#trustAsResourceUrl - * - * @description - * 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}.) - */ + 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, dateTimezoneOffset) + : value === '\'\'' ? '\'' : value.replace(/(^'|'$)/g, '').replace(/''/g, '\''); + }); - /** - * @ngdoc method - * @name $sce#trustAsJs - * - * @description - * 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}.) - */ + return text; + }; +} - /** - * @ngdoc method - * @name $sce#getTrusted - * - * @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. - */ - /** - * @ngdoc method - * @name $sce#getTrustedHtml - * - * @description - * Shorthand method. `$sce.getTrustedHtml(value)` → - * {@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)` - */ +/** + * @ngdoc filter + * @name json + * @kind function + * + * @description + * Allows you to convert a JavaScript object into JSON string. + * + * This filter is mostly useful for debugging. When using the double curly {{value}} notation + * 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:4 }}
+
+ + it('should jsonify filtered objects', function() { + 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, spacing) { + if (isUndefined(spacing)) { + spacing = 2; + } + return toJson(object, spacing); + }; +} - /** - * @ngdoc method - * @name $sce#getTrustedCss - * - * @description - * Shorthand method. `$sce.getTrustedCss(value)` → - * {@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)` - */ - /** - * @ngdoc method - * @name $sce#getTrustedUrl - * - * @description - * Shorthand method. `$sce.getTrustedUrl(value)` → - * {@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)` - */ +/** + * @ngdoc filter + * @name lowercase + * @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); - /** - * @ngdoc method - * @name $sce#getTrustedResourceUrl - * - * @description - * Shorthand method. `$sce.getTrustedResourceUrl(value)` → - * {@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)` - */ - /** - * @ngdoc method - * @name $sce#getTrustedJs - * - * @description - * Shorthand method. `$sce.getTrustedJs(value)` → - * {@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)` - */ +/** + * @ngdoc filter + * @name uppercase + * @kind function + * @description + * Converts string to uppercase. + * @example + + + +
+ +

{{title}}

+ +

{{title | uppercase}}

+
+
+
+ */ +var uppercaseFilter = valueFn(uppercase); - /** - * @ngdoc method - * @name $sce#parseAsHtml - * - * @description - * Shorthand method. `$sce.parseAsHtml(expression string)` → - * {@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: - * - * * `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`. - */ +/** + * @ngdoc filter + * @name limitTo + * @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, 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`. 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 + + + +
+ +

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

+ +

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')); - /** - * @ngdoc method - * @name $sce#parseAsCss - * - * @description - * Shorthand method. `$sce.parseAsCss(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: - * - * * `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`. - */ + 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'); + }); - /** - * @ngdoc method - * @name $sce#parseAsUrl - * - * @description - * Shorthand method. `$sce.parseAsUrl(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: - * - * * `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`. - */ + // 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'); + // }); - /** - * @ngdoc method - * @name $sce#parseAsResourceUrl - * - * @description - * Shorthand method. `$sce.parseAsResourceUrl(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: - * - * * `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`. - */ + 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, begin) { + if (Math.abs(Number(limit)) === Infinity) { + limit = Number(limit); + } else { + limit = toInt(limit); + } + if (isNumberNaN(limit)) return input; - /** - * @ngdoc method - * @name $sce#parseAsJs - * - * @description - * Shorthand method. `$sce.parseAsJs(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: - * - * * `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`. - */ + if (isNumber(input)) input = input.toString(); + if (!isArrayLike(input)) return input; - // Shorthand delegations. - var parse = sce.parseAs, - getTrusted = sce.getTrusted, - trustAs = sce.trustAs; + begin = (!begin || isNaN(begin)) ? 0 : toInt(begin); + begin = (begin < 0) ? Math.max(0, input.length + begin) : begin; - forEach(SCE_CONTEXTS, function(enumValue, name) { - var lName = lowercase(name); - sce[camelCase("parse_as_" + lName)] = function(expr) { - return parse(enumValue, expr); - }; - sce[camelCase("get_trusted_" + lName)] = function(value) { - return getTrusted(enumValue, value); - }; - sce[camelCase("trust_as_" + lName)] = function(value) { - return trustAs(enumValue, value); - }; - }); + if (limit >= 0) { + return sliceFn(input, begin, begin + limit); + } else { + if (begin === 0) { + return sliceFn(input, limit, input.length); + } else { + return sliceFn(input, Math.max(0, begin + limit), begin); + } + } + }; +} - return sce; - }]; +function sliceFn(input, begin, end) { + if (isString(input)) return input.slice(begin, end); + + return slice.call(input, begin, end); } -/** - * !!! This is an undocumented "private" service !!! +/** + * @ngdoc filter + * @name orderBy + * @kind function + * + * @description + * 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`: 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. + * + * + * @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. + * + + +
+ + + + + + + + + + + +
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'); + }); + +
+ *
* - * @name $sniffer - * @requires $window - * @requires $document + * @example + * ### Changing parameters dynamically * - * @property {boolean} history Does the browser support html5 history api ? - * @property {boolean} transitions Does the browser support CSS transition events ? - * @property {boolean} animations Does the browser support CSS animation events ? + * 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. * - * @description - * This is very simple implementation of testing browser's features. - */ -function $SnifferProvider() { - this.$get = ['$window', '$document', function($window, $document) { - var eventSupport = {}, - android = - int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]), - boxee = /Boxee/i.test(($window.navigator || {}).userAgent), - document = $document[0] || {}, - vendorPrefix, - vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/, - bodyStyle = document.body && document.body.style, - transitions = false, - animations = false, - match; - - 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); - } - } + + +
+
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; + } - return { - // Android has history.pushState, but it does not update location correctly - // so let's not use the history API at all. - // http://code.google.com/p/android/issues/detail?id=17471 - // https://github.com/angular/angular.js/issues/904 + .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'); + }); - // 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 - hasEvent: function(event) { - // 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. - // 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 <= 11) return false; + it('should sort friends in reverse order, when clicking on the same column', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); - if (isUndefined(eventSupport[event])) { - var divElm = document.createElement('div'); - eventSupport[event] = 'on' + event in divElm; - } + ageHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Adam'); - return eventSupport[event]; - }, - csp: csp(), - vendorPrefix: vendorPrefix, - transitions: transitions, - animations: animations, - android: android - }; - }]; -} + ageHeader.click(); + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + }); -var $compileMinErr = minErr('$compile'); + it('should restore the original order, when clicking "Set to unsorted"', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); -/** - * @ngdoc service - * @name $templateRequest - * - * @description - * The `$templateRequest` service 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). + unsortButton.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Julie'); + }); + +
+ *
* - * @param {string} 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 + * @example + * ### Using `orderBy` inside a controller * - * @return {Promise} the HTTP Promise for the given. + * 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')`.) * - * @property {number} totalPendingRequests total amount of pending template requests being downloaded. - */ -function $TemplateRequestProvider() { - this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) { - function handleRequestFn(tpl, ignoreRequestError) { - handleRequestFn.totalPendingRequests++; - - var transformResponse = $http.defaults && $http.defaults.transformResponse; - - if (isArray(transformResponse)) { - transformResponse = transformResponse.filter(function(transformer) { - return transformer !== defaultHttpResponseTransform; - }); - } else if (transformResponse === defaultHttpResponseTransform) { - transformResponse = null; - } + + +
+
Sort by = {{propertyName}}; reverse = {{reverse}}
+
+ +
+ + + + + + + + + + + +
+ + + + + + + + +
{{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; + } - var httpOptions = { - cache: $templateCache, - transformResponse: transformResponse - }; + .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; + } - return $http.get(tpl, httpOptions) - ['finally'](function() { - handleRequestFn.totalPendingRequests--; - }) - .then(function(response) { - return response.data; - }, handleError); + .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'); + }); - function handleError(resp) { - if (!ignoreRequestError) { - throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl); - } - return $q.reject(resp); - } - } + it('should sort friends in reverse order, when clicking on the same column', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); - handleRequestFn.totalPendingRequests = 0; + ageHeader.click(); + expect(firstName.getText()).toBe('John'); + expect(lastName.getText()).toBe('Adam'); - return handleRequestFn; - }]; -} + ageHeader.click(); + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); + }); -function $$TestabilityProvider() { - this.$get = ['$rootScope', '$browser', '$location', - function($rootScope, $browser, $location) { + it('should restore the original order, when clicking "Set to unsorted"', function() { + expect(firstName.getText()).toBe('Adam'); + expect(lastName.getText()).toBe('John'); - /** - * @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 = {}; + 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; + } - /** - * @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; - }; + // Compare strings alphabetically, taking locale into account + return v1.value.localeCompare(v2.value); + }; + }]); + + + .friends-container { + display: inline-block; + margin: 0 30px; + } - /** - * @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; - } - } - }; + .friends { + border-collapse: collapse; + } - /** - * @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(); - }; + .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, compareFn) { - /** - * @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(); - } - }; + if (array == null) return array; + if (!isArrayLike(array)) { + throw minErr('orderBy')('notarray', 'Expected array but received: {0}', array); + } - /** - * @name $$testability#whenStable - * - * @description - * Calls the callback when $timeout and $http requests are completed. - * - * @param {function} callback - */ - testability.whenStable = function(callback) { - $browser.notifyWhenNoOutstandingRequests(callback); - }; + if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; } + if (sortPredicate.length === 0) { sortPredicate = ['+']; } - return testability; - }]; -} + var predicates = processPredicates(sortPredicate); -function $TimeoutProvider() { - this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler', - function($rootScope, $browser, $q, $$q, $exceptionHandler) { - var deferreds = {}; + var descending = reverseOrder ? -1 : 1; + // Define the `compare()` function. Use a default comparator if none is specified. + var compare = isFunction(compareFn) ? compareFn : defaultCompare; - /** - * @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. - * - */ - function timeout(fn, delay, invokeApply) { - var skipApply = (isDefined(invokeApply) && !invokeApply), - deferred = (skipApply ? $$q : $q).defer(), - promise = deferred.promise, - timeoutId; + // 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; }); - timeoutId = $browser.defer(function() { - try { - deferred.resolve(fn()); - } catch (e) { - deferred.reject(e); - $exceptionHandler(e); + 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; } - finally { - delete deferreds[promise.$$timeoutId]; + } + + 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); } + if (predicate !== '') { + get = $parse(predicate); + if (get.constant) { + var key = get(); + get = function(value) { return value[key]; }; + } + } + } + return {get: get, descending: descending}; + }); + } - if (!skipApply) $rootScope.$apply(); - }, delay); + function isPrimitive(value) { + switch (typeof value) { + case 'number': /* falls through */ + case 'boolean': /* falls through */ + case 'string': + return true; + default: + return false; + } + } - promise.$$timeoutId = timeoutId; - deferreds[timeoutId] = deferred; + 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 promise; + 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; - /** - * @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 (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; } - return false; - }; - return timeout; - }]; -} + 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; + } -// NOTE: The usage of window and document instead of $window and $document here is -// deliberate. This service depends on the specific behavior of anchor nodes created by the -// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and -// cause us to break tests. In addition, when the browser resolves a URL for XHR, it -// 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); + return result; + } +} +function ngDirective(directive) { + if (isFunction(directive)) { + directive = { + link: directive + }; + } + directive.restrict = directive.restrict || 'AC'; + return valueFn(directive); +} /** + * @ngdoc directive + * @name a + * @restrict E * - * Implementation Notes for non-IE browsers - * ---------------------------------------- - * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM, - * results both in the normalizing and parsing of the URL. Normalizing means that a relative - * 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 - * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html + * @description + * Modifies the default behavior of the html a tag so that the default action is prevented when + * the href attribute is empty. * - * Implementation Notes for IE - * --------------------------- - * IE >= 8 and <= 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. + * 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 (!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) { + // if we have no href url, then don't navigate anywhere. + if (!element.attr(href)) { + event.preventDefault(); + } + }); + }; + } + } +}); + +/** + * @ngdoc directive + * @name ngHref + * @restrict A + * @priority 99 * - * 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. + * @description + * Using AngularJS markup like `{{hash}}` in an href attribute will + * make the link go to the wrong URL if the user clicks it before + * 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. * - * References: - * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement - * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html - * http://url.spec.whatwg.org/#urlutils - * https://github.com/angular/angular.js/pull/2902 - * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/ + * The wrong way to write it: + * ```html + * link1 + * ``` * - * @kind function - * @param {string} url The URL to be parsed. - * @description Normalizes and parses a URL. - * @returns {object} Returns the normalized URL as a dictionary. + * The correct way to write it: + * ```html + * link1 + * ``` * - * | 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 | - * | 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 "/" + * @element A + * @param {template} ngHref any string which can contain `{{}}` markup. * - */ -function urlResolve(url) { - var href = url; + * @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)
+ link 2 (link, don't reload)
+ link 3 (link, reload!)
+ anchor (link, don't reload)
+ anchor (no link)
+ link (link, change location) +
+ + it('should execute ng-click but not reload when href without value', function() { + element(by.id('link-1')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('1'); + expect(element(by.id('link-1')).getAttribute('href')).toBe(''); + }); + + it('should execute ng-click but not reload when href empty string', function() { + element(by.id('link-2')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('2'); + expect(element(by.id('link-2')).getAttribute('href')).toBe(''); + }); + + it('should execute ng-click and change url when ng-href specified', function() { + expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/); + + element(by.id('link-3')).click(); + + // 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$/); + }); + }, 5000, 'page should navigate to /123'); + }); - if (msie) { - // Normalize before parse. Refer Implementation Notes on why this is - // done in two steps on IE. - urlParsingNode.setAttribute("href", href); - href = urlParsingNode.href; - } + 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(''); + }); - urlParsingNode.setAttribute('href', href); + it('should execute ng-click but not reload when no href but name specified', function() { + element(by.id('link-5')).click(); + expect(element(by.model('value')).getAttribute('value')).toEqual('5'); + expect(element(by.id('link-5')).getAttribute('href')).toBe(null); + }); - // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils - 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, - port: urlParsingNode.port, - pathname: (urlParsingNode.pathname.charAt(0) === '/') - ? urlParsingNode.pathname - : '/' + urlParsingNode.pathname - }; -} + it('should only change url when only ng-href', function() { + element(by.model('value')).clear(); + element(by.model('value')).sendKeys('6'); + expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/); -/** - * 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. + element(by.id('link-6')).click(); + + // 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$/); + }); + }, 5000, 'page should navigate to /6'); + }); + +
*/ -function urlIsSameOrigin(requestUrl) { - var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; - return (parsed.protocol === originUrl.protocol && - parsed.host === originUrl.host); -} /** - * @ngdoc service - * @name $window + * @ngdoc directive + * @name ngSrc + * @restrict A + * @priority 99 * * @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. + * 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 AngularJS replaces the expression inside + * `{{hash}}`. The `ngSrc` directive solves this problem. * - * 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. + * The buggy way to write it: + * ```html + * Description + * ``` * - * @example - - - -
- - -
-
- - it('should display the greeting in the input box', function() { - element(by.model('greeting')).sendKeys('Hello, E2E Tests'); - // If we click the button it will block the test runner - // element(':button').click(); - }); - -
- */ -function $WindowProvider() { - this.$get = valueFn(window); -} - -/* global currencyFilter: true, - dateFilter: true, - filterFilter: true, - jsonFilter: true, - limitToFilter: true, - lowercaseFilter: true, - numberFilter: true, - orderByFilter: true, - uppercaseFilter: true, + * The correct way to write it: + * ```html + * Description + * ``` + * + * @element IMG + * @param {template} ngSrc any string which can contain `{{}}` markup. */ /** - * @ngdoc provider - * @name $filterProvider - * @description - * - * Filters are just functions which transform input to an output. However filters need to be - * Dependency Injected. To achieve this a filter definition consists of a factory function which is - * annotated with dependencies and is responsible for creating a filter function. + * @ngdoc directive + * @name ngSrcset + * @restrict A + * @priority 99 * - * ```js - * // Filter registration - * function MyModule($provide, $filterProvider) { - * // create a service to demonstrate injection (not always needed) - * $provide.value('greet', function(name){ - * return 'Hello ' + name + '!'; - * }); + * @description + * 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 AngularJS replaces the expression inside + * `{{hash}}`. The `ngSrcset` directive solves this problem. * - * // register a filter factory which uses the - * // greet service to demonstrate DI. - * $filterProvider.register('greet', function(greet){ - * // return the filter function which uses the greet service - * // to generate salutation - * return function(text) { - * // filters need to be forgiving so check input validity - * return text && greet(text) || text; - * }; - * }); - * } + * The buggy way to write it: + * ```html + * Description * ``` * - * The filter function is registered with the `$injector` under the filter name suffix with - * `Filter`. - * - * ```js - * it('should be the same instance', inject( - * function($filterProvider) { - * $filterProvider.register('reverse', function(){ - * return ...; - * }); - * }, - * function($filter, reverseFilter) { - * expect($filter('reverse')).toBe(reverseFilter); - * }); + * The correct way to write it: + * ```html + * Description * ``` * - * - * 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. + * @element IMG + * @param {template} ngSrcset any string which can contain `{{}}` markup. */ /** - * @ngdoc service - * @name $filter - * @kind function + * @ngdoc directive + * @name ngDisabled + * @restrict A + * @priority 100 + * * @description - * Filters are used for formatting data displayed to the user. * - * The general syntax in templates is as follows: + * 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. * - * {{ expression [| filter_name[:parameter_value] ... ] }} + * A special directive is necessary because we cannot use interpolation inside the `disabled` + * attribute. See the {@link guide/interpolation interpolation guide} for more info. * - * @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']; -function $FilterProvider($provide) { - var suffix = 'Filter'; + + +
+ +
+ + it('should toggle button', function() { + expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy(); + element(by.model('checked')).click(); + expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy(); + }); + +
+ * + * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, + * then the `disabled` attribute will be set on the element + */ - /** - * @ngdoc method - * @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. - * @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)) { - var filters = {}; - forEach(name, function(filter, key) { - filters[key] = register(key, filter); - }); - return filters; - } else { - return $provide.factory(name + suffix, factory); - } - } - this.register = register; - this.$get = ['$injector', function($injector) { - return function(name) { - return $injector.get(name + suffix); - }; - }]; +/** + * @ngdoc directive + * @name ngChecked + * @restrict A + * @priority 100 + * + * @description + * 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 + + +
+ +
+ + it('should check both checkBoxes', function() { + 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 the `checked` attribute will be set on the element + */ - //////////////////////////////////////// - /* global - currencyFilter: false, - dateFilter: false, - filterFilter: false, - jsonFilter: false, - limitToFilter: false, - lowercaseFilter: false, - numberFilter: false, - orderByFilter: false, - uppercaseFilter: false, - */ +/** + * @ngdoc directive + * @name ngReadonly + * @restrict A + * @priority 100 + * + * @description + * + * 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 + + +
+ +
+ + it('should toggle readonly attr', function() { + expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy(); + element(by.model('checked')).click(); + expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy(); + }); + +
+ * + * @element INPUT + * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, + * then special attribute "readonly" will be set on the element + */ - register('currency', currencyFilter); - register('date', dateFilter); - register('filter', filterFilter); - register('json', jsonFilter); - register('limitTo', limitToFilter); - register('lowercase', lowercaseFilter); - register('number', numberFilter); - register('orderBy', orderByFilter); - register('uppercase', uppercaseFilter); -} /** - * @ngdoc filter - * @name filter - * @kind function + * @ngdoc directive + * @name ngSelected + * @restrict A + * @priority 100 * * @description - * Selects a subset of items from `array` and returns it as a new array. - * - * @param {Array} array The source array. - * @param {string|Object|function()} expression The predicate to be used for selecting items from - * `array`. * - * Can be one of: + * Sets the `selected` attribute on the element, if the expression inside `ngSelected` is truthy. * - * - `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 `!`. + * A special directive is necessary because we cannot use interpolation inside the `selected` + * attribute. See the {@link guide/interpolation interpolation guide} for more info. * - * - `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 or its nested object properties. That's equivalent to the simple - * substring match with a `string` as described above. 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:** `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. + *
* - * 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'}`. + * @example + + +
+ +
+ + it('should select Greetings!', function() { + expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy(); + element(by.model('selected')).click(); + expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy(); + }); + +
* - * - `function(value, index)`: 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. + * @element OPTION + * @param {expression} ngSelected If the {@link guide/expression expression} is truthy, + * then special attribute "selected" will be set on the element + */ + +/** + * @ngdoc directive + * @name ngOpen + * @restrict A + * @priority 100 * - * @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. + * @description * - * Can be one of: + * Sets the `open` attribute on the element, if the expression inside `ngOpen` is truthy. * - * - `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. + * A special directive is necessary because we cannot use interpolation inside the `open` + * attribute. See the {@link guide/interpolation interpolation guide} for more info. * - * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`. - * This is essentially strict comparison of expected and actual. + * ## A note about browser compatibility * - * - `false|undefined`: A short hand for a function which will look for a substring match in case - * insensitive way. + * Internet Explorer and Edge do not support the `details` element, it is + * recommended to use {@link ng.ngShow} and {@link ng.ngHide} instead. * * @example - - -
- - Search: - - - - - - -
NamePhone
{{friend.name}}{{friend.phone}}
-
- Any:
- Name only
- Phone only
- Equality
- - - - - - -
NamePhone
{{friendObj.name}}{{friendObj.phone}}
-
- - var expectFriendNames = function(expectedNames, key) { - element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) { - arr.forEach(function(wd, i) { - expect(wd.getText()).toMatch(expectedNames[i]); - }); + + +
+
+ List +
    +
  • Apple
  • +
  • Orange
  • +
  • Durian
  • +
+
+
+ + it('should toggle open', function() { + expect(element(by.id('details')).getAttribute('open')).toBeFalsy(); + element(by.model('open')).click(); + expect(element(by.id('details')).getAttribute('open')).toBeTruthy(); }); - }; + +
+ * + * @element DETAILS + * @param {expression} ngOpen If the {@link guide/expression expression} is truthy, + * then special attribute "open" will be set on the element + */ - it('should search across all fields when filtering with a string', function() { - var searchText = element(by.model('searchText')); - searchText.clear(); - searchText.sendKeys('m'); - expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend'); +var ngAttributeAliasDirectives = {}; - searchText.clear(); - searchText.sendKeys('76'); - expectFriendNames(['John', 'Julie'], 'friend'); - }); +// boolean attrs are evaluated +forEach(BOOLEAN_ATTR, function(propName, attrName) { + // binding to multiple is not supported + if (propName === 'multiple') return; - it('should search in specific fields when filtering with a predicate object', function() { - var searchAny = element(by.model('search.$')); - searchAny.clear(); - searchAny.sendKeys('i'); - expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj'); - }); - it('should use a equal comparison when comparator is true', function() { - var searchName = element(by.model('search.name')); - var strict = element(by.model('strict')); - searchName.clear(); - searchName.sendKeys('Julie'); - strict.click(); - expectFriendNames(['Julie'], 'friendObj'); - }); -
-
- */ -function filterFilter() { - return function(array, expression, comparator) { - if (!isArray(array)) return array; + function defaultLinkFn(scope, element, attr) { + scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { + attr.$set(attrName, !!value); + }); + } - var predicateFn; - var matchAgainstAnyProp; + var normalized = directiveNormalize('ng-' + attrName); + var linkFn = defaultLinkFn; - switch (typeof expression) { - case 'function': - predicateFn = expression; - break; - case 'boolean': - case 'number': - case 'string': - matchAgainstAnyProp = true; - //jshint -W086 - case 'object': - //jshint +W086 - predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp); - break; - default: - return array; - } + 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); + } + }; + } - return array.filter(predicateFn); + ngAttributeAliasDirectives[normalized] = function() { + return { + restrict: 'A', + priority: 100, + link: linkFn + }; }; -} +}); -// Helper functions for `filterFilter` -function createPredicateFn(expression, comparator, matchAgainstAnyProp) { - var shouldMatchPrimitives = isObject(expression) && ('$' in expression); - var predicateFn; +// aliased input attrs are evaluated +forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) { + ngAttributeAliasDirectives[ngAttr] = function() { + return { + priority: 100, + link: function(scope, element, attr) { + //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; + } + } - if (comparator === true) { - comparator = equals; - } else if (!isFunction(comparator)) { - comparator = function(actual, expected) { - if (isObject(actual) || isObject(expected)) { - // Prevent an object to be considered equal to a string like `'[object'` - return false; + scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) { + attr.$set(ngAttr, value); + }); } - - actual = lowercase('' + actual); - expected = lowercase('' + expected); - return actual.indexOf(expected) !== -1; }; - } - - predicateFn = function(item) { - if (shouldMatchPrimitives && !isObject(item)) { - return deepCompare(item, expression.$, comparator, false); - } - return deepCompare(item, expression, comparator, matchAgainstAnyProp); }; +}); - return predicateFn; -} +// ng-src, ng-srcset, ng-href are interpolated +forEach(['src', 'srcset', 'href'], function(attrName) { + var normalized = directiveNormalize('ng-' + attrName); + ngAttributeAliasDirectives[normalized] = ['$sce', function($sce) { + return { + priority: 99, // it needs to run after the attributes are interpolated + link: function(scope, element, attr) { + var propName = attrName, + name = attrName; -function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) { - var actualType = (actual !== null) ? typeof actual : 'null'; - var expectedType = (expected !== null) ? typeof expected : 'null'; + if (attrName === 'href' && + toString.call(element.prop('href')) === '[object SVGAnimatedString]') { + name = 'xlinkHref'; + attr.$attr[name] = 'xlink:href'; + propName = null; + } - if ((expectedType === 'string') && (expected.charAt(0) === '!')) { - return !deepCompare(actual, expected.substring(1), comparator, 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, matchAgainstAnyProp); - }); - } + // 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])); - switch (actualType) { - case 'object': - var key; - if (matchAgainstAnyProp) { - for (key in actual) { - if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) { - return true; - } - } - return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false); - } else if (expectedType === 'object') { - for (key in expected) { - var expectedVal = expected[key]; - if (isFunction(expectedVal) || isUndefined(expectedVal)) { - continue; + attr.$observe(normalized, function(value) { + if (!value) { + if (attrName === 'href') { + attr.$set(name, null); + } + return; } - var matchAnyProperty = key === '$'; - var actualVal = matchAnyProperty ? actual : actual[key]; - if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) { - return false; - } - } - return true; - } else { - return comparator(actual, expected); + attr.$set(name, value); + + // 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 might have sanitized the url. + if (msie && propName) element.prop(propName, attr[name]); + }); } - break; - case 'function': - return false; - default: - return comparator(actual, expected); - } + }; + }]; +}); + +/* global -nullFormCtrl, -PENDING_CLASS, -SUBMITTED_CLASS + */ +var nullFormCtrl = { + $addControl: noop, + $getControls: valueFn([]), + $$renameControl: nullFormRenameControl, + $removeControl: noop, + $setValidity: noop, + $setDirty: noop, + $setPristine: noop, + $setSubmitted: noop, + $$setSubmitted: noop +}, +PENDING_CLASS = 'ng-pending', +SUBMITTED_CLASS = 'ng-submitted'; + +function nullFormRenameControl(control, name) { + control.$name = name; } /** - * @ngdoc filter - * @name currency - * @kind function + * @ngdoc type + * @name form.FormController * - * @description - * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default - * symbol for current locale is used. + * @property {boolean} $pristine True if user has not interacted with the form yet. + * @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. * - * @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. + * @property {Object} $pending An object hash, containing references to controls or forms with + * pending validators, where: * + * - keys are validations tokens (error names). + * - values are arrays of controls or forms that have a pending validator for the given error name. * - * @example - - - -
-
- default currency symbol ($): {{amount | currency}}
- 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.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') { - // 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.id('currency-custom')).getText()).toBe('(USD$1,234.00)'); - expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)'); - }); - -
- */ -currencyFilter.$inject = ['$locale']; -function currencyFilter($locale) { - var formats = $locale.NUMBER_FORMATS; - return function(amount, currencySymbol, fractionSize) { - if (isUndefined(currencySymbol)) { - currencySymbol = formats.CURRENCY_SYM; - } - - if (isUndefined(fractionSize)) { - fractionSize = formats.PATTERNS[1].maxFrac; - } - - // if null or undefined pass it through - return (amount == null) - ? amount - : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize). - replace(/\u00A4/g, currencySymbol); - }; -} - -/** - * @ngdoc filter - * @name number - * @kind function + * See {@link form.FormController#$error $error} for a list of built-in validation tokens. * - * @description - * Formats a number as text. + * @property {Object} $error An object hash, containing references to controls or forms with failing + * validators, where: * - * If the input is not a number an empty string is returned. + * - keys are validation tokens (error names), + * - values are arrays of controls or forms that have a failing validator for the given error name. * - * @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. + * Built-in validation tokens: + * - `email` + * - `max` + * - `maxlength` + * - `min` + * - `minlength` + * - `number` + * - `pattern` + * - `required` + * - `url` + * - `date` + * - `datetimelocal` + * - `time` + * - `week` + * - `month` + * + * @description + * `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 + * of `FormController`. * - * @example - - - -
- Enter number:
- Default formatting: {{val | number}}
- No fractions: {{val | number:0}}
- Negative number: {{-val | number:4}} -
-
- - it('should format numbers', function() { - expect(element(by.id('number-default')).getText()).toBe('1,234.568'); - expect(element(by.binding('val | number:0')).getText()).toBe('1,235'); - expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679'); - }); - - it('should update', function() { - element(by.model('val')).clear(); - element(by.model('val')).sendKeys('3374.333'); - expect(element(by.id('number-default')).getText()).toBe('3,374.333'); - expect(element(by.binding('val | number:0')).getText()).toBe('3,374'); - expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330'); - }); - -
*/ +//asks for $scope to fool the BC controller module +FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate']; +function FormController($element, $attrs, $scope, $animate, $interpolate) { + this.$$controls = []; + // init state + 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; -numberFilter.$inject = ['$locale']; -function numberFilter($locale) { - var formats = $locale.NUMBER_FORMATS; - return function(number, fractionSize) { + this.$$element = $element; + this.$$animate = $animate; - // if null or undefined pass it through - return (number == null) - ? number - : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP, - fractionSize); - }; + setupValidity(this); } -var DECIMAL_SEP = '.'; -function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) { - if (!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) { - number = 0; - } else { - formatedText = numStr; - hasExponent = true; +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. 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. + */ + $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'); + this.$$controls.push(control); + + if (control.$name) { + this[control.$name] = control; } - } - if (!hasExponent) { - var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length; + control.$$parentForm = this; + }, - // determine fractionSize if it is not specified - if (isUndefined(fractionSize)) { - fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac); - } + /** + * @ngdoc method + * @name form.FormController#$getControls + * @returns {Array} the controls that are currently part of this form + * + * @description + * 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. + * + * 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. + */ + $getControls: function() { + return shallowCopy(this.$$controls); + }, - // safely round numbers in JS without hitting imprecisions of floating-point arithmetics - // inspired by: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round - number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize); + // Private API: rename a form control + $$renameControl: function(control, newName) { + var oldName = control.$name; - var fraction = ('' + number).split(DECIMAL_SEP); - var whole = fraction[0]; - fraction = fraction[1] || ''; + if (this[oldName] === control) { + delete this[oldName]; + } + this[newName] = control; + control.$name = newName; + }, - var i, pos = 0, - lgroup = pattern.lgSize, - group = pattern.gSize; + /** + * @ngdoc method + * @name form.FormController#$removeControl + * @param {object} control control object, either a {@link form.FormController} or an + * {@link ngModel.NgModelController} + * + * @description + * Deregister a control from the form. + * + * Input elements using ngModelController do this automatically when they are destroyed. + * + * 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`. + */ + $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; + }, - 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); - } - } + /** + * @ngdoc method + * @name form.FormController#$setDirty + * + * @description + * Sets the form to a dirty state. + * + * 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. + */ + $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(); + }, - for (i = pos; i < whole.length; i++) { - if ((whole.length - i) % lgroup === 0 && i !== 0) { - formatedText += groupSep; - } - formatedText += whole.charAt(i); - } + /** + * @ngdoc method + * @name form.FormController#$setPristine + * + * @description + * Sets the form to its pristine state. + * + * 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. + */ + $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(); + }); + }, - // format fraction part. - while (fraction.length < fractionSize) { - fraction += '0'; - } + /** + * @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(); + }); + }, - if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize); - } else { - if (fractionSize > 0 && number < 1) { - formatedText = number.toFixed(fractionSize); - number = parseFloat(formatedText); + /** + * @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(); + }, - if (number === 0) { - isNegative = false; + $$setSubmitted: function() { + this.$$animate.addClass(this.$$element, SUBMITTED_CLASS); + this.$submitted = true; + forEach(this.$$controls, function(control) { + if (control.$$setSubmitted) { + control.$$setSubmitted(); + } + }); } +}; - parts.push(isNegative ? pattern.negPre : pattern.posPre, - formatedText, - isNegative ? pattern.negSuf : pattern.posSuf); - return parts.join(''); -} - -function padNumber(num, digits, trim) { - var neg = ''; - if (num < 0) { - neg = '-'; - num = -num; +/** + * @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]; + } } - num = '' + num; - while (num.length < digits) num = '0' + num; - if (trim) - num = num.substr(num.length - digits); - return neg + num; -} - - -function dateGetter(name, size, offset, trim) { - offset = offset || 0; - return function(date) { - var value = date['get' + name](); - if (offset > 0 || value > -offset) - value += offset; - if (value === 0 && offset == -12) value = 12; - return padNumber(value, size, trim); - }; -} - -function dateStrGetter(name, shortForm) { - return function(date, formats) { - var value = date['get' + name](); - var get = uppercase(shortForm ? ('SHORT' + name) : name); - - return formats[get][value]; - }; -} - -function timeZoneGetter(date) { - var zone = -1 * date.getTimezoneOffset(); - var paddedZone = (zone >= 0) ? "+" : ""; - - paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) + - padNumber(Math.abs(zone % 60), 2); +}); - return paddedZone; -} +/** + * @ngdoc directive + * @name ngForm + * @restrict EAC + * + * @description + * 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 the related scope, under this name. + * + */ -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); -} + /** + * @ngdoc directive + * @name form + * @restrict E + * + * @description + * Directive that instantiates + * {@link form.FormController FormController}. + * + * If the `name` attribute is specified, the form controller is published onto the current scope under + * this name. + * + * ## Alias: {@link ng.directive:ngForm `ngForm`} + * + * 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 + * 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 + * - `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 + * + * 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, 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 + * a form is submitted: + * + * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element + * - {@link ng.directive:ngClick ngClick} directive on the first + * button or input field of type submit (input[type=submit]) + * + * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit} + * or {@link ng.directive:ngClick ngClick} directives. + * This is because of the following form submission rules in the HTML specification: + * + * - If a form has only one input field then hitting enter in this field triggers form submit + * (`ngSubmit`) + * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter + * doesn't trigger submit + * - if a form has one or more input fields and one or more buttons or input[type=submit] then + * 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`) + * + * 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 + * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well + * as JS animations. + * + * The following example shows a simple way to utilize CSS transitions to style a form element + * that has been rendered as invalid after it has been validated: + * + *
+ * //be sure to include ngAnimate as a module to hook into more
+ * //advanced animations
+ * .my-form {
+ *   transition:0.5s linear all;
+ *   background: white;
+ * }
+ * .my-form.ng-invalid {
+ *   background: red;
+ *   color:white;
+ * }
+ * 
+ * + * @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}}
+ +
+ + it('should initialize to model', function() { + var userType = element(by.binding('userType')); + var valid = element(by.binding('myForm.input.$valid')); -function getThursdayThisWeek(datetime) { - return new Date(datetime.getFullYear(), datetime.getMonth(), - // 4 = index of Thursday - datetime.getDate() + (4 - datetime.getDay())); -} + expect(userType.getText()).toContain('guest'); + expect(valid.getText()).toContain('true'); + }); -function weekGetter(size) { - return function(date) { - var firstThurs = getFirstThursdayOfYear(date.getFullYear()), - thisThurs = getThursdayThisWeek(date); + it('should be invalid if empty', function() { + var userType = element(by.binding('userType')); + var valid = element(by.binding('myForm.input.$valid')); + var userInput = element(by.model('userType')); - var diff = +thisThurs - +firstThurs, - result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week + userInput.clear(); + userInput.sendKeys(''); - return padNumber(result, size); - }; -} + expect(userType.getText()).toEqual('userType ='); + expect(valid.getText()).toContain('false'); + }); + +
+ * + * @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', '$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 ngFormCompile(formElement, attr) { + // Setup initial state of the control + formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS); -function ampmGetter(date, formats) { - return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]; -} + var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false); -function eraGetter(date, formats) { - return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1]; -} + return { + pre: function ngFormPreLink(scope, formElement, attr, ctrls) { + var controller = ctrls[0]; -function longEraGetter(date, formats) { - return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1]; -} + // 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 handleFormSubmission = function(event) { + scope.$apply(function() { + controller.$commitViewValue(); + controller.$setSubmitted(); + }); -var DATE_FORMATS = { - yyyy: dateGetter('FullYear', 4), - yy: dateGetter('FullYear', 2, 0, true), - y: dateGetter('FullYear', 1), - MMMM: dateStrGetter('Month'), - MMM: dateStrGetter('Month', true), - MM: dateGetter('Month', 2, 1), - M: dateGetter('Month', 1, 1), - dd: dateGetter('Date', 2), - d: dateGetter('Date', 1), - HH: dateGetter('Hours', 2), - H: dateGetter('Hours', 1), - hh: dateGetter('Hours', 2, -12), - h: dateGetter('Hours', 1, -12), - mm: dateGetter('Minutes', 2), - m: dateGetter('Minutes', 1), - ss: dateGetter('Seconds', 2), - s: dateGetter('Seconds', 1), - // while ISO 8601 requires fractions to be prefixed with `.` or `,` - // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions - sss: dateGetter('Milliseconds', 3), - EEEE: dateStrGetter('Day'), - EEE: dateStrGetter('Day', true), - a: ampmGetter, - Z: timeZoneGetter, - ww: weekGetter(2), - w: weekGetter(1), - G: eraGetter, - GG: eraGetter, - GGG: eraGetter, - GGGG: longEraGetter -}; + event.preventDefault(); + }; -var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/, - NUMBER_STRING = /^\-?\d+$/; + formElement[0].addEventListener('submit', handleFormSubmission); -/** - * @ngdoc filter - * @name date - * @kind function - * - * @description - * Formats `date` to a string based on the requested `format`. - * - * `format` string can be composed of the following elements: - * - * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010) - * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10) - * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199) - * * `'MMMM'`: Month in year (January-December) - * * `'MMM'`: Month in year (Jan-Dec) - * * `'MM'`: Month in year, padded (01-12) - * * `'M'`: Month in year (1-12) - * * `'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) - * * `'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'`: 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. 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) - * - * `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'"`). - * - * @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 - * 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. Right now, only `'UTC'` is supported. - * 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'}}
- {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: - {{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}/); - 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)/); - }); - -
- */ -dateFilter.$inject = ['$locale']; -function dateFilter($locale) { + // 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() { + formElement[0].removeEventListener('submit', handleFormSubmission); + }, 0, false); + }); + } + var parentFormCtrl = ctrls[1] || controller.$$parentForm; + parentFormCtrl.$addControl(controller); - var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/; - // 1 2 3 4 5 6 7 8 9 10 11 - function jsonStringToDate(string) { - var match; - if (match = string.match(R_ISO8601_STR)) { - var date = new Date(0), - tzHour = 0, - tzMin = 0, - dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear, - timeSetter = match[8] ? date.setUTCHours : date.setHours; + var setter = nameAttr ? getSetter(controller.$name) : noop; - if (match[9]) { - tzHour = int(match[9] + match[10]); - tzMin = int(match[9] + match[11]); + 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 + }); + } + }; } - 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); - timeSetter.call(date, h, m, s, ms); - return date; + }; + + 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; } - return string; - } + }]; +}; +var formDirective = formDirectiveFactory(); +var ngFormDirective = formDirectiveFactory(true); - return function(date, format, timezone) { - var text = '', - parts = [], - fn, match; - format = format || 'mediumDate'; - format = $locale.DATETIME_FORMATS[format] || format; - if (isString(date)) { - date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date); - } - if (isNumber(date)) { - date = new Date(date); - } +// 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; - if (!isDate(date)) { - return date; + clazz.prototype.$setValidity = function(validationErrorKey, state, controller) { + if (isUndefined(state)) { + createAndSet(this, '$pending', validationErrorKey, controller); + } else { + unsetAndCleanup(this, '$pending', validationErrorKey, controller); } - - while (format) { - match = DATE_FORMATS_SPLIT.exec(format); - if (match) { - parts = concat(parts, match, 1); - format = parts.pop(); + 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 { - parts.push(format); - format = null; + 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); + } - if (timezone && timezone === 'UTC') { - date = new Date(date.getTime()); - date.setMinutes(date.getMinutes() + date.getTimezoneOffset()); + // 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; } - forEach(parts, function(value) { - fn = DATE_FORMATS[value]; - text += fn ? fn(date, $locale.DATETIME_FORMATS) - : value.replace(/(^'|'$)/g, '').replace(/''/g, "'"); - }); - return text; + toggleValidationCss(this, validationErrorKey, combinedState); + this.$$parentForm.$setValidity(validationErrorKey, combinedState, this); }; -} - -/** - * @ngdoc filter - * @name json - * @kind function - * - * @description - * Allows you to convert a JavaScript object into JSON string. - * - * This filter is mostly useful for debugging. When using the double curly {{value}} notation - * 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:4 }}
-
- - it('should jsonify filtered objects', function() { - expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/); - expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/); - }); - -
- * - */ -function jsonFilter() { - return function(object, spacing) { - if (isUndefined(spacing)) { - spacing = 2; + function createAndSet(ctrl, name, value, controller) { + if (!ctrl[name]) { + ctrl[name] = {}; } - return toJson(object, spacing); - }; -} - - -/** - * @ngdoc filter - * @name lowercase - * @kind function - * @description - * Converts string to lowercase. - * @see angular.lowercase - */ -var lowercaseFilter = valueFn(lowercase); + 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; + } + } -/** - * @ngdoc filter - * @name uppercase - * @kind function - * @description - * Converts string to uppercase. - * @see angular.uppercase - */ -var uppercaseFilter = valueFn(uppercase); + 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; + } + } -/** - * @ngdoc filter - * @name limitTo - * @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, string or number, as specified by - * the value and sign (positive or negative) of `limit`. If a number is used as input, it is - * converted to a string. - * - * @param {Array|string|number} input Source array, 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. - * - * @example - - - -
- Limit {{numbers}} to: -

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

- Limit {{letters}} to: -

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

- Limit {{longNumber}} to: -

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')); + function toggleValidationCss(ctrl, validationErrorKey, isValid) { + validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; - 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'); - }); + cachedToggleClass(ctrl, VALID_CLASS + validationErrorKey, isValid === true); + cachedToggleClass(ctrl, INVALID_CLASS + validationErrorKey, isValid === false); + } +} - // 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'); - // }); +function isObjectEmpty(obj) { + if (obj) { + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + return false; + } + } + } + return true; +} - 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'); - }); - -
+/* global + VALID_CLASS: false, + INVALID_CLASS: false, + PRISTINE_CLASS: false, + DIRTY_CLASS: false, + ngModelMinErr: false */ -function limitToFilter() { - return function(input, limit) { - if (isNumber(input)) input = input.toString(); - if (!isArray(input) && !isString(input)) return input; - if (Math.abs(Number(limit)) === Infinity) { - limit = Number(limit); - } else { - limit = int(limit); - } +// 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})?)?$/; - //NaN check on limit - if (limit) { - return limit > 0 ? input.slice(0, limit) : input.slice(limit); - } else { - return isString(input) ? "" : []; - } - }; -} +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; +}); -/** - * @ngdoc filter - * @name orderBy - * @kind function - * - * @description - * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically - * for strings and numerically for numbers. Note: if you notice numbers are not being sorted - * correctly, make sure they are actually being saved as numbers and not strings. - * - * @param {Array} array The array to sort. - * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate 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. The result of this expression is used to compare elements - * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by - * 3 first characters of a property called `name`). The result of a constant expression - * is interpreted as a property name to be used in comparisons (for example `"special name"` - * to sort object by the value of their `special name` property). An expression can be - * optionally prefixed with `+` or `-` to control ascending or descending sort order - * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array - * element itself is used to compare where sorting. - * - `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. - * - * If the predicate is missing or empty then it defaults to `'+'`. - * - * @param {boolean=} reverse Reverse the order of the array. - * @returns {Array} Sorted copy of the source array. - * - * - * @example - * The example below demonstrates a simple ngRepeat, where the data is sorted - * by age in descending order (predicate is set to `'-age'`). - * `reverse` is not set, which means it defaults to `false`. - - - -
- - - - - - - - - - - -
NamePhone NumberAge
{{friend.name}}{{friend.phone}}{{friend.age}}
-
-
-
- * - * The predicate and reverse parameters can be controlled dynamically through scope properties, - * as shown in the next example. - * @example - +var inputType = { + + /** + * @ngdoc input + * @name input[text] + * + * @description + * Standard HTML text input with AngularJS data binding, inherited by most of the `input` elements. + * + * + * @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 + * 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. + * @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 + + + +
+ +
+ + 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('example.text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('example.text')); + + it('should initialize to model', function() { + expect(text.getText()).toContain('guest'); + expect(valid.getText()).toContain('true'); + }); + + it('should be invalid if empty', function() { + input.clear(); + input.sendKeys(''); + + expect(text.getText()).toEqual('text ='); + expect(valid.getText()).toContain('false'); + }); + + it('should be invalid if multi word', function() { + input.clear(); + input.sendKeys('hello world'); + + expect(valid.getText()).toContain('false'); + }); + +
+ */ + 'text': textInputType, + + /** + * @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 + -
-
Sorting predicate = {{predicate}}; reverse = {{reverse}}
-
- [ unsorted ] - - - - - - - - - - - -
Name - (^)Phone NumberAge
{{friend.name}}{{friend.phone}}{{friend.age}}
-
+
+ + +
+ + 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}}
+
-
- * - * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the - * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the - * desired parameters. - * - * Example: - * - * @example - - -
- - - - - - - - - - - -
Name - (^)Phone NumberAge
{{friend.name}}{{friend.phone}}{{friend.age}}
-
-
+ + var value = element(by.binding('example.value | date: "yyyy-MM-dd"')); + var valid = element(by.binding('myForm.input.$valid')); - - angular.module('orderByExample', []) - .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) { - var orderBy = $filter('orderBy'); - $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 } - ]; - $scope.order = function(predicate, reverse) { - $scope.friends = orderBy($scope.friends, predicate, reverse); - }; - $scope.order('-age',false); - }]); - -
- */ -orderByFilter.$inject = ['$parse']; -function orderByFilter($parse) { - return function(array, sortPredicate, reverseOrder) { - if (!(isArrayLike(array))) return array; - sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate]; - if (sortPredicate.length === 0) { sortPredicate = ['+']; } - sortPredicate = sortPredicate.map(function(predicate) { - var descending = false, get = predicate || identity; - if (isString(predicate)) { - if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) { - descending = predicate.charAt(0) == '-'; - predicate = predicate.substring(1); - } - if (predicate === '') { - // Effectively no predicate was passed so we compare identity - return reverseComparator(compare, descending); - } - get = $parse(predicate); - if (get.constant) { - var key = get(); - return reverseComparator(function(a, b) { - return compare(a[key], b[key]); - }, descending); + // 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); } - } - return reverseComparator(function(a, b) { - return compare(get(a),get(b)); - }, descending); - }); - return slice.call(array).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 descending - ? function(a, b) {return comp(b,a);} - : comp; - } + it('should initialize to model', function() { + expect(value.getText()).toContain('2013-10-22'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); - function isPrimitive(value) { - switch (typeof value) { - case 'number': /* falls through */ - case 'boolean': /* falls through */ - case 'string': - return true; - default: - return false; - } - } + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); - function objectToString(value) { - if (value === null) return 'null'; - if (typeof value.valueOf === 'function') { - value = value.valueOf(); - if (isPrimitive(value)) return value; - } - if (typeof value.toString === 'function') { - value = value.toString(); - if (isPrimitive(value)) return value; - } - return ''; - } + 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'), - function compare(v1, v2) { - var t1 = typeof v1; - var t2 = typeof v2; - if (t1 === t2 && t1 === "object") { - v1 = objectToString(v1); - v2 = objectToString(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; - } - } - }; -} + /** + * @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')); -function ngDirective(directive) { - if (isFunction(directive)) { - directive = { - link: directive - }; - } - directive.restrict = directive.restrict || 'AC'; - return valueFn(directive); -} + // 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); + } -/** - * @ngdoc directive - * @name a - * @restrict E - * - * @description - * 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` - */ -var htmlAnchorDirective = valueFn({ - restrict: 'E', - compile: function(element, attr) { - if (!attr.href && !attr.xlinkHref && !attr.name) { - return function(scope, element) { - // If the linked element is not an anchor tag anymore, do nothing - if (element[0].nodeName.toLowerCase() !== 'a') return; + it('should initialize to model', function() { + expect(value.getText()).toContain('2010-12-28T14:57:00'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); - // 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) { - // if we have no href url, then don't navigate anywhere. - if (!element.attr(href)) { - event.preventDefault(); - } - }); - }; - } - } -}); + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); -/** - * @ngdoc directive - * @name ngHref - * @restrict A - * @priority 99 - * - * @description - * Using Angular 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. - * - * The wrong way to write it: - * ```html - * link1 - * ``` - * - * The correct way to write it: - * ```html - * link1 - * ``` - * - * @element A - * @param {template} ngHref any string which can contain `{{}}` markup. - * - * @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)
- link 2 (link, don't reload)
- link 3 (link, reload!)
- anchor (link, don't reload)
- anchor (no link)
- link (link, change location) -
- - it('should execute ng-click but not reload when href without value', function() { - element(by.id('link-1')).click(); - expect(element(by.model('value')).getAttribute('value')).toEqual('1'); - expect(element(by.id('link-1')).getAttribute('href')).toBe(''); - }); + 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'), - it('should execute ng-click but not reload when href empty string', function() { - element(by.id('link-2')).click(); - expect(element(by.model('value')).getAttribute('value')).toEqual('2'); - expect(element(by.id('link-2')).getAttribute('href')).toBe(''); - }); + /** + * @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')); - it('should execute ng-click and change url when ng-href specified', function() { - expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/); + // 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); + } - element(by.id('link-3')).click(); + it('should initialize to model', function() { + expect(value.getText()).toContain('14:57:00'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); - // At this point, we navigate away from an Angular page, so we need - // to use browser.driver to get the base webdriver. + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); - browser.wait(function() { - return browser.driver.getCurrentUrl().then(function(url) { - return url.match(/\/123$/); - }); - }, 5000, 'page should navigate to /123'); - }); + 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'), - xit('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(''); - }); + /** + * @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')); - it('should execute ng-click but not reload when no href but name specified', function() { - element(by.id('link-5')).click(); - expect(element(by.model('value')).getAttribute('value')).toEqual('5'); - expect(element(by.id('link-5')).getAttribute('href')).toBe(null); - }); + // 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 only change url when only ng-href', function() { - element(by.model('value')).clear(); - element(by.model('value')).sendKeys('6'); - expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/); + it('should initialize to model', function() { + expect(value.getText()).toContain('2013-W01'); + expect(valid.getText()).toContain('myForm.input.$valid = true'); + }); - element(by.id('link-6')).click(); + it('should be invalid if empty', function() { + setInput(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('myForm.input.$valid = false'); + }); - // At this point, we navigate away from an Angular 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$/); - }); - }, 5000, 'page should navigate to /6'); - }); - + 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 directive - * @name ngSrc - * @restrict A - * @priority 99 - * - * @description - * Using Angular 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 - * `{{hash}}`. The `ngSrc` directive solves this problem. - * - * The buggy way to write it: - * ```html - * - * ``` - * - * The correct way to write it: - * ```html - * - * ``` - * - * @element IMG - * @param {template} ngSrc any string which can contain `{{}}` markup. - */ + /** + * @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. -/** - * @ngdoc directive - * @name ngSrcset - * @restrict A - * @priority 99 - * - * @description - * Using Angular 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 - * `{{hash}}`. The `ngSrcset` directive solves this problem. - * - * The buggy way to write it: - * ```html - * - * ``` - * - * The correct way to write it: - * ```html - * - * ``` - * - * @element IMG - * @param {template} ngSrcset any string which can contain `{{}}` markup. - */ + * @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')); -/** - * @ngdoc directive - * @name ngDisabled - * @restrict A - * @priority 100 - * - * @description - * - * This directive sets the `disabled` attribute on the element if the - * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy. - * - * A special directive is necessary because we cannot use interpolation inside the `disabled` - * attribute. The following example would make the button enabled on Chrome/Firefox - * but not on older IEs: - * - * ```html - * - *
- * - *
- * ``` - * - * This is because 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. - * - * @example - - - Click me to toggle:
- -
- - it('should toggle button', function() { - expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy(); - element(by.model('checked')).click(); - expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy(); - }); - -
- * - * @element INPUT - * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy, - * then the `disabled` attribute will be set on the element - */ + // 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'); + }); -/** - * @ngdoc directive - * @name ngChecked - * @restrict A - * @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. - * @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(); - }); - -
- * - * @element INPUT - * @param {expression} ngChecked If the {@link guide/expression expression} is truthy, - * then special attribute "checked" will be set on the element - */ + 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 directive - * @name ngReadonly - * @restrict A - * @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. - * @example - - - Check me to make text readonly:
- -
- - it('should toggle readonly attr', function() { - expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy(); - element(by.model('checked')).click(); - expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy(); - }); - -
- * - * @element INPUT - * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy, - * then special attribute "readonly" will be set on the element - */ + /** + * @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'); + }); -/** - * @ngdoc directive - * @name ngSelected - * @restrict A - * @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. - * - * @example - - - Check me to select:
- -
- - it('should select Greetings!', function() { - expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy(); - element(by.model('selected')).click(); - expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy(); - }); - -
- * - * @element OPTION - * @param {expression} ngSelected If the {@link guide/expression expression} is truthy, - * then special attribute "selected" will be set on the element - */ + it('should be invalid if empty', function() { + input.clear(); + input.sendKeys(''); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('false'); + }); -/** - * @ngdoc directive - * @name ngOpen - * @restrict A - * @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. - * @example - - - Check me check multiple:
-
- Show/Hide me -
-
- - it('should toggle open', function() { - expect(element(by.id('details')).getAttribute('open')).toBeFalsy(); - element(by.model('open')).click(); - expect(element(by.id('details')).getAttribute('open')).toBeTruthy(); - }); - -
- * - * @element DETAILS - * @param {expression} ngOpen If the {@link guide/expression expression} is truthy, - * then special attribute "open" will be set on the element - */ + it('should be invalid if over max', function() { + input.clear(); + input.sendKeys('123'); + expect(value.getText()).toEqual('value ='); + expect(valid.getText()).toContain('false'); + }); +
+
+ */ + 'number': numberInputType, -var ngAttributeAliasDirectives = {}; + /** + * @ngdoc input + * @name input[url] + * + * @description + * Text input with URL validation. Sets the `url` validation error key if the content is not a + * valid URL. + * + *
+ * **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 + * 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 + + + +
+
+ + var text = element(by.binding('url.text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('url.text')); + + it('should initialize to model', function() { + expect(text.getText()).toContain('http://google.com'); + expect(valid.getText()).toContain('true'); + }); -// boolean attrs are evaluated -forEach(BOOLEAN_ATTR, function(propName, attrName) { - // binding to multiple is not supported - if (propName == "multiple") return; + it('should be invalid if empty', function() { + input.clear(); + input.sendKeys(''); - var normalized = directiveNormalize('ng-' + attrName); - ngAttributeAliasDirectives[normalized] = function() { - return { - restrict: 'A', - priority: 100, - link: function(scope, element, attr) { - scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) { - attr.$set(attrName, !!value); - }); - } - }; - }; -}); + expect(text.getText()).toEqual('text ='); + expect(valid.getText()).toContain('false'); + }); -// aliased input attrs are evaluated -forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) { - ngAttributeAliasDirectives[ngAttr] = function() { - return { - priority: 100, - link: function(scope, element, attr) { - //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; - } - } + it('should be invalid if not url', function() { + input.clear(); + input.sendKeys('box'); - scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) { - attr.$set(ngAttr, value); - }); - } - }; - }; -}); + expect(valid.getText()).toContain('false'); + }); + +
+ */ + 'url': urlInputType, -// ng-src, ng-srcset, ng-href are interpolated -forEach(['src', 'srcset', 'href'], function(attrName) { - var normalized = directiveNormalize('ng-' + attrName); - ngAttributeAliasDirectives[normalized] = function() { - return { - priority: 99, // it needs to run after the attributes are interpolated - link: function(scope, element, attr) { - var propName = attrName, - name = attrName; - if (attrName === 'href' && - toString.call(element.prop('href')) === '[object SVGAnimatedString]') { - name = 'xlinkHref'; - attr.$attr[name] = 'xlink:href'; - propName = null; - } + /** + * @ngdoc input + * @name input[email] + * + * @description + * Text input with email validation. Sets the `email` validation error key if not a valid email + * address. + * + *
+ * **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 + * 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 email! +
+ text = {{email.text}}
+ myForm.input.$valid = {{myForm.input.$valid}}
+ myForm.input.$error = {{myForm.input.$error}}
+ myForm.$valid = {{myForm.$valid}}
+ myForm.$error.required = {{!!myForm.$error.required}}
+ myForm.$error.email = {{!!myForm.$error.email}}
+
+
+ + var text = element(by.binding('email.text')); + var valid = element(by.binding('myForm.input.$valid')); + var input = element(by.model('email.text')); + + it('should initialize to model', function() { + expect(text.getText()).toContain('me@example.com'); + expect(valid.getText()).toContain('true'); + }); - attr.$observe(normalized, function(value) { - if (!value) { - if (attrName === 'href') { - attr.$set(name, null); - } - return; - } + it('should be invalid if empty', function() { + input.clear(); + input.sendKeys(''); + expect(text.getText()).toEqual('text ='); + expect(valid.getText()).toContain('false'); + }); - attr.$set(name, value); + it('should be invalid if not email', function() { + input.clear(); + input.sendKeys('xxx'); - // 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. - if (msie && propName) element.prop(propName, attr[name]); - }); - } - }; - }; -}); + expect(valid.getText()).toContain('false'); + }); + +
+ */ + 'email': emailInputType, -/* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true - */ -var nullFormCtrl = { - $addControl: noop, - $$renameControl: nullFormRenameControl, - $removeControl: noop, - $setValidity: noop, - $setDirty: noop, - $setPristine: noop, - $setSubmitted: noop -}, -SUBMITTED_CLASS = 'ng-submitted'; -function nullFormRenameControl(control, name) { - control.$name = name; -} + /** + * @ngdoc input + * @name input[radio] + * + * @description + * HTML radio button. + * + * **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 AngularJS expression to be executed when input changes due to user + * interaction with the input element. + * @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 + + + +
+
+
+
+ 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 inputs = element.all(by.model('color.name')); + var color = element(by.binding('color.name')); -/** - * @ngdoc type - * @name form.FormController - * - * @property {boolean} $pristine True if user has not interacted with the form yet. - * @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 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 given error name. - * - * Built-in validation tokens: - * - * - `email` - * - `max` - * - `maxlength` - * - `min` - * - `minlength` - * - `number` - * - `pattern` - * - `required` - * - `url` - * - `date` - * - `datetimelocal` - * - `time` - * - `week` - * - `month` - * - * @description - * `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 - * of `FormController`. - * - */ -//asks for $scope to fool the BC controller module -FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate']; -function FormController(element, attrs, $scope, $animate, $interpolate) { - var form = this, - controls = []; + expect(color.getText()).toContain('blue'); - var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl; + inputs.get(0).click(); + expect(color.getText()).toContain('red'); - // init state - form.$error = {}; - form.$$success = {}; - form.$pending = undefined; - form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope); - form.$dirty = false; - form.$pristine = true; - form.$valid = true; - form.$invalid = false; - form.$submitted = false; - - parentForm.$addControl(form); + inputs.get(1).click(); + expect(color.getText()).toContain('green'); + }); + +
+ */ + 'radio': radioInputType, /** - * @ngdoc method - * @name form.FormController#$rollbackViewValue + * @ngdoc input + * @name input[range] * * @description - * Rollback all form controls pending updates to the `$modelValue`. + * Native range input with validation and transformation. * - * 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. + * 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}} +
+
+
+ */ - form.$rollbackViewValue = function() { - forEach(controls, function(control) { - control.$rollbackViewValue(); - }); - }; + 'range': rangeInputType, /** - * @ngdoc method - * @name form.FormController#$commitViewValue + * @ngdoc input + * @name input[checkbox] * * @description - * Commit all form controls pending updates to the `$modelValue`. + * HTML checkbox. * - * 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. + * @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 {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 = {{checkboxModel.value1}}
+ value2 = {{checkboxModel.value2}}
+
+
+ + it('should change state', function() { + 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('checkboxModel.value1')).click(); + element(by.model('checkboxModel.value2')).click(); + + expect(value1.getText()).toContain('false'); + expect(value2.getText()).toContain('NO'); + }); + +
*/ - form.$commitViewValue = function() { - forEach(controls, function(control) { - control.$commitViewValue(); + 'checkbox': checkboxInputType, + + 'hidden': noop, + 'button': noop, + 'submit': noop, + 'reset': noop, + 'file': noop +}; + +function stringBasedInputType(ctrl) { + ctrl.$formatters.push(function(value) { + return ctrl.$isEmpty(value) ? value : value.toString(); + }); +} + +function textInputType(scope, element, attr, ctrl, $sniffer, $browser) { + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); + stringBasedInputType(ctrl); +} + +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() { + 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(); }); - }; + } - /** - * @ngdoc method - * @name form.FormController#$addControl - * - * @description - * Register a control with the form. - * - * Input elements using ngModelController do this automatically when they are linked. - */ - form.$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); + var timeout; - if (control.$name) { - form[control.$name] = control; + var listener = function(ev) { + if (timeout) { + $browser.defer.cancel(timeout); + timeout = null; } - }; - - // Private API: rename a form control - form.$$renameControl = function(control, newName) { - var oldName = control.$name; + if (composing) return; + var value = element.val(), + event = ev && ev.type; - if (form[oldName] === control) { - delete form[oldName]; + // By default we will trim the value + // If the attribute ng-trim exists we will avoid trimming + // If input type is 'password', the value is never trimmed + if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) { + value = trim(value); } - form[newName] = control; - control.$name = newName; - }; - /** - * @ngdoc method - * @name form.FormController#$removeControl - * - * @description - * Deregister a control from the form. - * - * Input elements using ngModelController do this automatically when they are destroyed. - */ - form.$removeControl = function(control) { - if (control.$name && form[control.$name] === control) { - delete form[control.$name]; + // 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); } - forEach(form.$pending, function(value, name) { - form.$setValidity(name, null, control); - }); - forEach(form.$error, function(value, name) { - form.$setValidity(name, null, control); - }); - forEach(form.$$success, function(value, name) { - form.$setValidity(name, null, control); - }); - - arrayRemove(controls, control); }; - - /** - * @ngdoc method - * @name form.FormController#$setValidity - * - * @description - * Sets the validity of a form control. - * - * This method will also propagate to parent forms. - */ - addSetValidityMethod({ - ctrl: this, - $element: element, - 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]; + // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the + // input event on backspace, delete or cut + if ($sniffer.hasEvent('input')) { + element.on('input', listener); + } else { + var deferListener = function(ev, input, origValue) { + if (!timeout) { + timeout = $browser.defer(function() { + timeout = null; + if (!input || input.value !== origValue) { + listener(ev); + } + }); } - }, - parentForm: parentForm, - $animate: $animate - }); + }; - /** - * @ngdoc method - * @name form.FormController#$setDirty - * - * @description - * Sets the form to a dirty state. - * - * 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(); - }; + element.on('keydown', /** @this */ function(event) { + var key = event.keyCode; - /** - * @ngdoc method - * @name form.FormController#$setPristine - * - * @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. - * - * 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.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS); - form.$dirty = false; - form.$pristine = true; - form.$submitted = false; - forEach(controls, function(control) { - control.$setPristine(); + // ignore + // command modifiers arrows + if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return; + + deferListener(event, this, this.value); }); - }; - /** - * @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. - */ - form.$setUntouched = function() { - forEach(controls, function(control) { - control.$setUntouched(); + // 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 drop', deferListener); + } + } + + // if user paste into input using mouse on older 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); + } + }); + } }); - }; + } - /** - * @ngdoc method - * @name form.FormController#$setSubmitted - * - * @description - * Sets the form to its submitted state. - */ - form.$setSubmitted = function() { - $animate.addClass(element, SUBMITTED_CLASS); - form.$submitted = true; - parentForm.$setSubmitted(); + ctrl.$render = function() { + // Workaround for Firefox validation #12102. + var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue; + if (element.val() !== value) { + element.val(value); + } }; } -/** - * @ngdoc directive - * @name ngForm - * @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, ...). - * - * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into - * related scope, under this name. - * - */ - - /** - * @ngdoc directive - * @name form - * @restrict E - * - * @description - * Directive that instantiates - * {@link form.FormController FormController}. - * - * If the `name` attribute is specified, the form controller is published onto the current scope under - * this name. - * - * # 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 - * 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. - * - * - * # CSS classes - * - `ng-valid` is set if the form is valid. - * - `ng-invalid` is set if the form is invalid. - * - `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 - * - * Since the role of forms in client-side Angular 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 - * `` element has an `action` attribute specified. - * - * You can use one of the following two ways to specify what javascript method should be called when - * a form is submitted: - * - * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element - * - {@link ng.directive:ngClick ngClick} directive on the first - * button or input field of type submit (input[type=submit]) - * - * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit} - * or {@link ng.directive:ngClick ngClick} directives. - * This is because of the following form submission rules in the HTML specification: - * - * - If a form has only one input field then hitting enter in this field triggers form submit - * (`ngSubmit`) - * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter - * doesn't trigger submit - * - if a form has one or more input fields and one or more buttons or input[type=submit] then - * 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`) - * - * 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. - * - * ## Animation Hooks - * - * 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 - * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well - * as JS animations. - * - * The following example shows a simple way to utilize CSS transitions to style a form element - * that has been rendered as invalid after it has been validated: - * - *
- * //be sure to include ngAnimate as a module to hook into more
- * //advanced animations
- * .my-form {
- *   transition:0.5s linear all;
- *   background: white;
- * }
- * .my-form.ng-invalid {
- *   background: red;
- *   color:white;
- * }
- * 
- * - * @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}}
- -
- - it('should initialize to model', function() { - var userType = element(by.binding('userType')); - var valid = element(by.binding('myForm.input.$valid')); - expect(userType.getText()).toContain('guest'); - expect(valid.getText()).toContain('true'); + forEach(parts, function(part, index) { + if (index < mapping.length) { + map[mapping[index]] = +part; + } }); - it('should be invalid if empty', function() { - var userType = element(by.binding('userType')); - var valid = element(by.binding('myForm.input.$valid')); - var userInput = element(by.model('userType')); + 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); + } - userInput.clear(); - userInput.sendKeys(''); + return date; + } + } - expect(userType.getText()).toEqual('userType ='); - expect(valid.getText()).toContain('false'); - }); - -
- * - * @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) { - var formDirective = { - name: 'form', - restrict: isNgForm ? 'EAC' : 'E', - controller: FormController, - compile: function ngFormCompile(formElement, attr) { - // Setup initial state of the control - formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS); + return NaN; + }; +} - var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false); +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); - return { - pre: function ngFormPreLink(scope, formElement, attr, controller) { - // 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 handleFormSubmission = function(event) { - scope.$apply(function() { - controller.$commitViewValue(); - controller.$setSubmitted(); - }); + var isTimeType = type === 'time' || type === 'datetimelocal'; + var previousDate; + var previousTimezone; - event.preventDefault(); - }; + 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; + }); - addEventListenerFn(formElement[0], 'submit', handleFormSubmission); + 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'); - // 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', handleFormSubmission); - }, 0, false); - }); - } + if (timezone) { + previousTimezone = timezone; + previousDate = convertTimezoneToLocal(previousDate, timezone, true); + } - var parentFormCtrl = controller.$$parentForm; + return formatter(value, timezone); + } else { + previousDate = null; + previousTimezone = null; + return ''; + } + }); - if (nameAttr) { - setter(scope, null, controller.$name, controller, controller.$name); - attr.$observe(nameAttr, function(newValue) { - if (controller.$name === newValue) return; - setter(scope, null, controller.$name, undefined, controller.$name); - parentFormCtrl.$$renameControl(controller, newValue); - setter(scope, null, controller.$name, controller, controller.$name); - }); - } - formElement.on('$destroy', function() { - parentFormCtrl.$removeControl(controller); - if (nameAttr) { - setter(scope, null, attr[nameAttr], undefined, controller.$name); - } - extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards - }); - } - }; + 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(); + } + }); + } + + 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)); } - }; - return formDirective; - }]; -}; + var parsedDate = parseDate(value, previousDate); -var formDirective = formDirectiveFactory(); -var ngFormDirective = formDirectiveFactory(true); + if (!isNaN(parsedDate) && timezone) { + parsedDate = convertTimezoneToLocal(parsedDate, timezone); + } + return parsedDate; + } -/* global VALID_CLASS: false, - INVALID_CLASS: false, - PRISTINE_CLASS: false, - DIRTY_CLASS: false, - UNTOUCHED_CLASS: false, - TOUCHED_CLASS: false, - $ngModelMinErr: false, -*/ + function formatter(value, timezone) { + var targetFormat = format; -// Regex code is obtained from SO: 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)/; -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-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i; -var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\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})?)?$/; + if (isTimeType && isString(ctrl.$options.getOption('timeSecondsFormat'))) { + targetFormat = format + .replace('ss.sss', ctrl.$options.getOption('timeSecondsFormat')) + .replace(/:$/, ''); + } -var inputType = { + var formatted = $filter('date')(value, targetFormat, timezone); - /** - * @ngdoc input - * @name input[text] - * - * @description - * Standard HTML text input with angular data binding, inherited by most of the `input` elements. - * - * - * @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=} required Adds `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 value does not match - * a RegExp found by evaluating the Angular expression given in the attribute value. - * If the expression evaluates to a RegExp object then this is used directly. - * If the expression is 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$')`. - * @param {string=} ngChange Angular 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. - * This parameter is ignored for input[type=password] controls, which will never trim the - * input. - * - * @example - - - -
- Single word: - - 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('example.text')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('example.text')); + if (isTimeType && ctrl.$options.getOption('timeStripZeroSeconds')) { + formatted = formatted.replace(/(?::00)?(?:\.000)?$/, ''); + } - it('should initialize to model', function() { - expect(text.getText()).toContain('guest'); - expect(valid.getText()).toContain('true'); - }); + return formatted; + } + }; +} - it('should be invalid if empty', function() { - input.clear(); - input.sendKeys(''); +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; + } - expect(text.getText()).toEqual('text ='); - expect(valid.getText()).toContain('false'); - }); + return value; + }); + } +} - it('should be invalid if multi word', function() { - input.clear(); - input.sendKeys('hello world'); +function numberFormatterParser(ctrl) { + ctrl.$parsers.push(function(value) { + if (ctrl.$isEmpty(value)) return null; + if (NUMBER_REGEXP.test(value)) return parseFloat(value); - expect(valid.getText()).toContain('false'); - }); - -
- */ - 'text': textInputType, + ctrl.$$parserName = 'number'; + return undefined; + }); - /** - * @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 Angular 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 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`. This must be a - * valid ISO date string (yyyy-MM-dd). - * @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). - * @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 Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
- Pick a date in 2013: - - - 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('example.value | date: "yyyy-MM-dd"')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('example.value')); + ctrl.$formatters.push(function(value) { + if (!ctrl.$isEmpty(value)) { + if (!isNumber(value)) { + throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value); + } + value = value.toString(); + } + return value; + }); +} - // 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); - } +function parseNumberAttrVal(val) { + if (isDefined(val) && !isNumber(val)) { + val = parseFloat(val); + } + return !isNumberNaN(val) ? val : undefined; +} - it('should initialize to model', function() { - expect(value.getText()).toContain('2013-10-22'); - expect(valid.getText()).toContain('myForm.input.$valid = true'); - }); +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) - it('should be invalid if empty', function() { - setInput(''); - expect(value.getText()).toEqual('value ='); - expect(valid.getText()).toContain('myForm.input.$valid = false'); - }); + // eslint-disable-next-line no-bitwise + return (num | 0) === num; +} - 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'), +function countDecimals(num) { + var numString = num.toString(); + var decimalSymbolIndex = numString.indexOf('.'); - /** - * @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 Angular 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 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`. This must be a - * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). - * @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). - * @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 Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
- Pick a date between in 2013: - - - 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')); - var input = element(by.model('example.value')); + if (decimalSymbolIndex === -1) { + if (-1 < num && num < 1) { + // It may be in the exponential notation format (`1e-X`) + var match = /e-(\d+)$/.exec(numString); - // 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); + if (match) { + return Number(match[1]); } + } - it('should initialize to model', function() { - expect(value.getText()).toContain('2010-12-28T14:57:00'); - expect(valid.getText()).toContain('myForm.input.$valid = true'); - }); + return 0; + } - it('should be invalid if empty', function() { - setInput(''); - expect(value.getText()).toEqual('value ='); - expect(valid.getText()).toContain('myForm.input.$valid = false'); - }); + return numString.length - decimalSymbolIndex - 1; +} - 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'), +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); - /** - * @ngdoc input - * @name input[time] - * - * @description - * Input with time 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 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 Angular 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 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`. This must be a - * valid ISO time format (HH:mm:ss). - * @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). - * @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 Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
- Pick a between 8am and 5pm: - - - 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')); - var input = element(by.model('example.value')); + var isNonIntegerValue = !isNumberInteger(value); + var isNonIntegerStepBase = !isNumberInteger(stepBase); + var isNonIntegerStep = !isNumberInteger(step); + + // 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); + } - // 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); + 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; + }; + + attr.$observe('min', function(val) { + if (val !== minVal) { + parsedMinVal = parseNumberAttrVal(val); + minVal = val; + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); } + }); + } - it('should initialize to model', function() { - expect(value.getText()).toContain('14:57:00'); - expect(valid.getText()).toContain('myForm.input.$valid = true'); - }); + if (isDefined(attr.max) || attr.ngMax) { + var maxVal = attr.max || $parse(attr.ngMax)(scope); + var parsedMaxVal = parseNumberAttrVal(maxVal); - it('should be invalid if empty', function() { - setInput(''); - expect(value.getText()).toEqual('value ='); - expect(valid.getText()).toContain('myForm.input.$valid = false'); - }); + ctrl.$validators.max = function(modelValue, viewValue) { + return ctrl.$isEmpty(viewValue) || isUndefined(parsedMaxVal) || viewValue <= parsedMaxVal; + }; - 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'), + attr.$observe('max', function(val) { + if (val !== maxVal) { + parsedMaxVal = parseNumberAttrVal(val); + maxVal = val; + // TODO(matsko): implement validateLater to reduce number of validations + ctrl.$validate(); + } + }); + } - /** - * @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 Angular 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 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`. This must be a - * valid ISO week format (yyyy-W##). - * @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##). - * @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 Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
- Pick a date between in 2013: - - - 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')); - var input = element(by.model('example.value')); + if (isDefined(attr.step) || attr.ngStep) { + var stepVal = attr.step || $parse(attr.ngStep)(scope); + var parsedStepVal = parseNumberAttrVal(stepVal); - // 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); + ctrl.$validators.step = function(modelValue, viewValue) { + return ctrl.$isEmpty(viewValue) || isUndefined(parsedStepVal) || + isValidForStep(viewValue, parsedMinVal || 0, parsedStepVal); + }; + + attr.$observe('step', function(val) { + // TODO(matsko): implement validateLater to reduce number of validations + if (val !== stepVal) { + parsedStepVal = parseNumberAttrVal(val); + stepVal = val; + ctrl.$validate(); } - 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'), +function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) { + badInputChecker(scope, element, attr, ctrl, 'range'); + numberFormatterParser(ctrl); + baseInputType(scope, element, attr, ctrl, $sniffer, $browser); - /** - * @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 Angular 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 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`. This must be - * a valid ISO month format (yyyy-MM). - * @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). - * @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 Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
- Pick a month in 2013: - - - 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')); - var input = element(by.model('example.value')); + 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; + }; - // 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); + 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; + }; + + 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); } + }); + } - it('should initialize to model', function() { - expect(value.getText()).toContain('2013-10'); - expect(valid.getText()).toContain('myForm.input.$valid = true'); - }); + function minChange(val) { + minVal = parseNumberAttrVal(val); + // ignore changes before model is initialized + if (isNumberNaN(ctrl.$modelValue)) { + return; + } - it('should be invalid if empty', function() { - setInput(''); - expect(value.getText()).toEqual('value ='); - expect(valid.getText()).toContain('myForm.input.$valid = false'); - }); + 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(); + } + } - 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'), + 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); + }; +} - /** - * @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 a number, otherwise Angular will throw an error. - * - * @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. 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 value does not match - * a RegExp found by evaluating the Angular expression given in the attribute value. - * If the expression evaluates to a RegExp object then this is used directly. - * If the expression is 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$')`. - * @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 = {{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')); +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); - it('should initialize to model', function() { - expect(value.getText()).toContain('12'); - expect(valid.getText()).toContain('true'); - }); + ctrl.$validators.email = function(modelValue, viewValue) { + var value = modelValue || viewValue; + return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value); + }; +} - it('should be invalid if empty', function() { - input.clear(); - input.sendKeys(''); - expect(value.getText()).toEqual('value ='); - expect(valid.getText()).toContain('false'); - }); +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()); + } - it('should be invalid if over max', function() { - input.clear(); - input.sendKeys('123'); - expect(value.getText()).toEqual('value ='); - expect(valid.getText()).toContain('false'); - }); - -
- */ - 'number': numberInputType, + var listener = function(ev) { + var value; + if (element[0].checked) { + value = attr.value; + if (doTrim) { + value = trim(value); + } + ctrl.$setViewValue(value, ev && ev.type); + } + }; + element.on('change', listener); - /** - * @ngdoc input - * @name input[url] - * - * @description - * Text input with URL validation. Sets the `url` validation error key if the content is not a - * valid URL. - * - *
- * **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 angular 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 - * 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 value does not match - * a RegExp found by evaluating the Angular expression given in the attribute value. - * If the expression evaluates to a RegExp object then this is used directly. - * If the expression is 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$')`. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
- URL: - - Required! - - Not valid url! - text = {{url.text}}
- myForm.input.$valid = {{myForm.input.$valid}}
- myForm.input.$error = {{myForm.input.$error}}
- myForm.$valid = {{myForm.$valid}}
- myForm.$error.required = {{!!myForm.$error.required}}
- myForm.$error.url = {{!!myForm.$error.url}}
-
-
- - var text = element(by.binding('url.text')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('url.text')); + ctrl.$render = function() { + var value = attr.value; + if (doTrim) { + value = trim(value); + } + element[0].checked = (value === ctrl.$viewValue); + }; - it('should initialize to model', function() { - expect(text.getText()).toContain('http://google.com'); - expect(valid.getText()).toContain('true'); - }); + attr.$observe('value', ctrl.$render); +} - it('should be invalid if empty', function() { - input.clear(); - input.sendKeys(''); +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; +} - expect(text.getText()).toEqual('text ='); - expect(valid.getText()).toContain('false'); - }); +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); - it('should be invalid if not url', function() { - input.clear(); - input.sendKeys('box'); + var listener = function(ev) { + ctrl.$setViewValue(element[0].checked, ev && ev.type); + }; - expect(valid.getText()).toContain('false'); - }); - -
- */ - 'url': urlInputType, + element.on('change', listener); + + ctrl.$render = function() { + element[0].checked = ctrl.$viewValue; + }; + // 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 === false; + }; - /** - * @ngdoc input - * @name input[email] - * - * @description - * Text input with email validation. Sets the `email` validation error key if not a valid email - * address. - * - *
- * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex - * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can - * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide}) - *
- * - * @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=} 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 value does not match - * a RegExp found by evaluating the Angular expression given in the attribute value. - * If the expression evaluates to a RegExp object then this is used directly. - * If the expression is 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$')`. - * @param {string=} ngChange Angular expression to be executed when input changes due to user - * interaction with the input element. - * - * @example - - - -
- Email: - - Required! - - Not valid email! - text = {{email.text}}
- myForm.input.$valid = {{myForm.input.$valid}}
- myForm.input.$error = {{myForm.input.$error}}
- myForm.$valid = {{myForm.$valid}}
- myForm.$error.required = {{!!myForm.$error.required}}
- myForm.$error.email = {{!!myForm.$error.email}}
-
-
- - var text = element(by.binding('email.text')); - var valid = element(by.binding('myForm.input.$valid')); - var input = element(by.model('email.text')); + ctrl.$formatters.push(function(value) { + return equals(value, trueValue); + }); + + ctrl.$parsers.push(function(value) { + return value ? trueValue : falseValue; + }); +} - it('should initialize to model', function() { - expect(text.getText()).toContain('me@example.com'); - expect(valid.getText()).toContain('true'); - }); - it('should be invalid if empty', function() { - input.clear(); - input.sendKeys(''); - expect(text.getText()).toEqual('text ='); - expect(valid.getText()).toContain('false'); - }); +/** + * @ngdoc directive + * @name textarea + * @restrict E + * + * @description + * 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 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 + * 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=} 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 ` + *
{{ 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 incBtn = element(by.id('inc')); - var counter = element(by.id('counter')); - var evilBtn = element(by.id('evil')); - var evilError = element(by.id('evilError')); + var parse = function(viewValue) { + // If the viewValue is invalid (say required but empty) it will be `undefined` + if (isUndefined(viewValue)) return; - function getAndClearSevereErrors() { - return browser.manage().logs().get('browser').then(function(browserLog) { - return browserLog.filter(function(logEntry) { - return logEntry.level.value > webdriver.logging.Level.WARNING.value; - }); - }); - } + var list = []; - function clearErrors() { - getAndClearSevereErrors(); - } + if (viewValue) { + forEach(viewValue.split(separator), function(value) { + if (value) list.push(trimValues ? trim(value) : value); + }); + } - function expectNoErrors() { - getAndClearSevereErrors().then(function(filteredLog) { - expect(filteredLog.length).toEqual(0); - if (filteredLog.length) { - console.log('browser console errors: ' + util.inspect(filteredLog)); - } - }); - } + return list; + }; - function expectError(regex) { - getAndClearSevereErrors().then(function(filteredLog) { - var found = false; - filteredLog.forEach(function(log) { - if (log.message.match(regex)) { - found = true; - } - }); - if (!found) { - throw new Error('expected an error that matches ' + regex); - } - }); - } + ctrl.$parsers.push(parse); + ctrl.$formatters.push(function(value) { + if (isArray(value)) { + return value.join(ngList); + } - beforeEach(function() { - util = require('util'); - webdriver = require('protractor/node_modules/selenium-webdriver'); - }); + return undefined; + }); - // For now, we only test on Chrome, - // as Safari does not load the page with Protractor's injected scripts, - // and Firefox webdriver always disables content security policy (#6358) - if (browser.params.browser !== 'chrome') { - return; - } + // Override the standard $isEmpty because an empty array means the input is empty. + ctrl.$isEmpty = function(value) { + return !value || !value.length; + }; + } + }; +}; - it('should not report errors when the page is loaded', function() { - // clear errors so we are not dependent on previous tests - clearErrors(); - // Need to reload the page as the page is already loaded when - // we come here - browser.driver.getCurrentUrl().then(function(url) { - browser.get(url); - }); - expectNoErrors(); - }); +/* 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 +*/ - it('should evaluate expressions', function() { - expect(counter.getText()).toEqual('0'); - incBtn.click(); - expect(counter.getText()).toEqual('1'); - expectNoErrors(); - }); - it('should throw and report an error when using "eval"', function() { - evilBtn.click(); - expect(evilError.getText()).toMatch(/Content Security Policy/); - expectError(/Content Security Policy/); - }); - - - */ +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'; -// 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 -// the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc +var ngModelMinErr = minErr('ngModel'); /** - * @ngdoc directive - * @name ngClick + * @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. * - * @description - * The ngClick directive allows you to specify custom behavior when - * an element is clicked. + * @property {*} $modelValue The value in the model that the control is bound to. * - * @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`}) + * @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); + * ``` + * - * @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 collection of directives that allows creation of custom event handlers that are defined as - * angular expressions and are compiled and executed within the current scope. - */ -var ngEventDirectives = {}; + * @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. -// For events that might fire synchronously during DOM manipulation -// we need to execute their event handlers asynchronously using $evalAsync, -// so that they are not executed in an inconsistent state. -var forceAsyncEvents = { - 'blur': true, - 'focus': true -}; -forEach( - 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '), - function(eventName) { - var directiveName = directiveNormalize('ng-' + eventName); - ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) { - return { - restrict: 'A', - compile: function($element, attr) { - // We expose the powerful $event object on the scope that provides access to the Window, - // etc. that isn't protected by the fast paths in $parse. We explicitly request better - // checks at the cost of speed since event handler expressions are not executed as - // frequently as regular change detection. - var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true); - return function ngEventHandler(scope, element) { - element.on(eventName, function(event) { - var callback = function() { - fn(scope, {$event:event}); - }; - if (forceAsyncEvents[eventName] && $rootScope.$$phase) { - scope.$evalAsync(callback); - } else { - scope.$apply(callback); - } - }); - }; - } - }; - }]; - } -); + Formatters are used to format / convert the {@link ngModel.NgModelController#$modelValue + `$modelValue`} for display in the control. -/** - * @ngdoc directive - * @name ngDblclick + 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); + * ``` * - * @description - * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event. + * @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. * - * @element ANY - * @priority 0 - * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon - * a dblclick. (The Event object is available as `$event`) + * ```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); + * }; + * ``` * - * @example - - - - count: {{count}} - - - */ - - -/** - * @ngdoc directive - * @name ngMousedown + * @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. * - * @description - * The ngMousedown directive allows you to specify custom behavior on mousedown event. + * 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. * - * @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`}) + * ```js + * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) { + * var value = modelValue || viewValue; * - * @example - - - - count: {{count}} - - - */ - - -/** - * @ngdoc directive - * @name ngMouseup + * // 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; + * }); + * }; + * ``` * - * @description - * Specify custom behavior on mouseup event. + * @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. * - * @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`}) + * @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. * - * @example - - - - count: {{count}} - - - */ - -/** - * @ngdoc directive - * @name ngMouseover + * @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 - * Specify custom behavior on mouseover event. * - * @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`}) + * `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 - - - - count: {{count}} - - - */ - - -/** - * @ngdoc directive - * @name ngMouseenter + * ### 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. * - * @description - * Specify custom behavior on mouseenter event. + * `contenteditable` is an HTML5 attribute, which tells the browser to let the element + * contents be edited in place by the user. * - * @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`}) + * 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. * - * @example - - - - count: {{count}} - - - */ + * + + [contenteditable] { + border: 1px solid black; + background-color: white; + min-height: 20px; + } + .ng-invalid { + border: 1px solid red; + } -/** - * @ngdoc directive - * @name ngMouseleave - * - * @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`}) - * - * @example - - - - count: {{count}} - - - */ + + + 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 -/** - * @ngdoc directive - * @name ngMousemove - * - * @description - * Specify custom behavior on mousemove event. - * - * @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`}) - * - * @example - - - - count: {{count}} - - - */ + // 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); -/** - * @ngdoc directive - * @name ngKeydown - * - * @description - * Specify custom behavior on keydown event. + contentEditable.clear(); + contentEditable.sendKeys(protractor.Key.BACK_SPACE); + expect(contentEditable.getText()).toEqual(''); + expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/); + }); + + *
* - * @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.) * - * @example - - - - key down count: {{count}} - - */ +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)'); -/** - * @ngdoc directive - * @name ngKeyup - * - * @description - * Specify custom behavior on keyup event. - * - * @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.) - * - * @example - - -

Typing in the input box below updates the key count

- key up count: {{count}} + 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; + }, -

Typing in the input box below updates the keycode

- -

event keyCode: {{ event.keyCode }}

-

event altKey: {{ event.altKey }}

-
-
- */ + $$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 directive - * @name ngKeypress - * - * @description - * Specify custom behavior on keypress event. - * - * @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.) - * - * @example - - - - key press count: {{count}} - - - */ + /** + * @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 directive - * @name ngSubmit - * - * @description - * Enables binding angular expressions to onsubmit events. - * - * 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. - * - *
- * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and - * `ngSubmit` handlers together. See the - * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation} - * for a detailed discussion of when `ngSubmit` may be triggered. - *
- * - * @element form - * @priority 0 - * @param {expression} ngSubmit {@link guide/expression Expression} to eval. - * ({@link guide/expression#-event- Event object is available as `$event`}) - * - * @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.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 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 directive - * @name ngFocus - * - * @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. - * - * @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`}) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ + /** + * @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; + } -/** - * @ngdoc directive - * @name ngBlur - * - * @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. - * - * @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`}) - * - * @example - * See {@link ng.directive:ngClick ngClick} - */ + + *
+ */ + $rollbackViewValue: function() { + this.$$timeout.cancel(this.$$pendingDebounce); + this.$viewValue = this.$$lastCommittedViewValue; + this.$render(); + }, -/** - * @ngdoc directive - * @name ngCopy - * - * @description - * Specify custom behavior on copy event. - * - * @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`}) - * - * @example - - - - copied: {{copied}} - - - */ + /** + * @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() { -/** - * @ngdoc directive - * @name ngCut - * - * @description - * Specify custom behavior on cut event. - * - * @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`}) - * - * @example - - - - cut: {{cut}} - - - */ + // ignore $validate before model is initialized + if (isNumberNaN(this.$modelValue)) { + return; + } -/** - * @ngdoc directive - * @name ngPaste - * - * @description - * Specify custom behavior on paste event. - * - * @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`}) - * - * @example - - - - pasted: {{paste}} - - - */ + 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; -/** - * @ngdoc directive - * @name ngIf - * @restrict A - * - * @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 - * 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. - * - * @example - - - Click me:
- Show when checked: - - This is removed when the checkbox is unchecked. - -
- - .animate-if { - background:white; - border:1px solid black; - padding:10px; - } + var prevValid = this.$valid; + var prevModelValue = this.$modelValue; - .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; - } + var allowInvalid = this.$options.getOption('allowInvalid'); - .animate-if.ng-enter, - .animate-if.ng-leave.ng-leave-active { - opacity:0; - } + 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; - .animate-if.ng-leave, - .animate-if.ng-enter.ng-enter-active { - opacity:1; + if (that.$modelValue !== prevModelValue) { + that.$$writeModelToScope(); + } } - -
- */ -var ngIfDirective = ['$animate', function($animate) { - 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++] = 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 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).then(function() { - previousElements = null; - }); - block = null; - } - } - }); - } - }; -}]; + $$runValidators: function(modelValue, viewValue, doneCallback) { + this.$$currentValidationRunId++; + var localValidationRunId = this.$$currentValidationRunId; + var that = this; -/** - * @ngdoc directive - * @name ngInclude - * @restrict ECA - * - * @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 {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or - * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular'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 - * enter - animation is used to bring new content into the browser. - * leave - animation is used to animate existing content away. - * - * The enter and leave animation occur concurrently. - * - * @scope - * @priority 400 - * - * @param {string} ngInclude|src angular 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. - * - * @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; - } + // check parser error + if (!processParseErrors()) { + validationDone(false); + return; + } + if (!processSyncValidators()) { + validationDone(false); + return; + } + processAsyncValidators(); - .slide-animate { - padding:10px; - } + function processParseErrors() { + var errorKey = that.$$parserName; - .slide-animate.ng-enter, .slide-animate.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; + 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); + }); + } - position:absolute; - top:0; - left:0; - right:0; - bottom:0; - display:block; - padding:10px; + // Set the parse error last, to prevent unsetting it, should a $validators key == parserName + setValidity(errorKey, that.$$parserValid); + return that.$$parserValid; } + return true; + } - .slide-animate.ng-enter { - top:-50px; + 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; } - .slide-animate.ng-enter.ng-enter-active { - top:0; + 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); } + } - .slide-animate.ng-leave { - top:0; + function setValidity(name, isValid) { + if (localValidationRunId === that.$$currentValidationRunId) { + that.$setValidity(name, isValid); } - .slide-animate.ng-leave.ng-leave-active { - top:50px; + } + + function validationDone(allValid) { + if (localValidationRunId === that.$$currentValidationRunId) { + + doneCallback(allValid); } - - - 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/); - }); + /** + * @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; - 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/); - }); + this.$$timeout.cancel(this.$$pendingDebounce); - 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); - }); - -
- */ + // 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; + // change to dirty + if (this.$pristine) { + this.$setDirty(); + } + this.$$parseAndValidate(); + }, -/** - * @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. - */ + $$parseAndValidate: function() { + var viewValue = this.$$lastCommittedViewValue; + var modelValue = viewValue; + var that = this; + this.$$parserValid = isUndefined(modelValue) ? undefined : true; -/** - * @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. - */ + // Reset any previous parse error + this.$setValidity(this.$$parserName, null); + this.$$parserName = 'parse'; + 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; -/** - * @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', '$sce', - function($templateRequest, $anchorScroll, $animate, $sce) { - 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; + if (allowInvalid) { + this.$modelValue = modelValue; + writeToModelIfNeeded(); + } - return function(scope, $element, $attr, ctrl, $transclude) { - var changeCounter = 0, - currentScope, - previousElement, - currentElement; + // 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(); + } + }); - var cleanupLastIncludeContent = function() { - if (previousElement) { - previousElement.remove(); - previousElement = null; - } - if (currentScope) { - currentScope.$destroy(); - currentScope = null; - } - if (currentElement) { - $animate.leave(currentElement).then(function() { - previousElement = null; - }); - previousElement = currentElement; - currentElement = null; - } - }; + function writeToModelIfNeeded() { + if (that.$modelValue !== prevModelValue) { + that.$$writeModelToScope(); + } + } + }, - scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) { - var afterAnimation = function() { - if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { - $anchorScroll(); - } - }; - var thisChangeId = ++changeCounter; + $$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); + }, - 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 (thisChangeId !== changeCounter) return; - var newScope = scope.$new(); - ctrl.template = response; + /** + * @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); + } + }, - // 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).then(afterAnimation); - }); + $$debounceViewValueCommit: function(trigger) { + var debounceDelay = this.$options.getOption('debounce'); - currentScope = newScope; - currentElement = clone; + 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['*']; + } - currentScope.$emit('$includeContentLoaded', src); - scope.$eval(onloadExp); - }, function() { - if (thisChangeId === changeCounter) { - cleanupLastIncludeContent(); - scope.$emit('$includeContentError', src); - } - }); - scope.$emit('$includeContentRequested', src); - } else { - cleanupLastIncludeContent(); - ctrl.template = null; - } - }); - }; + 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(); + }); } - }; -}]; + }, -// 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 (/SVG/.test($element[0].toString())) { - // 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, document).childNodes)(scope, - function namespaceAdaptedClone(clone) { - $element.append(clone); - }, {futureParentElement: $element}); - return; - } + /** + * @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(); + }, - $element.html(ctrl.template); - $compile($element.contents())(scope); - } - }; - }]; + /** + * @ngdoc method + * + * @name ngModel.NgModelController#$processModelValue -/** - * @ngdoc directive - * @name ngInit - * @restrict AC - * - * @description - * The `ngInit` directive allows you to evaluate an expression in the - * current scope. - * - *
- * The only appropriate use of `ngInit` is for aliasing special properties of - * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you - * should use {@link guide/controller controllers} rather than `ngInit` - * to initialize values on a scope. - *
- *
- * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make - * sure you have parenthesis for correct precedence: - *
- * `
` - *
- *
- * - * @priority 450 - * - * @element ANY - * @param {expression} ngInit {@link guide/expression Expression} to eval. - * - * @example - + * @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. + * + * - -
-
-
- 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;'); - }); +
+
+ Search Fruit: + +
+
+ Model:
+
{{selectedFruit | json}}
+
+
-
- */ -var ngInitDirective = ngDirective({ - priority: 450, - compile: function() { - return { - pre: function(scope, element, attrs) { - scope.$eval(attrs.ngInit); - } - }; - } -}); + + 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; + }); -/** - * @ngdoc directive - * @name ngList - * - * @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 with Validation - * - * - * - * angular.module('listExample', []) - * .controller('ExampleController', ['$scope', function($scope) { - * $scope.names = ['morpheus', 'neo', 'trinity']; - * }]); - * - * - *
- * 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.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 whitespace - * - * - * - *
{{ 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]'); - * }); - * - *
- * - * @element input - * @param {string=} ngList optional delimiter that should be used to split the value. - */ -var ngListDirective = function() { - return { - restrict: 'A', - priority: 100, - require: 'ngModel', - link: function(scope, element, attr, ctrl) { - // We want to control whitespace trimming so we use this convoluted approach - // to access the ngList attribute, which doesn't pre-trim the attribute - var ngList = element.attr(attr.$attr.ngList) || ', '; - var trimValues = attr.ngTrim !== 'false'; - var separator = trimValues ? trim(ngList) : ngList; + 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; + } + } - var parse = function(viewValue) { - // If the viewValue is invalid (say required but empty) it will be `undefined` - if (isUndefined(viewValue)) return; + return match; + }); + }; - var list = []; + that.selectItem = function(item) { + ngModel.$setViewValue(item); + ngModel.$processModelValue(); + that.onSelect({item: item}); + }; + } + }); +
+ +
+ +
    +
  • + +
  • +
+
+
+ *
+ * + */ + $processModelValue: function() { + var viewValue = this.$$format(); - if (viewValue) { - forEach(viewValue.split(separator), function(value) { - if (value) list.push(trimValues ? trim(value) : value); - }); - } + 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); + } + }, - return list; - }; + /** + * This method is called internally to run the $formatters on the $modelValue + */ + $$format: function() { + var formatters = this.$formatters, + idx = formatters.length; - ctrl.$parsers.push(parse); - ctrl.$formatters.push(function(value) { - if (isArray(value)) { - return value.join(ngList); - } + var viewValue = this.$modelValue; + while (idx--) { + viewValue = formatters[idx](viewValue); + } - return undefined; - }); + return viewValue; + }, - // Override the standard $isEmpty because an empty array means the input is empty. - ctrl.$isEmpty = function(value) { - return !value || !value.length; - }; - } - }; -}; + /** + * This method is called internally when the bound scope value changes. + */ + $$setModelValue: function(modelValue) { + this.$modelValue = this.$$rawModelValue = modelValue; + this.$$parserValid = undefined; + this.$processModelValue(); + }, -/* global VALID_CLASS: true, - INVALID_CLASS: true, - PRISTINE_CLASS: true, - DIRTY_CLASS: true, - UNTOUCHED_CLASS: true, - TOUCHED_CLASS: true, -*/ + $$setUpdateOnEvents: function() { + if (this.$$updateEvents) { + this.$$element.off(this.$$updateEvents, this.$$updateEventHandler); + } -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', - PENDING_CLASS = 'ng-pending'; + 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); + } -var $ngModelMinErr = new minErr('ngModel'); + return modelValue; + }); +} /** - * @ngdoc type - * @name ngModel.NgModelController + * @ngdoc method + * @name ngModel.NgModelController#$setValidity * - * @property {string} $viewValue Actual string value in the view. - * @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 reads value from the DOM. 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`}. + * @description + * 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. + */ +addSetValidityMethod({ + clazz: NgModelController, + set: function(object, property) { + object[property] = true; + }, + unset: function(object, property) { + delete object[property]; + } +}); -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`. +/** + * @ngdoc directive + * @name ngModel + * @restrict A + * @priority 1 + * @param {expression} ngModel assignable {@link guide/expression Expression} to bind to. * - * @property {Array.} $formatters Array of functions to execute, as a pipeline, whenever - the model value changes. 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. - Used to format / convert values for display in the control. - * ```js - * function formatter(value) { - * if (value) { - * return value.toUpperCase(); - * } - * } - * ngModel.$formatters.push(formatter); - * ``` + * @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. * - * @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. + * `ngModel` is responsible for: * - * ```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); - * }; - * ``` + * - 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}. * - * @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. + * 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. * - * 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. + * For best practices on using `ngModel`, see: * - * ```js - * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) { - * var value = modelValue || viewValue; + * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes) * - * // 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; - * }); - * }; - * ``` + * For basic examples, how to use `ngModel`, see: * - * @property {Array.} $viewChangeListeners Array of functions to execute whenever the - * view value has changed. 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. + * - {@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} * - * @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. + * ## Complex Models (objects or collections) * - * @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. + * 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. * - * @description + * The model must be assigned an entirely new object or collection before a re-rendering will occur. * - * `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. - * Angular 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. + * 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. + * + * 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. + * + * ## 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`: 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 + * + * Keep in mind that ngAnimate can detect each of these classes when added and removed. + * + * @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. + * + * 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: + * + *
+ * //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 - * ### 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. + * ### Basic Usage + * + + + +

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

+
+ +
+
+ *
* - * `contenteditable` is an HTML5 attribute, which tells the browser to let the element - * contents be edited in place by the user. + * @example + * ### Binding to a getter/setter * - * 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. + * 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. * - * - - [contenteditable] { - border: 1px solid black; - background-color: white; - min-height: 20px; - } + *
+ * **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 = 
+
+
+ + 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); - .ng-invalid { - border: 1px solid red; - } + return { + pre: function ngModelPreLink(scope, element, attr, ctrls) { + var modelCtrl = ctrls[0], + formCtrl = ctrls[1] || modelCtrl.$$parentForm, + optionsCtrl = ctrls[2]; -
- - 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 + if (optionsCtrl) { + modelCtrl.$options = optionsCtrl.$options; + } - // Specify how UI should be updated - ngModel.$render = function() { - element.html($sce.getTrustedHtml(ngModel.$viewValue || '')); - }; + modelCtrl.$$initGetterSetters(); - // Listen for change events to enable binding - element.on('blur keyup change', function() { - scope.$evalAsync(read); - }); - read(); // initialize + // notify others, especially parent forms + formCtrl.$addControl(modelCtrl); - // 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); - } + attr.$observe('name', function(newValue) { + if (modelCtrl.$name !== newValue) { + modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue); } - }; - }]); -
- -
-
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/); - }); - - *
- * - * - */ -var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate', - function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $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); + }); + scope.$on('$destroy', function() { + modelCtrl.$$parentForm.$removeControl(modelCtrl); + }); + }, + post: function ngModelPostLink(scope, element, attr, ctrls) { + var modelCtrl = ctrls[0]; + modelCtrl.$$setUpdateOnEvents(); - var parsedNgModel = $parse($attr.ngModel), - parsedNgModelAssign = parsedNgModel.assign, - ngModelGet = parsedNgModel, - ngModelSet = parsedNgModelAssign, - pendingDebounce = null, - parserValid, - ctrl = this; + function setTouched() { + modelCtrl.$setTouched(); + } - this.$$setOptions = function(options) { - ctrl.$options = options; - if (options && options.getterSetter) { - var invokeModelGetter = $parse($attr.ngModel + '()'), - invokeModelSetter = $parse($attr.ngModel + '($$$p)'); + element.on('blur', function() { + if (modelCtrl.$touched) return; - ngModelGet = function($scope) { - var modelValue = parsedNgModel($scope); - if (isFunction(modelValue)) { - modelValue = invokeModelGetter($scope); - } - return modelValue; - }; - ngModelSet = function($scope, newValue) { - if (isFunction(parsedNgModel($scope))) { - invokeModelSetter($scope, {$$$p: ctrl.$modelValue}); - } else { - parsedNgModelAssign($scope, ctrl.$modelValue); + if ($rootScope.$$phase) { + scope.$evalAsync(setTouched); + } else { + scope.$apply(setTouched); + } + }); } }; - } else if (!parsedNgModel.assign) { - throw $ngModelMinErr('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. - * - * 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 to 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 to their previous value. 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. - */ - this.$render = noop; +/* exported defaultModelOptions */ +var defaultModelOptions; +var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/; - /** - * @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 to 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". - */ - this.$isEmpty = function(value) { - return isUndefined(value) || value === '' || value === null || value !== value; - }; +/** + * @ngdoc type + * @name ModelOptions + * @description + * A container for the options set by the {@link ngModelOptions} directive + */ +function ModelOptions(options) { + this.$$options = options; +} - var parentForm = $element.inheritedData('$formController') || nullFormCtrl, - currentValidationRunId = 0; +ModelOptions.prototype = { /** * @ngdoc method - * @name ngModel.NgModelController#$setValidity - * + * @name ModelOptions#getOption + * @param {string} name the name of the option to retrieve + * @returns {*} the value of the option * @description - * 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` - * class 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 Angular when validators do not run because of parse errors and - * when `$asyncValidators` do not run because any of the `$validators` failed. + * Returns the value of the given option */ - addSetValidityMethod({ - ctrl: this, - $element: $element, - set: function(object, property) { - object[property] = true; - }, - unset: function(object, property) { - delete object[property]; - }, - parentForm: parentForm, - $animate: $animate - }); + getOption: function(name) { + return this.$$options[name]; + }, /** * @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. + * @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. */ - this.$setPristine = function() { - ctrl.$dirty = false; - ctrl.$pristine = true; - $animate.removeClass($element, DIRTY_CLASS); - $animate.addClass($element, PRISTINE_CLASS); - }; + 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); + } +}; + + +defaultModelOptions = new ModelOptions({ + updateOn: '', + updateOnDefault: true, + debounce: 0, + getterSetter: false, + allowInvalid: false, + timezone: null +}); + + +/** + * @ngdoc directive + * @name ngModelOptions + * @restrict A + * @priority 10 + * + * @description + * 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. + * + * 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: `
+ *
+ * + *
+ *
+ * ``` + * + * the `input` element will have the following settings + * + * ```js + * { allowInvalid: true, updateOn: 'default', debounce: 0 } + * ``` + * + * Notice that the `debounce` setting was not inherited and used the default value instead. + * + * You can specify that all undefined settings are automatically inherited from an ancestor by + * including a property with key of `"*"` and value of `"$inherit"`. + * + * For example given the following fragment of HTML + * + * + * ```html + *
+ *
+ * + *
+ *
+ * ``` + * + * the `input` element will have the following settings + * + * ```js + * { allowInvalid: true, updateOn: 'default', debounce: 200 } + * ``` + * + * Notice that the `debounce` setting now inherits the value from the outer `
` element. + * + * 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. + * + * + * ## Triggering and debouncing model updates + * + * 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. + * + * 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. + * + * 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. + * + * 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. + * + * ### Overriding immediate updates + * + * 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. + * + * + * + *
+ *
+ *
+ *
+ *
+ *
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'); + * }); + * + * 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'); + * }); + * + *
+ * + * ### Debouncing updates + * + * 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. + * + * + * + *
+ *
+ * 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 + } + }; - /** - * @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. - */ - this.$setDirty = function() { - ctrl.$dirty = true; - ctrl.$pristine = false; - $animate.removeClass($element, PRISTINE_CLASS); - $animate.addClass($element, DIRTY_CLASS); - parentForm.$setDirty(); - }; + this.updateEvents = function() { + var eventList = this.options.updateOn.split(' '); + eventList.push('*'); + var events = {}; - /** - * @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. - */ - this.$setUntouched = function() { - ctrl.$touched = false; - ctrl.$untouched = true; - $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS); - }; + for (var i = 0; i < eventList.length; i++) { + events[eventList[i]] = this.options.debounce[eventList[i]]; + } - /** - * @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). - */ - this.$setTouched = function() { - ctrl.$touched = true; - ctrl.$untouched = false; - $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS); - }; + this.events = events; + }; - /** - * @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 a some - * future event. - * - * If you have an input that uses `ng-model-options` to set up debounced events or events such - * as blur you can have a situation where there is a period when the `$viewValue` - * is out of synch with the ngModel's `$modelValue`. - * - * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue` - * programmatically before these debounced/future events have resolved/occurred, because Angular'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. - * - * - * - * angular.module('cancel-update-example', []) - * - * .controller('CancelUpdateController', ['$scope', function($scope) { - * $scope.resetWithCancel = function(e) { - * if (e.keyCode == 27) { - * $scope.myForm.myInput1.$rollbackViewValue(); - * $scope.myValue = ''; - * } - * }; - * $scope.resetWithoutCancel = function(e) { - * if (e.keyCode == 27) { - * $scope.myValue = ''; - * } - * }; - * }]); - * - * - *
- *

Try typing something in each input. See that the model only updates when you - * blur off the input. - *

- *

Now see what happens if you start typing then press the Escape key

- * - *
- *

With $rollbackViewValue()

- *
- * myValue: "{{ myValue }}" - * - *

Without $rollbackViewValue()

- *
- * myValue: "{{ myValue }}" - *
- *
- *
- *
- */ - this.$rollbackViewValue = function() { - $timeout.cancel(pendingDebounce); - ctrl.$viewValue = ctrl.$$lastCommittedViewValue; - ctrl.$render(); - }; + this.updateOptions = function() { + var options = angular.extend(this.options, { + updateOn: Object.keys(this.events).join(' ').replace('*', ''), + debounce: this.events + }); - /** - * @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. - */ - this.$validate = function() { - // ignore $validate before model is initialized - if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) { - return; - } + this.form.input.$overrideModelOptions(options); + }; - var viewValue = ctrl.$$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 = ctrl.$$rawModelValue; + // Initialize the event form + this.updateEvents(); + } + }); +
+ +
+ Input: +
+ Model: {{$ctrl.name}} +
+ - var prevValid = ctrl.$valid; - var prevModelValue = ctrl.$modelValue; +
+
+ updateOn
+ - var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid; + + + + + + + + + +
OptionDebounce value
{{key}}
- ctrl.$$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 ctrl.$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. - ctrl.$modelValue = allValid ? modelValue : undefined; +
+ +
+
+
+ * + * + * ## Model updates and validation + * + * 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. + * + * + * ## Connecting to the scope + * + * 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. + * + * The following example shows how to bind to getter/setters: + * + * + * + *
+ *
+ * + *
+ *
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; + * } + * }; + * }]); + * + *
+ * + * + * ## Programmatically changing options + * + * 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}. + * + * + * ## Specifying timezones + * + * You can specify the timezone that date/time input directives expect by providing its name in the + * `timezone` property. + * + * + * ## 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. + * + + + + + + 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 + }; - if (ctrl.$modelValue !== prevModelValue) { - ctrl.$$writeModelToScope(); - } - } - }); + 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); + } }; - this.$$runValidators = function(modelValue, viewValue, doneCallback) { - currentValidationRunId++; - var localValidationRunId = currentValidationRunId; + return { + restrict: 'A', + // ngModelOptions needs to run before ngModel and input directives + priority: 10, + require: {parentCtrl: '?^^ngModelOptions'}, + bindToController: true, + controller: NgModelOptionsController + }; +}; - // check parser error - if (!processParseErrors()) { - validationDone(false); - return; - } - if (!processSyncValidators()) { - validationDone(false); - return; - } - processAsyncValidators(); - function processParseErrors() { - var errorKey = ctrl.$$parserName || 'parse'; - if (parserValid === undefined) { - setValidity(errorKey, null); - } else { - if (!parserValid) { - forEach(ctrl.$validators, function(v, name) { - setValidity(name, null); - }); - forEach(ctrl.$asyncValidators, function(v, name) { - setValidity(name, null); - }); - } - // Set the parse error last, to prevent unsetting it, should a $validators key == parserName - setValidity(errorKey, parserValid); - return parserValid; - } - return true; +// 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; } + }); +} - function processSyncValidators() { - var syncValidatorsValid = true; - forEach(ctrl.$validators, function(validator, name) { - var result = validator(modelValue, viewValue); - syncValidatorsValid = syncValidatorsValid && result; - setValidity(name, result); - }); - if (!syncValidatorsValid) { - forEach(ctrl.$asyncValidators, function(v, name) { - setValidity(name, null); - }); - return false; - } - return true; - } +/** + * @ngdoc directive + * @name ngNonBindable + * @restrict AC + * @priority 1000 + * @element ANY + * + * @description + * 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. + * + + +
Normal: {{1 + 2}}
+
Ignored: {{1 + 2}}
+
+ + 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 ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); - function processAsyncValidators() { - var validatorPromises = []; - var allValid = true; - forEach(ctrl.$asyncValidators, function(validator, name) { - var promise = validator(modelValue, viewValue); - if (!isPromiseLike(promise)) { - throw $ngModelMinErr("$asyncValidators", - "Expected asynchronous validator to return a promise but got '{0}' instead.", promise); - } - setValidity(name, undefined); - validatorPromises.push(promise.then(function() { - setValidity(name, true); - }, function(error) { - allValid = false; - setValidity(name, false); - })); - }); - if (!validatorPromises.length) { - validationDone(true); - } else { - $q.all(validatorPromises).then(function() { - validationDone(allValid); - }, noop); - } - } +/* exported ngOptionsDirective */ - function setValidity(name, isValid) { - if (localValidationRunId === currentValidationRunId) { - ctrl.$setValidity(name, isValid); - } - } +/* global jqLiteRemove */ - function validationDone(allValid) { - if (localValidationRunId === currentValidationRunId) { +var ngOptionsMinErr = minErr('ngOptions'); - doneCallback(allValid); - } - } - }; +/** + * @ngdoc directive + * @name ngOptions + * @restrict A + * + * @description + * + * 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 `
- - - angular.module('optionsExample', []) - .controller('ExampleController', ['$scope', function($scope) { - $scope.user = { name: 'say' }; - }]); - - + forEach(selectedValues, function(value) { + var option = options.selectValueMap[value]; + if (option && !option.disabled) selections.push(options.getViewValueFromOption(option)); + }); - This one shows how to bind to getter/setters: + return selections; + }; - - -
-
- Name: - -
-
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; + // If we are using `track by` then we must watch these tracked values on the model + // since ngModel only watches for object identity change + if (ngOptions.trackBy) { + + scope.$watchCollection(function() { + if (isArray(ngModelCtrl.$viewValue)) { + return ngModelCtrl.$viewValue.map(function(value) { + return ngOptions.getTrackByValue(value); + }); + } + }, function() { + ngModelCtrl.$render(); + }); + + } + } + + if (providedEmptyOption) { + + // compile the element since there might be bindings in it + $compile(selectCtrl.emptyOption)(scope); + + selectElement.prepend(selectCtrl.emptyOption); + + if (selectCtrl.emptyOption[0].nodeType === NODE_TYPE_COMMENT) { + // This means the empty option has currently no actual DOM node, probably because + // it has been modified by a transclusion directive. + selectCtrl.hasEmptyOption = false; + + // Redefine the registerOption function, which will catch + // options that are added by ngIf etc. (rendering of the node is async because of + // lazy transclusion) + selectCtrl.registerOption = function(optionScope, optionEl) { + if (optionEl.val() === '') { + selectCtrl.hasEmptyOption = true; + selectCtrl.emptyOption = optionEl; + selectCtrl.emptyOption.removeClass('ng-scope'); + // This ensures the new empty option is selected if previously no option was selected + ngModelCtrl.$render(); + + optionEl.on('$destroy', function() { + var needsRerender = selectCtrl.$isEmptyOptionSelected(); + + selectCtrl.hasEmptyOption = false; + selectCtrl.emptyOption = undefined; + + if (needsRerender) ngModelCtrl.$render(); + }); } }; - }]); - -
- */ -var ngModelOptionsDirective = function() { - return { - restrict: 'A', - controller: ['$scope', '$attrs', function($scope, $attrs) { - var that = this; - this.$options = $scope.$eval($attrs.ngModelOptions); - // Allow adding/overriding bound events - if (this.$options.updateOn !== undefined) { - this.$options.updateOnDefault = false; - // extract "default" pseudo-event from list of events that can trigger a model update - this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() { - that.$options.updateOnDefault = true; - return ' '; - })); - } else { - this.$options.updateOnDefault = true; + + } else { + // remove the class, which is added automatically because we recompile the element and it + // becomes the compilation root + selectCtrl.emptyOption.removeClass('ng-scope'); + } + } - }] - }; -}; + // We will re-render the option elements if the option values or labels change + scope.$watchCollection(ngOptions.getWatchables, updateOptions); + // ------------------------------------------------------------------ // -// helper methods -function addSetValidityMethod(context) { - var ctrl = context.ctrl, - $element = context.$element, - classCache = {}, - set = context.set, - unset = context.unset, - parentForm = context.parentForm, - $animate = context.$animate; + function addOptionElement(option, parent) { + var optionElement = optionTemplate.cloneNode(false); + parent.appendChild(optionElement); + updateOptionElement(option, optionElement); + } - classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS)); + function getAndUpdateSelectedOption(viewValue) { + var option = options.getOptionFromViewValue(viewValue); + var element = option && option.element; - ctrl.$setValidity = setValidity; + if (element && !element.selected) element.selected = true; - function setValidity(validationErrorKey, state, controller) { - if (state === undefined) { - createAndSet('$pending', validationErrorKey, controller); - } else { - unsetAndCleanup('$pending', validationErrorKey, controller); - } - if (!isBoolean(state)) { - unset(ctrl.$error, validationErrorKey, controller); - unset(ctrl.$$success, validationErrorKey, controller); - } else { - if (state) { - unset(ctrl.$error, validationErrorKey, controller); - set(ctrl.$$success, validationErrorKey, controller); - } else { - set(ctrl.$error, validationErrorKey, controller); - unset(ctrl.$$success, validationErrorKey, controller); + return option; } - } - if (ctrl.$pending) { - cachedToggleClass(PENDING_CLASS, true); - ctrl.$valid = ctrl.$invalid = undefined; - toggleValidationCss('', null); - } else { - cachedToggleClass(PENDING_CLASS, false); - ctrl.$valid = isObjectEmpty(ctrl.$error); - ctrl.$invalid = !ctrl.$valid; - toggleValidationCss('', ctrl.$valid); - } - // re-read the state as the set/unset methods could have - // combined state in ctrl.$error[validationError] (used for forms), - // where setting/unsetting only increments/decrements the value, - // and does not replace it. - var combinedState; - if (ctrl.$pending && ctrl.$pending[validationErrorKey]) { - combinedState = undefined; - } else if (ctrl.$error[validationErrorKey]) { - combinedState = false; - } else if (ctrl.$$success[validationErrorKey]) { - combinedState = true; - } else { - combinedState = null; - } + function updateOptionElement(option, element) { + option.element = element; + element.disabled = option.disabled; + // Support: IE 11 only, Edge 12-13 only + // NOTE: The label must be set before the value, otherwise IE 11 & Edge create unresponsive + // selects in certain circumstances when multiple selects are next to each other and display + // the option list in listbox style, i.e. the select is [multiple], or specifies a [size]. + // See https://github.com/angular/angular.js/issues/11314 for more info. + // This is unfortunately untestable with unit / e2e tests + if (option.label !== element.label) { + element.label = option.label; + element.textContent = option.label; + } + element.value = option.selectValue; + } - toggleValidationCss(validationErrorKey, combinedState); - parentForm.$setValidity(validationErrorKey, combinedState, ctrl); - } + function updateOptions() { + var previousValue = options && selectCtrl.readValue(); - function createAndSet(name, value, controller) { - if (!ctrl[name]) { - ctrl[name] = {}; - } - set(ctrl[name], value, controller); - } + // We must remove all current options, but cannot simply set innerHTML = null + // since the providedEmptyOption might have an ngIf on it that inserts comments which we + // must preserve. + // Instead, iterate over the current option elements and remove them or their optgroup + // parents + if (options) { - function unsetAndCleanup(name, value, controller) { - if (ctrl[name]) { - unset(ctrl[name], value, controller); - } - if (isObjectEmpty(ctrl[name])) { - ctrl[name] = undefined; - } - } + for (var i = options.items.length - 1; i >= 0; i--) { + var option = options.items[i]; + if (isDefined(option.group)) { + jqLiteRemove(option.element.parentNode); + } else { + jqLiteRemove(option.element); + } + } + } - function cachedToggleClass(className, switchValue) { - if (switchValue && !classCache[className]) { - $animate.addClass($element, className); - classCache[className] = true; - } else if (!switchValue && classCache[className]) { - $animate.removeClass($element, className); - classCache[className] = false; - } - } + options = ngOptions.getOptions(); - function toggleValidationCss(validationErrorKey, isValid) { - validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : ''; + var groupElementMap = {}; - cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true); - cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false); - } -} + options.items.forEach(function addOption(option) { + var groupElement; -function isObjectEmpty(obj) { - if (obj) { - for (var prop in obj) { - return false; - } + if (isDefined(option.group)) { + + // This option is to live in a group + // See if we have already created this group + groupElement = groupElementMap[option.group]; + + if (!groupElement) { + + groupElement = optGroupTemplate.cloneNode(false); + listFragment.appendChild(groupElement); + + // Update the label on the group element + // "null" is special cased because of Safari + groupElement.label = option.group === null ? 'null' : option.group; + + // Store it for use later + groupElementMap[option.group] = groupElement; + } + + addOptionElement(option, groupElement); + + } else { + + // This option is not in a group + addOptionElement(option, listFragment); + } + }); + + selectElement[0].appendChild(listFragment); + + ngModelCtrl.$render(); + + // Check to see if the value has changed due to the update to the options + if (!ngModelCtrl.$isEmpty(previousValue)) { + var nextValue = selectCtrl.readValue(); + var isNotPrimitive = ngOptions.trackBy || multiple; + if (isNotPrimitive ? !equals(previousValue, nextValue) : previousValue !== nextValue) { + ngModelCtrl.$setViewValue(nextValue); + ngModelCtrl.$render(); + } + } + } } - return true; -} -/** - * @ngdoc directive - * @name ngNonBindable - * @restrict AC - * @priority 1000 - * - * @description - * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current - * DOM element. This is useful if the element contains what appears to be Angular directives and - * bindings but which should be ignored by Angular. This could be the case if you have a site that - * displays snippets of code, for instance. - * - * @element ANY - * - * @example - * In this example there are two locations where a simple interpolation binding (`{{}}`) is present, - * but the one wrapped in `ngNonBindable` is left alone. - * - * @example - - -
Normal: {{1 + 2}}
-
Ignored: {{1 + 2}}
-
- - 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 ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); + return { + restrict: 'A', + terminal: true, + require: ['select', 'ngModel'], + link: { + pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) { + // Deactivate the SelectController.register method to prevent + // option directives from accidentally registering themselves + // (and unwanted $destroy handlers etc.) + ctrls[0].registerOption = noop; + }, + post: ngOptionsPostLink + } + }; +}]; /** * @ngdoc directive @@ -23972,27 +32917,27 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); * @description * `ngPluralize` is a directive that displays messages according to en-US localization rules. * These rules are bundled with angular.js, but can be overridden - * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive + * (see {@link guide/i18n AngularJS i18n} dev guide). You configure ngPluralize directive * by specifying the mappings between * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) * and the strings to be displayed. * - * # Plural categories and explicit number rules + * ## Plural categories and explicit number rules * There are two * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html) - * in Angular's default en-US locale: "one" and "other". + * in AngularJS's default en-US locale: "one" and "other". * * While a plural category may match many numbers (for example, in en-US locale, "other" can match * any number that is not 1), an explicit number rule can only match one number. For example, the * explicit number rule for "3" matches the number 3. There are examples of plural categories * and explicit number rules throughout the rest of this documentation. * - * # Configuring ngPluralize + * ## Configuring ngPluralize * You configure ngPluralize by providing 2 attributes: `count` and `when`. * You can also provide an optional attribute, `offset`. * * The value of the `count` attribute can be either a string or an {@link guide/expression - * Angular expression}; these are evaluated on the current scope for its bound value. + * AngularJS expression}; these are evaluated on the current scope for its bound value. * * The `when` attribute specifies the mappings between plural categories and the actual * string to be displayed. The value of the attribute should be a JSON object. @@ -24014,11 +32959,14 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); * show "a dozen people are viewing". * * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted - * into pluralized strings. In the previous example, Angular will replace `{}` with + * into pluralized strings. In the previous example, AngularJS will replace `{}` with * `{{personCount}}`. The closed braces `{}` is a placeholder * for {{numberExpression}}. * - * # Configuring ngPluralize with offset + * If no rule is defined for a category, then an empty string is displayed and a warning is generated. + * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`. + * + * ## Configuring ngPluralize with offset * The `offset` attribute allows further customization of pluralized text, which can result in * a better user experience. For example, instead of the message "4 people are viewing this document", * you might display "John, Kate and 2 others are viewing this document". @@ -24039,7 +32987,7 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); * three explicit number rules 0, 1 and 2. * When one person, perhaps John, views the document, "John is viewing" will be shown. * When three people view the document, no explicit number rule is found, so - * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category. + * an offset of 2 is taken off 3, and AngularJS uses 1 to decide the plural category. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing" * is shown. * @@ -24053,7 +33001,7 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); * @param {number=} offset Offset to deduct from the total number. * * @example - +
- Person 1:
- Person 2:
- Number of People:
+
+
+
Without Offset: @@ -24136,65 +33084,372 @@ var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 }); */ -var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) { - var BRACE = /{}/g, - IS_WHEN = /^when(Minus)?(.+)$/; - - return { - restrict: 'EA', - link: function(scope, element, attr) { - var numberExp = attr.count, - whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs - offset = attr.offset || 0, - whens = scope.$eval(whenExp) || {}, - whensExpFns = {}, - startSymbol = $interpolate.startSymbol(), - endSymbol = $interpolate.endSymbol(), - braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol, - watchRemover = angular.noop, - lastCount; +var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) { + var BRACE = /{}/g, + IS_WHEN = /^when(Minus)?(.+)$/; + + return { + link: function(scope, element, attr) { + var numberExp = attr.count, + whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs + offset = attr.offset || 0, + whens = scope.$eval(whenExp) || {}, + whensExpFns = {}, + startSymbol = $interpolate.startSymbol(), + endSymbol = $interpolate.endSymbol(), + braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol, + watchRemover = angular.noop, + lastCount; + + forEach(attr, function(expression, attributeName) { + var tmpMatch = IS_WHEN.exec(attributeName); + if (tmpMatch) { + var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]); + whens[whenKey] = element.attr(attr.$attr[attributeName]); + } + }); + forEach(whens, function(expression, key) { + whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement)); + + }); + + scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) { + var count = parseFloat(newVal); + var countIsNaN = isNumberNaN(count); + + if (!countIsNaN && !(count in whens)) { + // If an explicit number rule such as 1, 2, 3... is defined, just use it. + // Otherwise, check it against pluralization rules in $locale service. + count = $locale.pluralCat(count - offset); + } + + // If both `count` and `lastCount` are NaN, we don't need to re-register a watch. + // In JS `NaN !== NaN`, so we have to explicitly check. + if ((count !== lastCount) && !(countIsNaN && isNumberNaN(lastCount))) { + watchRemover(); + var whenExpFn = whensExpFns[count]; + if (isUndefined(whenExpFn)) { + if (newVal != null) { + $log.debug('ngPluralize: no rule defined for \'' + count + '\' in ' + whenExp); + } + watchRemover = noop; + updateElementText(); + } else { + watchRemover = scope.$watch(whenExpFn, updateElementText); + } + lastCount = count; + } + }); + + function updateElementText(newText) { + element.text(newText || ''); + } + } + }; +}]; + +/** + * @ngdoc directive + * @name ngRef + * @restrict A + * + * @description + * The `ngRef` attribute tells AngularJS to assign the controller of a component (or a directive) + * to the given property in the current scope. It is also possible to add the jqlite-wrapped DOM + * element to the scope. + * + * If the element with `ngRef` is destroyed `null` is assigned to the property. + * + * Note that if you want to assign from a child into the parent scope, you must initialize the + * target property on the parent scope, otherwise `ngRef` will assign on the child scope. + * This commonly happens when assigning elements or components wrapped in {@link ngIf} or + * {@link ngRepeat}. See the second example below. + * + * + * @element ANY + * @param {string} ngRef property name - A valid AngularJS expression identifier to which the + * controller or jqlite-wrapped DOM element will be bound. + * @param {string=} ngRefRead read value - The name of a directive (or component) on this element, + * or the special string `$element`. If a name is provided, `ngRef` will + * assign the matching controller. If `$element` is provided, the element + * itself is assigned (even if a controller is available). + * + * + * @example + * ### Simple toggle + * This example shows how the controller of the component toggle + * is reused in the template through the scope to use its logic. + * + * + * + * + *
+ * You are using a component in the same template to show it. + *
+ *
+ * + * angular.module('myApp', []) + * .component('myToggle', { + * controller: function ToggleController() { + * var opened = false; + * this.isOpen = function() { return opened; }; + * this.toggle = function() { opened = !opened; }; + * } + * }); + * + * + * it('should publish the toggle into the scope', function() { + * var toggle = element(by.buttonText('Toggle')); + * expect(toggle.evaluate('myToggle.isOpen()')).toEqual(false); + * toggle.click(); + * expect(toggle.evaluate('myToggle.isOpen()')).toEqual(true); + * }); + * + *
+ * + * @example + * ### ngRef inside scopes + * This example shows how `ngRef` works with child scopes. The `ngRepeat`-ed `myWrapper` components + * are assigned to the scope of `myRoot`, because the `toggles` property has been initialized. + * The repeated `myToggle` components are published to the child scopes created by `ngRepeat`. + * `ngIf` behaves similarly - the assignment of `myToggle` happens in the `ngIf` child scope, + * because the target property has not been initialized on the `myRoot` component controller. + * + * + * + * + * + * + * angular.module('myApp', []) + * .component('myRoot', { + * templateUrl: 'root.html', + * controller: function() { + * this.wrappers = []; // initialize the array so that the wrappers are assigned into the parent scope + * } + * }) + * .component('myToggle', { + * template: 'myToggle', + * transclude: true, + * controller: function ToggleController() { + * var opened = false; + * this.isOpen = function() { return opened; }; + * this.toggle = function() { opened = !opened; }; + * } + * }) + * .component('myWrapper', { + * transclude: true, + * template: 'myWrapper' + + * '
ngRepeatToggle.isOpen(): {{$ctrl.ngRepeatToggle.isOpen() | json}}
' + + * '' + * }); + *
+ * + * myRoot + * Outer Toggle + *
outerToggle.isOpen(): {{$ctrl.outerToggle.isOpen() | json}}
+ *
wrappers assigned to root
+ *
+ * wrapper.ngRepeatToggle.isOpen(): {{wrapper.ngRepeatToggle.isOpen() | json}} + *
+ * + *
    + *
  • + * ngRepeat + *
    outerToggle.isOpen(): {{$ctrl.outerToggle.isOpen() | json}}
    + * ngRepeat Toggle {{$index + 1}} + *
  • + *
+ * + *
ngIfToggle.isOpen(): {{ngIfToggle.isOpen()}} // This is always undefined because it's + * assigned to the child scope created by ngIf. + *
+ *
+ ngIf + * ngIf Toggle + *
ngIfToggle.isOpen(): {{ngIfToggle.isOpen() | json}}
+ *
outerToggle.isOpen(): {{$ctrl.outerToggle.isOpen() | json}}
+ *
+ * + * + * ul { + * list-style: none; + * padding-left: 0; + * } + * + * li[ng-repeat] { + * background: lightgreen; + * padding: 8px; + * margin: 8px; + * } + * + * [ng-if] { + * background: lightgrey; + * padding: 8px; + * } + * + * my-root { + * background: lightgoldenrodyellow; + * padding: 8px; + * display: block; + * } + * + * my-wrapper { + * background: lightsalmon; + * padding: 8px; + * display: block; + * } + * + * my-toggle { + * background: lightblue; + * padding: 8px; + * display: block; + * } + * + * + * var OuterToggle = function() { + * this.toggle = function() { + * element(by.buttonText('Outer Toggle')).click(); + * }; + * this.isOpen = function() { + * return element.all(by.binding('outerToggle.isOpen()')).first().getText(); + * }; + * }; + * var NgRepeatToggle = function(i) { + * var parent = element.all(by.repeater('(index, value) in [1,2,3]')).get(i - 1); + * this.toggle = function() { + * element(by.buttonText('ngRepeat Toggle ' + i)).click(); + * }; + * this.isOpen = function() { + * return parent.element(by.binding('ngRepeatToggle.isOpen() | json')).getText(); + * }; + * this.isOuterOpen = function() { + * return parent.element(by.binding('outerToggle.isOpen() | json')).getText(); + * }; + * }; + * var NgRepeatToggles = function() { + * var toggles = [1,2,3].map(function(i) { return new NgRepeatToggle(i); }); + * this.forEach = function(fn) { + * toggles.forEach(fn); + * }; + * this.isOuterOpen = function(i) { + * return toggles[i - 1].isOuterOpen(); + * }; + * }; + * var NgIfToggle = function() { + * var parent = element(by.css('[ng-if]')); + * this.toggle = function() { + * element(by.buttonText('ngIf Toggle')).click(); + * }; + * this.isOpen = function() { + * return by.binding('ngIfToggle.isOpen() | json').getText(); + * }; + * this.isOuterOpen = function() { + * return parent.element(by.binding('outerToggle.isOpen() | json')).getText(); + * }; + * }; + * + * it('should toggle the outer toggle', function() { + * var outerToggle = new OuterToggle(); + * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): false'); + * outerToggle.toggle(); + * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): true'); + * }); + * + * it('should toggle all outer toggles', function() { + * var outerToggle = new OuterToggle(); + * var repeatToggles = new NgRepeatToggles(); + * var ifToggle = new NgIfToggle(); + * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): false'); + * expect(repeatToggles.isOuterOpen(1)).toEqual('outerToggle.isOpen(): false'); + * expect(repeatToggles.isOuterOpen(2)).toEqual('outerToggle.isOpen(): false'); + * expect(repeatToggles.isOuterOpen(3)).toEqual('outerToggle.isOpen(): false'); + * expect(ifToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false'); + * outerToggle.toggle(); + * expect(outerToggle.isOpen()).toEqual('outerToggle.isOpen(): true'); + * expect(repeatToggles.isOuterOpen(1)).toEqual('outerToggle.isOpen(): true'); + * expect(repeatToggles.isOuterOpen(2)).toEqual('outerToggle.isOpen(): true'); + * expect(repeatToggles.isOuterOpen(3)).toEqual('outerToggle.isOpen(): true'); + * expect(ifToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): true'); + * }); + * + * it('should toggle each repeat iteration separately', function() { + * var repeatToggles = new NgRepeatToggles(); + * + * repeatToggles.forEach(function(repeatToggle) { + * expect(repeatToggle.isOpen()).toEqual('ngRepeatToggle.isOpen(): false'); + * expect(repeatToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false'); + * repeatToggle.toggle(); + * expect(repeatToggle.isOpen()).toEqual('ngRepeatToggle.isOpen(): true'); + * expect(repeatToggle.isOuterOpen()).toEqual('outerToggle.isOpen(): false'); + * }); + * }); + * + * + * + */ - forEach(attr, function(expression, attributeName) { - var tmpMatch = IS_WHEN.exec(attributeName); - if (tmpMatch) { - var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]); - whens[whenKey] = element.attr(attr.$attr[attributeName]); - } - }); - forEach(whens, function(expression, key) { - whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement)); +var ngRefMinErr = minErr('ngRef'); - }); +var ngRefDirective = ['$parse', function($parse) { + return { + priority: -1, // Needed for compatibility with element transclusion on the same element + restrict: 'A', + compile: function(tElement, tAttrs) { + // Get the expected controller name, converts into "someThing" + var controllerName = directiveNormalize(nodeName_(tElement)); + + // Get the expression for value binding + var getter = $parse(tAttrs.ngRef); + var setter = getter.assign || function() { + throw ngRefMinErr('nonassign', 'Expression in ngRef="{0}" is non-assignable!', tAttrs.ngRef); + }; - scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) { - var count = parseFloat(newVal); - var countIsNaN = isNaN(count); + return function(scope, element, attrs) { + var refValue; - if (!countIsNaN && !(count in whens)) { - // If an explicit number rule such as 1, 2, 3... is defined, just use it. - // Otherwise, check it against pluralization rules in $locale service. - count = $locale.pluralCat(count - offset); + if (attrs.hasOwnProperty('ngRefRead')) { + if (attrs.ngRefRead === '$element') { + refValue = element; + } else { + refValue = element.data('$' + attrs.ngRefRead + 'Controller'); + + if (!refValue) { + throw ngRefMinErr( + 'noctrl', + 'The controller for ngRefRead="{0}" could not be found on ngRef="{1}"', + attrs.ngRefRead, + tAttrs.ngRef + ); + } + } + } else { + refValue = element.data('$' + controllerName + 'Controller'); } - // If both `count` and `lastCount` are NaN, we don't need to re-register a watch. - // In JS `NaN !== NaN`, so we have to exlicitly check. - if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) { - watchRemover(); - watchRemover = scope.$watch(whensExpFns[count], updateElementText); - lastCount = count; - } - }); + refValue = refValue || element; - function updateElementText(newText) { - element.text(newText || ''); - } + setter(scope, refValue); + + // when the element is removed, remove it (nullify it) + element.on('$destroy', function() { + // only remove it if value has not changed, + // because animations (and other procedures) may duplicate elements + if (getter(scope) === refValue) { + setter(scope, null); + } + }); + }; } }; }]; +/* exported ngRepeatDirective */ + /** * @ngdoc directive * @name ngRepeat + * @multiElement + * @restrict A * * @description * The `ngRepeat` directive instantiates a template once per item from a collection. Each template @@ -24212,10 +33467,13 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). | * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). | * - * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}. - * This may be useful when, for instance, nesting ngRepeats. + *
+ * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}. + * This may be useful when, for instance, nesting ngRepeats. + *
* - * # Iterating over object properties + * + * ## Iterating over object properties * * It is possible to get `ngRepeat` to iterate over the properties of an object using the following * syntax: @@ -24224,70 +33482,185 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp *
...
* ``` * - * You need to be aware that the JavaScript specification does not define what order - * it will return the keys for an object. In order to have a guaranteed deterministic order - * for the keys, Angular versions up to and including 1.3 **sort the keys alphabetically**. + * However, there are a few limitations compared to array iteration: + * + * - The JavaScript specification does not define the order of keys + * returned for an object, so AngularJS relies on the order returned by the browser + * when running `for key in myObj`. Browsers generally follow the strategy of providing + * keys in the order in which they were defined, although there are exceptions when keys are deleted + * and reinstated. See the + * [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes). * - * If this is not desired, the recommended workaround is to convert your object into an array - * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could + * - `ngRepeat` will silently *ignore* object keys starting with `$`, because + * it's a prefix used by AngularJS for public (`$`) and private (`$$`) properties. + * + * - The built-in filters {@link ng.orderBy orderBy} and {@link ng.filter filter} do not work with + * objects, and will throw an error if used with one. + * + * If you are hitting any of these limitations, the recommended workaround is to convert your object into an array + * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter) * or implement a `$watch` on the object yourself. * - * In version 1.4 we will remove the sorting, since it seems that browsers generally follow the - * strategy of providing keys in the order in which they were defined, although there are exceptions - * when keys are deleted and reinstated. * + * ## Tracking and Duplicates * - * # Tracking and Duplicates - * - * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM: + * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in + * the collection. When a change happens, `ngRepeat` then makes the corresponding changes to the DOM: * * * When an item is added, a new instance of the template is added to the DOM. * * When an item is removed, its template instance is removed from the DOM. * * When items are reordered, their respective templates are reordered in the DOM. * - * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when - * there are duplicates, it is not possible to maintain a one-to-one mapping between collection - * items and DOM elements. + * To minimize creation of DOM elements, `ngRepeat` uses a function + * to "keep track" of all items in the collection and their corresponding DOM elements. + * For example, if an item is added to the collection, `ngRepeat` will know that all other items + * already have DOM elements, and will not re-render them. * - * If you do need to repeat duplicate items, you can substitute the default tracking behavior - * with your own using the `track by` expression. + * All different types of tracking functions, their syntax, and their support for duplicate + * items in collections can be found in the + * {@link ngRepeat#ngRepeat-arguments ngRepeat expression description}. * - * For example, you may track items by the index of each item in the collection, using the - * special scope property `$index`: - * ```html - *
- * {{n}} - *
- * ``` + *
+ * **Best Practice:** If you are working with objects that have a unique identifier property, you + * should track by this identifier instead of the object instance, + * e.g. `item in items track by item.id`. + * Should you reload your data later, `ngRepeat` will not have to rebuild the DOM elements for items + * it has already rendered, even if the JavaScript objects in the collection have been substituted + * for new ones. For large collections, this significantly improves rendering performance. + *
* - * You may use arbitrary expressions in `track by`, including references to custom functions - * on the scope: - * ```html - *
- * {{n}} - *
- * ``` + * ### Effects of DOM Element re-use * - * If you are working with objects that have an identifier property, you can track - * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat` - * will not have to rebuild the DOM elements for items it has already rendered, even if the - * JavaScript objects in the collection have been substituted for new ones: - * ```html - *
- * {{model.name}} - *
- * ``` + * When DOM elements are re-used, ngRepeat updates the scope for the element, which will + * automatically update any active bindings on the template. However, other + * functionality will not be updated, because the element is not re-created: * - * When no `track by` expression is provided, it is equivalent to tracking by the built-in - * `$id` function, which tracks items by their identity: - * ```html - *
- * {{obj.prop}} - *
- * ``` + * - Directives are not re-compiled + * - {@link guide/expression#one-time-binding one-time expressions} on the repeated template are not + * updated if they have stabilized. + * + * The above affects all kinds of element re-use due to tracking, but may be especially visible + * when tracking by `$index` due to the way ngRepeat re-uses elements. + * + * The following example shows the effects of different actions with tracking: + + + + angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) { + var friends = [ + {name:'John', age:25}, + {name:'Mary', age:40}, + {name:'Peter', age:85} + ]; + + $scope.removeFirst = function() { + $scope.friends.shift(); + }; + + $scope.updateAge = function() { + $scope.friends.forEach(function(el) { + el.age = el.age + 5; + }); + }; + + $scope.copy = function() { + $scope.friends = angular.copy($scope.friends); + }; + + $scope.reset = function() { + $scope.friends = angular.copy(friends); + }; + + $scope.reset(); + }); + + +
+
    +
  1. When you click "Update Age", only the first list updates the age, because all others have + a one-time binding on the age property. If you then click "Copy", the current friend list + is copied, and now the second list updates the age, because the identity of the collection items + has changed and the list must be re-rendered. The 3rd and 4th list stay the same, because all the + items are already known according to their tracking functions. +
  2. +
  3. When you click "Remove First", the 4th list has the wrong age on both remaining items. This is + due to tracking by $index: when the first collection item is removed, ngRepeat reuses the first + DOM element for the new first collection item, and so on. Since the age property is one-time + bound, the value remains from the collection item which was previously at this index. +
  4. +
+ + + + +
+
+ track by $id(friend) (default): +
    +
  • + {{friend.name}} is {{friend.age}} years old. +
  • +
+ track by $id(friend) (default), with age one-time binding: +
    +
  • + {{friend.name}} is {{::friend.age}} years old. +
  • +
+ track by friend.name, with age one-time binding: +
    +
  • + {{friend.name}} is {{::friend.age}} years old. +
  • +
+ track by $index, with age one-time binding: +
    +
  • + {{friend.name}} is {{::friend.age}} years old. +
  • +
+
+
+ + .example-animate-container { + background:white; + border:1px solid black; + list-style:none; + margin:0; + padding:0 10px; + } + + .animate-repeat { + line-height:30px; + list-style:none; + box-sizing:border-box; + } + + .animate-repeat.ng-move, + .animate-repeat.ng-enter, + .animate-repeat.ng-leave { + transition:all linear 0.5s; + } + + .animate-repeat.ng-leave.ng-leave-active, + .animate-repeat.ng-move, + .animate-repeat.ng-enter { + opacity:0; + max-height:0; + } + + .animate-repeat.ng-leave, + .animate-repeat.ng-move.ng-move-active, + .animate-repeat.ng-enter.ng-enter-active { + opacity:1; + max-height:30px; + } + +
+ * - * # Special repeat start and end points + * ## Special repeat start and end points * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively. * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on) @@ -24332,11 +33705,13 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**). * * @animations - * **.enter** - when a new item is added to the list or when an item is revealed after a filter + * | Animation | Occurs | + * |----------------------------------|-------------------------------------| + * | {@link ng.$animate#enter enter} | when a new item is added to the list or when an item is revealed after a filter | + * | {@link ng.$animate#leave leave} | when an item is removed from the list or when an item is filtered out | + * | {@link ng.$animate#move move } | when an adjacent item is filtered out causing a reorder or when the item contents are reordered | * - * **.leave** - when an item is removed from the list or when an item is filtered out - * - * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered + * See the example below for defining CSS animations with ngRepeat. * * @element ANY * @scope @@ -24358,23 +33733,40 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression * is specified, ng-repeat associates elements by identity. It is an error to have * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are - * mapped to the same DOM element, which is not possible.) If filters are used in the expression, they should be - * applied before the tracking expression. - * - * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements - * will be associated by item identity in the array. - * - * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique - * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements - * with the corresponding item in the array by identity. Moving the same object in array would move the DOM - * element in the same way in the DOM. - * - * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this - * case the object identity does not matter. Two objects are considered equivalent as long as their `id` - * property is same. + * mapped to the same DOM element, which is not possible.) + * + * *Default tracking: $id()*: `item in items` is equivalent to `item in items track by $id(item)`. + * This implies that the DOM elements will be associated by item identity in the collection. + * + * The built-in `$id()` function can be used to assign a unique + * `$$hashKey` property to each item in the collection. This property is then used as a key to associated DOM elements + * with the corresponding item in the collection by identity. Moving the same object would move + * the DOM element in the same way in the DOM. + * Note that the default id function does not support duplicate primitive values (`number`, `string`), + * but supports duplictae non-primitive values (`object`) that are *equal* in shape. + * + * *Custom Expression*: It is possible to use any AngularJS expression to compute the tracking + * id, for example with a function, or using a property on the collection items. + * `item in items track by item.id` is a typical pattern when the items have a unique identifier, + * e.g. database id. In this case the object identity does not matter. Two objects are considered + * equivalent as long as their `id` property is same. + * Tracking by unique identifier is the most performant way and should be used whenever possible. + * + * *$index*: This special property tracks the collection items by their index, and + * re-uses the DOM elements that match that index, e.g. `item in items track by $index`. This can + * be used for a performance improvement if no unique identfier is available and the identity of + * the collection items cannot be easily computed. It also allows duplicates. + * + *
+ * Note: Re-using DOM elements can have unforeseen effects. Read the + * {@link ngRepeat#tracking-and-duplicates section on tracking and duplicates} for + * more info. + *
* - * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter - * to items in conjunction with a tracking expression. + *
+ * Note: the `track by` expression must come last - after any filters, and the alias expression: + * `item in items | filter:searchText as results track by item.id` + *
* * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message @@ -24383,35 +33775,45 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after * the items have been processed through the filter. * + * Please note that `as [variable name]` is not an operator but rather a part of ngRepeat + * micro-syntax so it can be used only after all filters (and not as operator, inside an expression). + * + * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results track by item.id` . + * * @example - * This example initializes the scope to a list of names and - * then uses `ngRepeat` to display every person: - + * This example uses `ngRepeat` to display a list of people. A filter is used to restrict the displayed + * results by name or by age. New (entering) and removed (leaving) items are animated. + -
+
I have {{friends.length}} friends. They are: - +
    -
  • +
  • [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  • -
  • +
  • No results found...
+ + angular.module('ngRepeat', ['ngAnimate']).controller('repeatController', function($scope) { + $scope.friends = [ + {name:'John', age:25, gender:'boy'}, + {name:'Jessie', age:30, gender:'girl'}, + {name:'Johanna', age:28, gender:'girl'}, + {name:'Joy', age:15, gender:'girl'}, + {name:'Mary', age:28, gender:'girl'}, + {name:'Peter', age:95, gender:'boy'}, + {name:'Sebastian', age:50, gender:'boy'}, + {name:'Erika', age:27, gender:'girl'}, + {name:'Patrick', age:40, gender:'boy'}, + {name:'Samantha', age:60, gender:'girl'} + ]; + }); + .example-animate-container { background:white; @@ -24422,7 +33824,7 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp } .animate-repeat { - line-height:40px; + line-height:30px; list-style:none; box-sizing:border-box; } @@ -24430,7 +33832,6 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp .animate-repeat.ng-move, .animate-repeat.ng-enter, .animate-repeat.ng-leave { - -webkit-transition:all linear 0.5s; transition:all linear 0.5s; } @@ -24445,7 +33846,7 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp .animate-repeat.ng-move.ng-move-active, .animate-repeat.ng-enter.ng-enter-active { opacity:1; - max-height:40px; + max-height:30px; } @@ -24472,7 +33873,7 @@ var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interp */ -var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { +var ngRepeatDirective = ['$parse', '$animate', '$compile', function($parse, $animate, $compile) { var NG_REMOVED = '$$NG_REMOVED'; var ngRepeatMinErr = minErr('ngRepeat'); @@ -24484,9 +33885,8 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { scope.$first = (index === 0); scope.$last = (index === (arrayLength - 1)); scope.$middle = !(scope.$first || scope.$last); - // jshint bitwise: false - scope.$odd = !(scope.$even = (index&1) === 0); - // jshint bitwise: true + // eslint-disable-next-line no-bitwise + scope.$odd = !(scope.$even = (index & 1) === 0); }; var getBlockStart = function(block) { @@ -24497,6 +33897,13 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { return block.clone[block.clone.length - 1]; }; + var trackByIdArrayFn = function($scope, key, value) { + return hashKey(value); + }; + + var trackByIdObjFn = function($scope, key) { + return key; + }; return { restrict: 'A', @@ -24507,12 +33914,12 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { $$tlb: true, compile: function ngRepeatCompile($element, $attr) { var expression = $attr.ngRepeat; - var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' '); + var ngRepeatEndComment = $compile.$$createComment('end ngRepeat', expression); var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/); if (!match) { - throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.", + throw ngRepeatMinErr('iexp', 'Expected expression in form of \'_item_ in _collection_[ track by _id_]\' but got \'{0}\'.', expression); } @@ -24521,10 +33928,10 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { var aliasAs = match[3]; var trackByExp = match[4]; - match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/); + match = lhs.match(/^(?:(\s*[$\w]+)|\(\s*([$\w]+)\s*,\s*([$\w]+)\s*\))$/); if (!match) { - throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.", + throw ngRepeatMinErr('iidexp', '\'_item_\' in \'_item_ in _collection_\' should be an identifier or \'(_key_, _value_)\' expression, but got \'{0}\'.', lhs); } var valueIdentifier = match[3] || match[1]; @@ -24532,40 +33939,31 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) || /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) { - throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.", + throw ngRepeatMinErr('badident', 'alias \'{0}\' is invalid --- must be a valid JS identifier which is not a reserved name.', aliasAs); } - var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn; - var hashFnLocals = {$id: hashKey}; + var trackByIdExpFn; if (trackByExp) { - trackByExpGetter = $parse(trackByExp); - } else { - trackByIdArrayFn = function(key, value) { - return hashKey(value); - }; - trackByIdObjFn = function(key) { - return key; + var hashFnLocals = {$id: hashKey}; + var trackByExpGetter = $parse(trackByExp); + + trackByIdExpFn = function($scope, key, value, index) { + // assign key, value, and $index to the locals so that they can be used in hash functions + if (keyIdentifier) hashFnLocals[keyIdentifier] = key; + hashFnLocals[valueIdentifier] = value; + hashFnLocals.$index = index; + return trackByExpGetter($scope, hashFnLocals); }; } return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) { - if (trackByExpGetter) { - trackByIdExpFn = function(key, value, index) { - // assign key, value, and $index to the locals so that they can be used in hash functions - if (keyIdentifier) hashFnLocals[keyIdentifier] = key; - hashFnLocals[valueIdentifier] = value; - hashFnLocals.$index = index; - return trackByExpGetter($scope, hashFnLocals); - }; - } - // Store a list of elements from previous run. This is a hash where key is the item from the // iterator, and the value is objects with following properties. // - scope: bound scope - // - element: previous element. + // - clone: previous element. // - index: position // // We are using no-proto object so that we don't need to guard against inherited props via @@ -24599,14 +33997,13 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { trackByIdFn = trackByIdExpFn || trackByIdArrayFn; } else { trackByIdFn = trackByIdExpFn || trackByIdObjFn; - // if object, extract keys, sort them and use to determine order of iteration over obj props + // if object, extract keys, in enumeration order, unsorted collectionKeys = []; for (var itemKey in collection) { - if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') { + if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') { collectionKeys.push(itemKey); } } - collectionKeys.sort(); } collectionLength = collectionKeys.length; @@ -24616,7 +34013,7 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { for (index = 0; index < collectionLength; index++) { key = (collection === collectionKeys) ? index : collectionKeys[index]; value = collection[key]; - trackById = trackByIdFn(key, value, index); + trackById = trackByIdFn($scope, key, value, index); if (lastBlockMap[trackById]) { // found previously seen block block = lastBlockMap[trackById]; @@ -24629,7 +34026,7 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { if (block && block.scope) lastBlockMap[block.id] = block; }); throw ngRepeatMinErr('dupes', - "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}", + 'Duplicates in a repeater are not allowed. Use \'track by\' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}', expression, trackById, value); } else { // new never before seen block @@ -24638,6 +34035,12 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { } } + // Clear the value property from the hashFnLocals object to prevent a reference to the last value + // being leaked into the ngRepeatCompile function scope + if (hashFnLocals) { + hashFnLocals[valueIdentifier] = undefined; + } + // remove leftover items for (var blockKey in lastBlockMap) { block = lastBlockMap[blockKey]; @@ -24670,9 +34073,9 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { nextNode = nextNode.nextSibling; } while (nextNode && nextNode[NG_REMOVED]); - if (getBlockStart(block) != nextNode) { + if (getBlockStart(block) !== nextNode) { // existing item which got moved - $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode)); + $animate.move(getBlockNodes(block.clone), null, previousNode); } previousNode = getBlockEnd(block); updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength); @@ -24684,8 +34087,7 @@ var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) { var endNode = ngRepeatEndComment.cloneNode(false); clone[clone.length++] = endNode; - // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper? - $animate.enter(clone, null, jqLite(previousNode)); + $animate.enter(clone, null, previousNode); previousNode = endNode; // 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 @@ -24708,13 +34110,16 @@ var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate'; /** * @ngdoc directive * @name ngShow + * @multiElement * * @description - * The `ngShow` directive shows or hides the given HTML element based on the expression - * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding - * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined - * in AngularJS and sets the display style to none (using an !important flag). - * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). + * The `ngShow` directive shows or hides the given HTML element based on the expression provided to + * the `ngShow` attribute. + * + * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element. + * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an + * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see + * {@link ng.directive:ngCsp ngCsp}). * * ```html * @@ -24724,31 +34129,32 @@ var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate'; *
* ``` * - * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class - * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed - * from the element causing the element not to appear hidden. + * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added + * to the class attribute on the element causing it to become hidden. When truthy, the `.ng-hide` + * CSS class is removed from the element causing the element not to appear hidden. * - * ## Why is !important used? + * ## Why is `!important` used? * - * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector - * can be easily overridden by heavier selectors. For example, something as simple - * as changing the display style on a HTML list item would make hidden elements appear visible. - * This also becomes a bigger issue when dealing with CSS frameworks. + * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the + * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as + * simple as changing the display style on a HTML list item would make hidden elements appear + * visible. This also becomes a bigger issue when dealing with CSS frameworks. * - * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector - * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the - * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. + * By using `!important`, the show and hide behavior will work as expected despite any clash between + * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a + * developer chooses to override the styling to change how to hide an element then it is just a + * matter of using `!important` in their own CSS code. * * ### Overriding `.ng-hide` * - * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change - * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` - * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope - * with extra animation classes that can be added. + * By default, the `.ng-hide` class will style the element with `display: none !important`. If you + * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for + * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually + * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added. * * ```css * .ng-hide:not(.ng-hide-animate) { - * /* this is just another form of hiding an element */ + * /* These are just alternative ways of hiding an element */ * display: block!important; * position: absolute; * top: -9999px; @@ -24756,29 +34162,24 @@ var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate'; * } * ``` * - * By default you don't need to override in CSS anything and the animations will work around the display style. + * By default you don't need to override anything in CSS and the animations will work around the + * display style. * - * ## A note about animations with `ngShow` + * @animations + * | Animation | Occurs | + * |-----------------------------------------------------|---------------------------------------------------------------------------------------------------------------| + * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden. | + * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngShow` expression evaluates to a truthy value and just before contents are set to visible. | * - * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression - * is true and false. This system works like the animation system present with ngClass except that - * you must also include the !important flag to override the display property - * so that you can perform an animation when the element is hidden during the time of the animation. + * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the + * directive expression is true and false. This system works like the animation system present with + * `ngClass` except that you must also include the `!important` flag to override the display + * property so that the elements are not actually hidden during the animation. * * ```css - * // - * //a working example can be found at the bottom of this page - * // + * /* A working example can be found at the bottom of this page. */ * .my-element.ng-hide-add, .my-element.ng-hide-remove { - * /* this is required as of 1.3x to properly - * apply all styling in a show/hide animation */ - * transition: 0s linear all; - * } - * - * .my-element.ng-hide-add-active, - * .my-element.ng-hide-remove-active { - * /* the transition is defined in the active class */ - * transition: 1s linear all; + * transition: all 0.5s linear; * } * * .my-element.ng-hide-add { ... } @@ -24787,79 +34188,124 @@ var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate'; * .my-element.ng-hide-remove.ng-hide-remove-active { ... } * ``` * - * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display - * property to block during animation states--ngAnimate will handle the style toggling automatically for you. - * - * @animations - * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible - * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden + * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property + * to block during animation states - ngAnimate will automatically handle the style toggling for you. * * @element ANY - * @param {expression} ngShow If the {@link guide/expression expression} is truthy - * then the element is shown or hidden respectively. + * @param {expression} ngShow If the {@link guide/expression expression} is truthy/falsy then the + * element is shown/hidden respectively. * * @example - + * A simple example, animating the element's opacity: + * + - Click me:
-
- Show: -
- I show up when your checkbox is checked. -
-
-
- Hide: -
- I hide when your checkbox is checked. -
+ Show:
+
+ I show up when your checkbox is checked.
- - @import url(../../components/bootstrap-3.1.1/css/bootstrap.css); - - .animate-show { - line-height: 20px; + .animate-show-hide.ng-hide { + opacity: 0; + } + + .animate-show-hide.ng-hide-add, + .animate-show-hide.ng-hide-remove { + transition: all linear 0.5s; + } + + .check-element { + border: 1px solid black; opacity: 1; padding: 10px; - border: 1px solid black; - background: white; } + + + it('should check ngShow', function() { + var checkbox = element(by.model('checked')); + var checkElem = element(by.css('.check-element')); - .animate-show.ng-hide-add.ng-hide-add-active, - .animate-show.ng-hide-remove.ng-hide-remove-active { - -webkit-transition: all linear 0.5s; - transition: all linear 0.5s; + expect(checkElem.isDisplayed()).toBe(false); + checkbox.click(); + expect(checkElem.isDisplayed()).toBe(true); + }); + + + * + *
+ * @example + * A more complex example, featuring different show/hide animations: + * + + + Show:
+
+ I show up when your checkbox is checked. +
+
+ + body { + overflow: hidden; + perspective: 1000px; } - .animate-show.ng-hide { - line-height: 0; - opacity: 0; - padding: 0 10px; + .funky-show-hide.ng-hide-add { + transform: rotateZ(0); + transform-origin: right; + transition: all 0.5s ease-in-out; + } + + .funky-show-hide.ng-hide-add.ng-hide-add-active { + transform: rotateZ(-135deg); + } + + .funky-show-hide.ng-hide-remove { + transform: rotateY(90deg); + transform-origin: left; + transition: all 0.5s ease; + } + + .funky-show-hide.ng-hide-remove.ng-hide-remove-active { + transform: rotateY(0); } .check-element { - padding: 10px; border: 1px solid black; - background: white; + opacity: 1; + padding: 10px; } - var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); - var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); - - it('should check ng-show / ng-hide', function() { - expect(thumbsUp.isDisplayed()).toBeFalsy(); - expect(thumbsDown.isDisplayed()).toBeTruthy(); + it('should check ngShow', function() { + var checkbox = element(by.model('checked')); + var checkElem = element(by.css('.check-element')); - element(by.model('checked')).click(); - - expect(thumbsUp.isDisplayed()).toBeTruthy(); - expect(thumbsDown.isDisplayed()).toBeFalsy(); + expect(checkElem.isDisplayed()).toBe(false); + checkbox.click(); + expect(checkElem.isDisplayed()).toBe(true); });
+ * + * @knownIssue + * + * ### Flickering when using ngShow to toggle between elements + * + * When using {@link ngShow} and / or {@link ngHide} to toggle between elements, it can + * happen that both the element to show and the element to hide are visible for a very short time. + * + * This usually happens when the {@link ngAnimate ngAnimate module} is included, but no actual animations + * are defined for {@link ngShow} / {@link ngHide}. Internet Explorer is affected more often than + * other browsers. + * + * There are several way to mitigate this problem: + * + * - {@link guide/animations#how-to-selectively-enable-disable-and-skip-animations Disable animations on the affected elements}. + * - Use {@link ngIf} or {@link ngSwitch} instead of {@link ngShow} / {@link ngHide}. + * - Use the special CSS selector `ng-hide.ng-hide-animate` to set `{display: none}` or similar on the affected elements. + * - Use `ng-class="{'ng-hide': expression}` instead of instead of {@link ngShow} / {@link ngHide}. + * - Define an animation on the affected elements. */ var ngShowDirective = ['$animate', function($animate) { return { @@ -24883,13 +34329,16 @@ var ngShowDirective = ['$animate', function($animate) { /** * @ngdoc directive * @name ngHide + * @multiElement * * @description - * The `ngHide` directive shows or hides the given HTML element based on the expression - * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding - * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined - * in AngularJS and sets the display style to none (using an !important flag). - * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}). + * The `ngHide` directive shows or hides the given HTML element based on the expression provided to + * the `ngHide` attribute. + * + * The element is shown or hidden by removing or adding the `.ng-hide` CSS class onto the element. + * The `.ng-hide` CSS class is predefined in AngularJS and sets the display style to none (using an + * `!important` flag). For CSP mode please add `angular-csp.css` to your HTML file (see + * {@link ng.directive:ngCsp ngCsp}). * * ```html * @@ -24899,30 +34348,32 @@ var ngShowDirective = ['$animate', function($animate) { *
* ``` * - * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class - * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed - * from the element causing the element not to appear hidden. + * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added + * to the class attribute on the element causing it to become hidden. When falsy, the `.ng-hide` + * CSS class is removed from the element causing the element not to appear hidden. * - * ## Why is !important used? + * ## Why is `!important` used? * - * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector - * can be easily overridden by heavier selectors. For example, something as simple - * as changing the display style on a HTML list item would make hidden elements appear visible. - * This also becomes a bigger issue when dealing with CSS frameworks. + * You may be wondering why `!important` is used for the `.ng-hide` CSS class. This is because the + * `.ng-hide` selector can be easily overridden by heavier selectors. For example, something as + * simple as changing the display style on a HTML list item would make hidden elements appear + * visible. This also becomes a bigger issue when dealing with CSS frameworks. * - * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector - * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the - * styling to change how to hide an element then it is just a matter of using !important in their own CSS code. + * By using `!important`, the show and hide behavior will work as expected despite any clash between + * CSS selector specificity (when `!important` isn't used with any conflicting styles). If a + * developer chooses to override the styling to change how to hide an element then it is just a + * matter of using `!important` in their own CSS code. * * ### Overriding `.ng-hide` * - * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change - * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide` - * class in CSS: + * By default, the `.ng-hide` class will style the element with `display: none !important`. If you + * wish to change the hide behavior with `ngShow`/`ngHide`, you can simply overwrite the styles for + * the `.ng-hide` CSS class. Note that the selector that needs to be used is actually + * `.ng-hide:not(.ng-hide-animate)` to cope with extra animation classes that can be added. * * ```css - * .ng-hide { - * /* this is just another form of hiding an element */ + * .ng-hide:not(.ng-hide-animate) { + * /* These are just alternative ways of hiding an element */ * display: block!important; * position: absolute; * top: -9999px; @@ -24930,20 +34381,24 @@ var ngShowDirective = ['$animate', function($animate) { * } * ``` * - * By default you don't need to override in CSS anything and the animations will work around the display style. + * By default you don't need to override in CSS anything and the animations will work around the + * display style. * - * ## A note about animations with `ngHide` + * @animations + * | Animation | Occurs | + * |-----------------------------------------------------|------------------------------------------------------------------------------------------------------------| + * | {@link $animate#addClass addClass} `.ng-hide` | After the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden. | + * | {@link $animate#removeClass removeClass} `.ng-hide` | After the `ngHide` expression evaluates to a non truthy value and just before contents are set to visible. | * - * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression - * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide` - * CSS class is added and removed for you instead of your own CSS class. + * Animations in `ngShow`/`ngHide` work with the show and hide events that are triggered when the + * directive expression is true and false. This system works like the animation system present with + * `ngClass` except that you must also include the `!important` flag to override the display + * property so that the elements are not actually hidden during the animation. * * ```css - * // - * //a working example can be found at the bottom of this page - * // + * /* A working example can be found at the bottom of this page. */ * .my-element.ng-hide-add, .my-element.ng-hide-remove { - * transition: 0.5s linear all; + * transition: all 0.5s linear; * } * * .my-element.ng-hide-add { ... } @@ -24952,75 +34407,124 @@ var ngShowDirective = ['$animate', function($animate) { * .my-element.ng-hide-remove.ng-hide-remove-active { ... } * ``` * - * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display - * property to block during animation states--ngAnimate will handle the style toggling automatically for you. - * - * @animations - * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden - * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible + * Keep in mind that, as of AngularJS version 1.3, there is no need to change the display property + * to block during animation states - ngAnimate will automatically handle the style toggling for you. * * @element ANY - * @param {expression} ngHide If the {@link guide/expression expression} is truthy then - * the element is shown or hidden respectively. + * @param {expression} ngHide If the {@link guide/expression expression} is truthy/falsy then the + * element is hidden/shown respectively. * * @example - + * A simple example, animating the element's opacity: + * + - Click me:
-
- Show: -
- I show up when your checkbox is checked. -
-
-
- Hide: -
- I hide when your checkbox is checked. -
+ Hide:
+
+ I hide when your checkbox is checked.
- - @import url(../../components/bootstrap-3.1.1/css/bootstrap.css); - - .animate-hide { - -webkit-transition: all linear 0.5s; + .animate-show-hide.ng-hide { + opacity: 0; + } + + .animate-show-hide.ng-hide-add, + .animate-show-hide.ng-hide-remove { transition: all linear 0.5s; - line-height: 20px; + } + + .check-element { + border: 1px solid black; opacity: 1; padding: 10px; - border: 1px solid black; - background: white; } + + + it('should check ngHide', function() { + var checkbox = element(by.model('checked')); + var checkElem = element(by.css('.check-element')); - .animate-hide.ng-hide { - line-height: 0; - opacity: 0; - padding: 0 10px; + expect(checkElem.isDisplayed()).toBe(true); + checkbox.click(); + expect(checkElem.isDisplayed()).toBe(false); + }); + + + * + *
+ * @example + * A more complex example, featuring different show/hide animations: + * + + + Hide:
+
+ I hide when your checkbox is checked. +
+
+ + body { + overflow: hidden; + perspective: 1000px; + } + + .funky-show-hide.ng-hide-add { + transform: rotateZ(0); + transform-origin: right; + transition: all 0.5s ease-in-out; + } + + .funky-show-hide.ng-hide-add.ng-hide-add-active { + transform: rotateZ(-135deg); + } + + .funky-show-hide.ng-hide-remove { + transform: rotateY(90deg); + transform-origin: left; + transition: all 0.5s ease; + } + + .funky-show-hide.ng-hide-remove.ng-hide-remove-active { + transform: rotateY(0); } .check-element { - padding: 10px; border: 1px solid black; - background: white; + opacity: 1; + padding: 10px; } - var thumbsUp = element(by.css('span.glyphicon-thumbs-up')); - var thumbsDown = element(by.css('span.glyphicon-thumbs-down')); - - it('should check ng-show / ng-hide', function() { - expect(thumbsUp.isDisplayed()).toBeFalsy(); - expect(thumbsDown.isDisplayed()).toBeTruthy(); + it('should check ngHide', function() { + var checkbox = element(by.model('checked')); + var checkElem = element(by.css('.check-element')); - element(by.model('checked')).click(); - - expect(thumbsUp.isDisplayed()).toBeTruthy(); - expect(thumbsDown.isDisplayed()).toBeFalsy(); + expect(checkElem.isDisplayed()).toBe(true); + checkbox.click(); + expect(checkElem.isDisplayed()).toBe(false); });
+ * + * @knownIssue + * + * ### Flickering when using ngHide to toggle between elements + * + * When using {@link ngShow} and / or {@link ngHide} to toggle between elements, it can + * happen that both the element to show and the element to hide are visible for a very short time. + * + * This usually happens when the {@link ngAnimate ngAnimate module} is included, but no actual animations + * are defined for {@link ngShow} / {@link ngHide}. Internet Explorer is affected more often than + * other browsers. + * + * There are several way to mitigate this problem: + * + * - {@link guide/animations#how-to-selectively-enable-disable-and-skip-animations Disable animations on the affected elements}. + * - Use {@link ngIf} or {@link ngSwitch} instead of {@link ngShow} / {@link ngHide}. + * - Use the special CSS selector `ng-hide.ng-hide-animate` to set `{display: none}` or similar on the affected elements. + * - Use `ng-class="{'ng-hide': expression}` instead of instead of {@link ngShow} / {@link ngHide}. + * - Define an animation on the affected elements. */ var ngHideDirective = ['$animate', function($animate) { return { @@ -25046,6 +34550,11 @@ var ngHideDirective = ['$animate', function($animate) { * @description * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally. * + * @knownIssue + * You should not use {@link guide/interpolation interpolation} in the value of the `style` + * attribute, when using the `ngStyle` directive on the same element. + * See {@link guide/interpolation#known-issues here} for more info. + * * @element ANY * @param {expression} ngStyle * @@ -25057,7 +34566,7 @@ var ngHideDirective = ['$animate', function($animate) { * See the 'background-color' style in the example below. * * @example - + @@ -25075,11 +34584,11 @@ var ngHideDirective = ['$animate', function($animate) { var colorSpan = element(by.css('span')); it('should check ng-style', function() { - expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); + expect(colorSpan.getCssValue('color')).toMatch(/rgba\(0, 0, 0, 1\)|rgb\(0, 0, 0\)/); element(by.css('input[value=\'set color\']')).click(); - expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)'); + expect(colorSpan.getCssValue('color')).toMatch(/rgba\(255, 0, 0, 1\)|rgb\(255, 0, 0\)/); element(by.css('input[value=clear]')).click(); - expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)'); + expect(colorSpan.getCssValue('color')).toMatch(/rgba\(0, 0, 0, 1\)|rgb\(0, 0, 0\)/); }); @@ -25087,7 +34596,7 @@ var ngHideDirective = ['$animate', function($animate) { var ngStyleDirective = ngDirective(function(scope, element, attr) { scope.$watchCollection(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) { if (oldStyles && (newStyles !== oldStyles)) { - forEach(oldStyles, function(val, style) { element.css(style, '');}); + forEach(oldStyles, function(val, style) { element.css(style, ''); }); } if (newStyles) element.css(newStyles); }); @@ -25120,8 +34629,10 @@ var ngStyleDirective = ngDirective(function(scope, element, attr) { *
* @animations - * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container - * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM + * | Animation | Occurs | + * |----------------------------------|-------------------------------------| + * | {@link ng.$animate#enter enter} | after the ngSwitch contents change and the matched child element is placed inside the container | + * | {@link ng.$animate#leave leave} | after the ngSwitch contents change and just before the former contents are removed from the DOM | * * @usage * @@ -25136,28 +34647,32 @@ var ngStyleDirective = ngDirective(function(scope, element, attr) { * * @scope * @priority 1200 - * @param {*} ngSwitch|on expression to match against ng-switch-when. + * @param {*} ngSwitch|on expression to match against ng-switch-when. * On child elements add: * * * `ngSwitchWhen`: the case statement to match against. If match then this * case will be displayed. If the same match appears multiple times, all the - * elements will be displayed. + * elements will be displayed. It is possible to associate multiple values to + * the same `ngSwitchWhen` by defining the optional attribute + * `ngSwitchWhenSeparator`. The separator will be used to split the value of + * the `ngSwitchWhen` attribute into multiple tokens, and the element will show + * if any of the `ngSwitch` evaluates to any of these tokens. * * `ngSwitchDefault`: the default case when no other case match. If there * are multiple default cases, all of them will be displayed when no other * case match. * * * @example - +
- selection={{selection}} + selection={{selection}}
-
Settings Div
+
Settings Div
Home Span
default
@@ -25166,7 +34681,7 @@ var ngStyleDirective = ngDirective(function(scope, element, attr) { angular.module('switchExample', ['ngAnimate']) .controller('ExampleController', ['$scope', function($scope) { - $scope.items = ['settings', 'home', 'other']; + $scope.items = ['settings', 'home', 'options', 'other']; $scope.selection = $scope.items[0]; }]); @@ -25184,7 +34699,6 @@ var ngStyleDirective = ngDirective(function(scope, element, attr) { } .animate-switch.ng-animate { - -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; position:absolute; @@ -25214,20 +34728,23 @@ var ngStyleDirective = ngDirective(function(scope, element, attr) { select.all(by.css('option')).get(1).click(); expect(switchElem.getText()).toMatch(/Home Span/); }); - it('should select default', function() { + it('should change to settings via "options"', function() { select.all(by.css('option')).get(2).click(); + expect(switchElem.getText()).toMatch(/Settings Div/); + }); + it('should select default', function() { + select.all(by.css('option')).get(3).click(); expect(switchElem.getText()).toMatch(/default/); }); */ -var ngSwitchDirective = ['$animate', function($animate) { +var ngSwitchDirective = ['$animate', '$compile', function($animate, $compile) { return { - restrict: 'EA', require: 'ngSwitch', // asks for $scope to fool the BC controller module - controller: ['$scope', function ngSwitchController() { + controller: ['$scope', function NgSwitchController() { this.cases = {}; }], link: function(scope, element, attr, ngSwitchController) { @@ -25238,21 +34755,24 @@ var ngSwitchDirective = ['$animate', function($animate) { selectedScopes = []; var spliceFactory = function(array, index) { - return function() { array.splice(index, 1); }; + return function(response) { + if (response !== false) array.splice(index, 1); + }; }; scope.$watch(watchExpr, function ngSwitchWatchAction(value) { var i, ii; - for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) { - $animate.cancel(previousLeaveAnimations[i]); + + // Start with the last, in case the array is modified during the loop + while (previousLeaveAnimations.length) { + $animate.cancel(previousLeaveAnimations.pop()); } - previousLeaveAnimations.length = 0; for (i = 0, ii = selectedScopes.length; i < ii; ++i) { var selected = getBlockNodes(selectedElements[i].clone); selectedScopes[i].$destroy(); - var promise = previousLeaveAnimations[i] = $animate.leave(selected); - promise.then(spliceFactory(previousLeaveAnimations, i)); + var runner = previousLeaveAnimations[i] = $animate.leave(selected); + runner.done(spliceFactory(previousLeaveAnimations, i)); } selectedElements.length = 0; @@ -25263,7 +34783,7 @@ var ngSwitchDirective = ['$animate', function($animate) { selectedTransclude.transclude(function(caseElement, selectedScope) { selectedScopes.push(selectedScope); var anchor = selectedTransclude.element; - caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: '); + caseElement[caseElement.length++] = $compile.$$createComment('end ngSwitchWhen'); var block = { clone: caseElement }; selectedElements.push(block); @@ -25282,8 +34802,16 @@ var ngSwitchWhenDirective = ngDirective({ require: '^ngSwitch', multiElement: true, link: function(scope, element, attrs, ctrl, $transclude) { - ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []); - ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element }); + + var cases = attrs.ngSwitchWhen.split(attrs.ngSwitchWhenSeparator).sort().filter( + // Filter duplicate cases + function(element, index, array) { return array[index - 1] !== element; } + ); + + forEach(cases, function(whenCase) { + ctrl.cases['!' + whenCase] = (ctrl.cases['!' + whenCase] || []); + ctrl.cases['!' + whenCase].push({ transclude: $transclude, element: element }); + }); } }); @@ -25306,69 +34834,222 @@ var ngSwitchDefaultDirective = ngDirective({ * @description * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion. * - * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted. + * You can specify that you want to insert a named transclusion slot, instead of the default slot, by providing the slot name + * as the value of the `ng-transclude` or `ng-transclude-slot` attribute. + * + * If the transcluded content is not empty (i.e. contains one or more DOM nodes, including whitespace text nodes), any existing + * content of this element will be removed before the transcluded content is inserted. + * If the transcluded content is empty (or only whitespace), the existing content is left intact. This lets you provide fallback + * content in the case that no transcluded content is provided. * * @element ANY * + * @param {string} ngTransclude|ngTranscludeSlot the name of the slot to insert at this point. If this is not provided, is empty + * or its value is the same as the name of the attribute then the default slot is used. + * * @example - - - -
-
-
- {{text}} -
-
- - it('should have transcluded', function() { - var titleElement = element(by.model('title')); - titleElement.clear(); - titleElement.sendKeys('TITLE'); - var textElement = element(by.model('text')); - textElement.clear(); - textElement.sendKeys('TEXT'); - expect(element(by.binding('title')).getText()).toEqual('TITLE'); - expect(element(by.binding('text')).getText()).toEqual('TEXT'); - }); - -
+ * ### Basic transclusion + * This example demonstrates basic transclusion of content into a component directive. + * + * + * + *
+ *
+ *
+ * {{text}} + *
+ *
+ * + * it('should have transcluded', function() { + * var titleElement = element(by.model('title')); + * titleElement.clear(); + * titleElement.sendKeys('TITLE'); + * var textElement = element(by.model('text')); + * textElement.clear(); + * textElement.sendKeys('TEXT'); + * expect(element(by.binding('title')).getText()).toEqual('TITLE'); + * expect(element(by.binding('text')).getText()).toEqual('TEXT'); + * }); + * + *
+ * + * @example + * ### Transclude fallback content + * This example shows how to use `NgTransclude` with fallback content, that + * is displayed if no transcluded content is provided. + * + * + * + * + * + * + * + * + * Button2 + * + * + * + * it('should have different transclude element content', function() { + * expect(element(by.id('fallback')).getText()).toBe('Button1'); + * expect(element(by.id('modified')).getText()).toBe('Button2'); + * }); + * + * * + * @example + * ### Multi-slot transclusion + * This example demonstrates using multi-slot transclusion in a component directive. + * + * + * + *
+ *
+ *
+ * + * {{title}} + *

{{text}}

+ *
+ *
+ *
+ * + * angular.module('multiSlotTranscludeExample', []) + * .directive('pane', function() { + * return { + * restrict: 'E', + * transclude: { + * 'title': '?paneTitle', + * 'body': 'paneBody', + * 'footer': '?paneFooter' + * }, + * template: '
' + + * '
Fallback Title
' + + * '
' + + * '' + + * '
' + * }; + * }) + * .controller('ExampleController', ['$scope', function($scope) { + * $scope.title = 'Lorem Ipsum'; + * $scope.link = 'https://google.com'; + * $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...'; + * }]); + *
+ * + * it('should have transcluded the title and the body', function() { + * var titleElement = element(by.model('title')); + * titleElement.clear(); + * titleElement.sendKeys('TITLE'); + * var textElement = element(by.model('text')); + * textElement.clear(); + * textElement.sendKeys('TEXT'); + * expect(element(by.css('.title')).getText()).toEqual('TITLE'); + * expect(element(by.binding('text')).getText()).toEqual('TEXT'); + * expect(element(by.css('.footer')).getText()).toEqual('Fallback Footer'); + * }); + * + *
*/ -var ngTranscludeDirective = ngDirective({ - restrict: 'EAC', - link: function($scope, $element, $attrs, controller, $transclude) { - if (!$transclude) { - throw minErr('ngTransclude')('orphan', - 'Illegal use of ngTransclude directive in the template! ' + - 'No parent directive that requires a transclusion found. ' + - 'Element: {0}', - startingTag($element)); - } - - $transclude(function(clone) { - $element.empty(); - $element.append(clone); - }); - } -}); +var ngTranscludeMinErr = minErr('ngTransclude'); +var ngTranscludeDirective = ['$compile', function($compile) { + return { + restrict: 'EAC', + compile: function ngTranscludeCompile(tElement) { + + // Remove and cache any original content to act as a fallback + var fallbackLinkFn = $compile(tElement.contents()); + tElement.empty(); + + return function ngTranscludePostLink($scope, $element, $attrs, controller, $transclude) { + + if (!$transclude) { + throw ngTranscludeMinErr('orphan', + 'Illegal use of ngTransclude directive in the template! ' + + 'No parent directive that requires a transclusion found. ' + + 'Element: {0}', + startingTag($element)); + } + + + // If the attribute is of the form: `ng-transclude="ng-transclude"` then treat it like the default + if ($attrs.ngTransclude === $attrs.$attr.ngTransclude) { + $attrs.ngTransclude = ''; + } + var slotName = $attrs.ngTransclude || $attrs.ngTranscludeSlot; + + // If the slot is required and no transclusion content is provided then this call will throw an error + $transclude(ngTranscludeCloneAttachFn, null, slotName); + + // If the slot is optional and no transclusion content is provided then use the fallback content + if (slotName && !$transclude.isSlotFilled(slotName)) { + useFallbackContent(); + } + + function ngTranscludeCloneAttachFn(clone, transcludedScope) { + if (clone.length && notWhitespace(clone)) { + $element.append(clone); + } else { + useFallbackContent(); + // There is nothing linked against the transcluded scope since no content was available, + // so it should be safe to clean up the generated scope. + transcludedScope.$destroy(); + } + } + + function useFallbackContent() { + // Since this is the fallback content rather than the transcluded content, + // we link against the scope of this directive rather than the transcluded scope + fallbackLinkFn($scope, function(clone) { + $element.append(clone); + }); + } + + function notWhitespace(nodes) { + for (var i = 0, ii = nodes.length; i < ii; i++) { + var node = nodes[i]; + if (node.nodeType !== NODE_TYPE_TEXT || node.nodeValue.trim()) { + return true; + } + } + } + }; + } + }; +}]; /** * @ngdoc directive @@ -25386,7 +35067,7 @@ var ngTranscludeDirective = ngDirective({ * @param {string} id Cache name of the template. * * @example - + -
-
    -
  • - Name: - [X] -
  • -
  • - [add] -
  • -
-
- Color (null not allowed): -
+ * $scope.forceUnknownOption = function() { + * $scope.selected = 'nonsense'; + * }; + * }]) + * .directive('unknownValueRequired', function() { + * return { + * priority: 1, // This directive must run after the required directive has added its validator + * require: ['ngModel', 'select'], + * link: function(scope, element, attrs, ctrls) { + * var ngModelCtrl = ctrls[0]; + * var selectCtrl = ctrls[1]; + * + * var originalRequiredValidator = ngModelCtrl.$validators.required; + * + * ngModelCtrl.$validators.required = function() { + * if (attrs.required && selectCtrl.$isUnknownOptionSelected()) { + * return false; + * } + * + * return originalRequiredValidator.apply(this, arguments); + * }; + * } + * }; + * }); + * + * + * it('should show the error message when the unknown option is selected', function() { - Color (null allowed): - - -
+ var error = element(by.className('error')); - Color grouped by shade: -
+ expect(error.getText()).toBe('Error: Please select a value'); + element(by.cssContainingText('option', 'Option 1')).click(); - Select bogus.
-
- Currently selected: {{ {selected_color:myColor} }} -
-
-
-
- - it('should check ng-options', function() { - expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red'); - element.all(by.model('myColor')).first().click(); - element.all(by.css('select[ng-model="myColor"] option')).first().click(); - expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black'); - element(by.css('.nullable select[ng-model="myColor"]')).click(); - element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click(); - expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null'); - }); - -
+ expect(error.isPresent()).toBe(false); + + element(by.tagName('button')).click(); + + expect(error.getText()).toBe('Error: Please select a value'); + }); + * + *
+ * + * */ +var SelectController = + ['$element', '$scope', /** @this */ function($element, $scope) { -var ngOptionsDirective = valueFn({ - restrict: 'A', - terminal: true -}); + var self = this, + optionsMap = new NgMap(); + + self.selectValueMap = {}; // Keys are the hashed values, values the original values + + // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors + self.ngModelCtrl = noopNgModelController; + self.multiple = false; + + // The "unknown" option is one that is prepended to the list if the viewValue + // does not match any of the options. When it is rendered the value of the unknown + // option is '? XXX ?' where XXX is the hashKey of the value that is not known. + // + // Support: IE 9 only + // We can't just jqLite(' + * + *
+ * + *
+ *
+ *
+ * singleSelect = {{data.singleSelect}} + * + *
+ *
+ *
+ * multipleSelect = {{data.multipleSelect}}
+ * + *
+ *
+ * + * angular.module('staticSelect', []) + * .controller('ExampleController', ['$scope', function($scope) { + * $scope.data = { + * singleSelect: null, + * multipleSelect: [], + * option1: 'option-1' + * }; + * + * $scope.forceUnknownOption = function() { + * $scope.data.singleSelect = 'nonsense'; + * }; + * }]); + * + *
+ * + * @example + * ### Using `ngRepeat` to generate `select` options + * + * + *
+ *
+ * + * + *
+ *
+ * model = {{data.model}}
+ *
+ *
+ * + * angular.module('ngrepeatSelect', []) + * .controller('ExampleController', ['$scope', function($scope) { + * $scope.data = { + * model: null, + * availableOptions: [ + * {id: '1', name: 'Option A'}, + * {id: '2', name: 'Option B'}, + * {id: '3', name: 'Option C'} + * ] + * }; + * }]); + * + *
+ * + * @example + * ### Using `ngValue` to bind the model to an array of objects + * + * + *
+ *
+ * + * + *
+ *
+ *
model = {{data.model | json}}

+ *
+ *
+ * + * angular.module('ngvalueSelect', []) + * .controller('ExampleController', ['$scope', function($scope) { + * $scope.data = { + * model: null, + * availableOptions: [ + {value: 'myString', name: 'string'}, + {value: 1, name: 'integer'}, + {value: true, name: 'boolean'}, + {value: null, name: 'null'}, + {value: {prop: 'value'}, name: 'object'}, + {value: ['a'], name: 'array'} + * ] + * }; + * }]); + * + *
+ * + * @example + * ### Using `select` with `ngOptions` and setting a default value + * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples. + * + * + * + *
+ *
+ * + * + *
+ *
+ * option = {{data.selectedOption}}
+ *
+ *
+ * + * angular.module('defaultValueSelect', []) + * .controller('ExampleController', ['$scope', function($scope) { + * $scope.data = { + * availableOptions: [ + * {id: '1', name: 'Option A'}, + * {id: '2', name: 'Option B'}, + * {id: '3', name: 'Option C'} + * ], + * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui + * }; + * }]); + * + *
+ * + * @example + * ### Binding `select` to a non-string value via `ngModel` parsing / formatting + * + * + * + * + * {{ model }} + * + * + * angular.module('nonStringSelect', []) + * .run(function($rootScope) { + * $rootScope.model = { id: 2 }; + * }) + * .directive('convertToNumber', function() { + * return { + * require: 'ngModel', + * link: function(scope, element, attrs, ngModel) { + * ngModel.$parsers.push(function(val) { + * return parseInt(val, 10); + * }); + * ngModel.$formatters.push(function(val) { + * return '' + val; + * }); + * } + * }; + * }); + * + * + * it('should initialize to model', function() { + * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two'); + * }); + * + * + * + */ +var selectDirective = function() { + + return { + restrict: 'E', + require: ['select', '?ngModel'], + controller: SelectController, + priority: 1, + link: { + pre: selectPreLink, + post: selectPostLink + } + }; - if (multiple) { - return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value))); - } else { - return viewValue === callExpression(compareValueFn, key, value); - } - }; - } + function selectPreLink(scope, element, attr, ctrls) { - function scheduleRendering() { - if (!renderScheduled) { - scope.$$postDigest(render); - renderScheduled = true; - } - } + var selectCtrl = ctrls[0]; + var ngModelCtrl = ctrls[1]; - /** - * A new labelMap is created with each render. - * This function is called for each existing option with added=false, - * and each new option with added=true. - * - Labels that are passed to this method twice, - * (once with added=true and once with added=false) will end up with a value of 0, and - * will cause no change to happen to the corresponding option. - * - Labels that are passed to this method only once with added=false will end up with a - * value of -1 and will eventually be passed to selectCtrl.removeOption() - * - Labels that are passed to this method only once with added=true will end up with a - * value of 1 and will eventually be passed to selectCtrl.addOption() - */ - function updateLabelMap(labelMap, label, added) { - labelMap[label] = labelMap[label] || 0; - labelMap[label] += (added ? 1 : -1); - } - - function render() { - renderScheduled = false; - - // Temporary location for the option groups before we render them - var optionGroups = {'':[]}, - optionGroupNames = [''], - optionGroupName, - optionGroup, - option, - existingParent, existingOptions, existingOption, - viewValue = ctrl.$viewValue, - values = valuesFn(scope) || [], - keys = keyName ? sortedKeys(values) : values, - key, - value, - groupLength, length, - groupIndex, index, - labelMap = {}, - selected, - isSelected = createIsSelectedFn(viewValue), - anySelected = false, - lastElement, - element, - label, - optionId; - - trackKeysCache = {}; - - // We now build up the list of options we need (we merge later) - for (index = 0; length = keys.length, index < length; index++) { - key = index; - if (keyName) { - key = keys[index]; - if (key.charAt(0) === '$') continue; - } - value = values[key]; + // if ngModel is not defined, we don't need to do anything but set the registerOption + // function to noop, so options don't get added internally + if (!ngModelCtrl) { + selectCtrl.registerOption = noop; + return; + } - optionGroupName = callExpression(groupByFn, key, value) || ''; - if (!(optionGroup = optionGroups[optionGroupName])) { - optionGroup = optionGroups[optionGroupName] = []; - optionGroupNames.push(optionGroupName); - } - selected = isSelected(key, value); - anySelected = anySelected || selected; + selectCtrl.ngModelCtrl = ngModelCtrl; - label = callExpression(displayFn, key, value); // what will be seen by the user + // When the selected item(s) changes we delegate getting the value of the select control + // to the `readValue` method, which can be changed if the select can have multiple + // selected values or if the options are being generated by `ngOptions` + element.on('change', function() { + selectCtrl.removeUnknownOption(); + scope.$apply(function() { + ngModelCtrl.$setViewValue(selectCtrl.readValue()); + }); + }); - // doing displayFn(scope, locals) || '' overwrites zero values - label = isDefined(label) ? label : ''; - optionId = trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index); - if (trackFn) { - trackKeysCache[optionId] = key; + // If the select allows multiple values then we need to modify how we read and write + // values from and to the control; also what it means for the value to be empty and + // we have to add an extra watch since ngModel doesn't work well with arrays - it + // doesn't trigger rendering if only an item in the array changes. + if (attr.multiple) { + selectCtrl.multiple = true; + + // Read value now needs to check each option to see if it is selected + selectCtrl.readValue = function readMultipleValue() { + var array = []; + forEach(element.find('option'), function(option) { + if (option.selected && !option.disabled) { + var val = option.value; + array.push(val in selectCtrl.selectValueMap ? selectCtrl.selectValueMap[val] : val); } + }); + return array; + }; - optionGroup.push({ - // either the index into array or key from object - id: optionId, - label: label, - selected: selected // determine if we should be selected - }); - } - if (!multiple) { - if (nullOption || viewValue === null) { - // insert null option if we have a placeholder, or the model is null - optionGroups[''].unshift({id:'', label:'', selected:!anySelected}); - } else if (!anySelected) { - // option could not be found, we have to insert the undefined item - optionGroups[''].unshift({id:'?', label:'', selected:true}); + // Write value now needs to set the selected property of each matching option + selectCtrl.writeValue = function writeMultipleValue(value) { + forEach(element.find('option'), function(option) { + var shouldBeSelected = !!value && (includes(value, option.value) || + includes(value, selectCtrl.selectValueMap[option.value])); + var currentlySelected = option.selected; + + // Support: IE 9-11 only, Edge 12-15+ + // In IE and Edge adding options to the selection via shift+click/UP/DOWN + // will de-select already selected options if "selected" on those options was set + // more than once (i.e. when the options were already selected) + // So we only modify the selected property if necessary. + // Note: this behavior cannot be replicated via unit tests because it only shows in the + // actual user interface. + if (shouldBeSelected !== currentlySelected) { + setOptionSelectedStatus(jqLite(option), shouldBeSelected); } - } - - // Now we need to update the list of DOM nodes to match the optionGroups we computed above - for (groupIndex = 0, groupLength = optionGroupNames.length; - groupIndex < groupLength; - groupIndex++) { - // current option group name or '' if no group - optionGroupName = optionGroupNames[groupIndex]; - - // list of options for that group. (first item has the parent) - optionGroup = optionGroups[optionGroupName]; - - if (optionGroupsCache.length <= groupIndex) { - // we need to grow the optionGroups - existingParent = { - element: optGroupTemplate.clone().attr('label', optionGroupName), - label: optionGroup.label - }; - existingOptions = [existingParent]; - optionGroupsCache.push(existingOptions); - selectElement.append(existingParent.element); - } else { - existingOptions = optionGroupsCache[groupIndex]; - existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element - // update the OPTGROUP label if not the same. - if (existingParent.label != optionGroupName) { - existingParent.element.attr('label', existingParent.label = optionGroupName); - } - } + }); + }; - lastElement = null; // start at the beginning - for (index = 0, length = optionGroup.length; index < length; index++) { - option = optionGroup[index]; - if ((existingOption = existingOptions[index + 1])) { - // reuse elements - lastElement = existingOption.element; - if (existingOption.label !== option.label) { - updateLabelMap(labelMap, existingOption.label, false); - updateLabelMap(labelMap, option.label, true); - lastElement.text(existingOption.label = option.label); - lastElement.prop('label', existingOption.label); - } - if (existingOption.id !== option.id) { - lastElement.val(existingOption.id = option.id); - } - // lastElement.prop('selected') provided by jQuery has side-effects - if (lastElement[0].selected !== option.selected) { - lastElement.prop('selected', (existingOption.selected = option.selected)); - if (msie) { - // See #7692 - // The selected item wouldn't visually update on IE without this. - // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well - lastElement.prop('selected', existingOption.selected); - } - } - } else { - // grow elements + // we have to do it on each watch since ngModel watches reference, but + // we need to work of an array, so we need to see if anything was inserted/removed + var lastView, lastViewRef = NaN; + scope.$watch(function selectMultipleWatch() { + if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) { + lastView = shallowCopy(ngModelCtrl.$viewValue); + ngModelCtrl.$render(); + } + lastViewRef = ngModelCtrl.$viewValue; + }); - // if it's a null option - if (option.id === '' && nullOption) { - // put back the pre-compiled element - element = nullOption; - } else { - // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but - // in this version of jQuery on some browser the .text() returns a string - // rather then the element. - (element = optionTemplate.clone()) - .val(option.id) - .prop('selected', option.selected) - .attr('selected', option.selected) - .prop('label', option.label) - .text(option.label); - } + // If we are a multiple select then value is now a collection + // so the meaning of $isEmpty changes + ngModelCtrl.$isEmpty = function(value) { + return !value || value.length === 0; + }; - existingOptions.push(existingOption = { - element: element, - label: option.label, - id: option.id, - selected: option.selected - }); - updateLabelMap(labelMap, option.label, true); - if (lastElement) { - lastElement.after(element); - } else { - existingParent.element.append(element); - } - lastElement = element; - } - } - // remove any excessive OPTIONs in a group - index++; // increment since the existingOptions[0] is parent element not OPTION - while (existingOptions.length > index) { - option = existingOptions.pop(); - updateLabelMap(labelMap, option.label, false); - option.element.remove(); - } - } - // remove any excessive OPTGROUPs from select - while (optionGroupsCache.length > groupIndex) { - // remove all the labels in the option group - optionGroup = optionGroupsCache.pop(); - for (index = 1; index < optionGroup.length; ++index) { - updateLabelMap(labelMap, optionGroup[index].label, false); - } - optionGroup[0].element.remove(); - } - forEach(labelMap, function(count, label) { - if (count > 0) { - selectCtrl.addOption(label); - } else if (count < 0) { - selectCtrl.removeOption(label); - } - }); - } } } - }; -}]; -var optionDirective = ['$interpolate', function($interpolate) { - var nullSelectCtrl = { - addOption: noop, - removeOption: noop - }; + function selectPostLink(scope, element, attrs, ctrls) { + // if ngModel is not defined, we don't need to do anything + var ngModelCtrl = ctrls[1]; + if (!ngModelCtrl) return; + + var selectCtrl = ctrls[0]; + + // We delegate rendering to the `writeValue` method, which can be changed + // if the select can have multiple selected values or if the options are being + // generated by `ngOptions`. + // This must be done in the postLink fn to prevent $render to be called before + // all nodes have been linked correctly. + ngModelCtrl.$render = function() { + selectCtrl.writeValue(ngModelCtrl.$viewValue); + }; + } +}; + +// The option directive is purely designed to communicate the existence (or lack of) +// of dynamically created (and destroyed) option elements to their containing select +// directive via its controller. +var optionDirective = ['$interpolate', function($interpolate) { return { restrict: 'E', priority: 100, compile: function(element, attr) { - if (isUndefined(attr.value)) { - var interpolateFn = $interpolate(element.text(), true); - if (!interpolateFn) { + var interpolateValueFn, interpolateTextFn; + + if (isDefined(attr.ngValue)) { + // Will be handled by registerOption + } else if (isDefined(attr.value)) { + // If the value attribute is defined, check if it contains an interpolation + interpolateValueFn = $interpolate(attr.value, true); + } else { + // If the value attribute is not defined then we fall back to the + // text content of the option element, which may be interpolated + interpolateTextFn = $interpolate(element.text(), true); + if (!interpolateTextFn) { attr.$set('value', element.text()); } } return function(scope, element, attr) { + // This is an optimization over using ^^ since we don't want to have to search + // all the way to the root of the DOM for every single option element var selectCtrlName = '$selectController', parent = element.parent(), selectCtrl = parent.data(selectCtrlName) || parent.parent().data(selectCtrlName); // in case we are in optgroup - if (!selectCtrl || !selectCtrl.databound) { - selectCtrl = nullSelectCtrl; - } - - if (interpolateFn) { - scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) { - attr.$set('value', newVal); - if (oldVal !== newVal) { - selectCtrl.removeOption(oldVal); - } - selectCtrl.addOption(newVal, element); - }); - } else { - selectCtrl.addOption(attr.value, element); + if (selectCtrl) { + selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn); } - - element.on('$destroy', function() { - selectCtrl.removeOption(attr.value); - }); }; } }; }]; -var styleDirective = valueFn({ - restrict: 'E', - terminal: false -}); +/** + * @ngdoc directive + * @name ngRequired + * @restrict A + * + * @param {expression} ngRequired AngularJS expression. If it evaluates to `true`, it sets the + * `required` attribute to the element and adds the `required` + * {@link ngModel.NgModelController#$validators `validator`}. + * + * @description + * + * ngRequired adds the required {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}. + * It is most often used for {@link input `input`} and {@link select `select`} controls, but can also be + * applied to custom controls. + * + * The directive sets the `required` attribute on the element if the AngularJS expression inside + * `ngRequired` evaluates to true. A special directive for setting `required` is necessary because we + * cannot use interpolation inside `required`. See the {@link guide/interpolation interpolation guide} + * for more info. + * + * The validator will set the `required` error key to true if the `required` attribute is set and + * calling {@link ngModel.NgModelController#$isEmpty `NgModelController.$isEmpty`} with the + * {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} returns `true`. For example, the + * `$isEmpty()` implementation for `input[text]` checks the length of the `$viewValue`. When developing + * custom controls, `$isEmpty()` can be overwritten to account for a $viewValue that is not string-based. + * + * @example + * + * + * + *
+ *
+ * + * + *
+ * + *
+ *
+ * required error set? = {{form.input.$error.required}}
+ * model = {{model}} + *
+ *
+ *
+ * + var required = element(by.binding('form.input.$error.required')); + var model = element(by.binding('model')); + var input = element(by.id('input')); -var requiredDirective = function() { + it('should set the required error', function() { + expect(required.getText()).toContain('true'); + + input.sendKeys('123'); + expect(required.getText()).not.toContain('true'); + expect(model.getText()).toContain('123'); + }); + * + *
+ */ +var requiredDirective = ['$parse', function($parse) { return { restrict: 'A', require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; - attr.required = true; // force truthy in case we are on non input element + // For boolean attributes like required, presence means true + var value = attr.hasOwnProperty('required') || $parse(attr.ngRequired)(scope); + + if (!attr.ngRequired) { + // force truthy in case we are on non input element + // (input elements do this automatically for boolean attributes like required) + attr.required = true; + } ctrl.$validators.required = function(modelValue, viewValue) { - return !attr.required || !ctrl.$isEmpty(viewValue); + return !value || !ctrl.$isEmpty(viewValue); }; - attr.$observe('required', function() { - ctrl.$validate(); + attr.$observe('required', function(newVal) { + + if (value !== newVal) { + value = newVal; + ctrl.$validate(); + } }); } }; -}; +}]; + +/** + * @ngdoc directive + * @name ngPattern + * @restrict A + * + * @param {expression|RegExp} ngPattern AngularJS expression that must evaluate to a `RegExp` or a `String` + * parsable into a `RegExp`, or a `RegExp` literal. See above for + * more details. + * + * @description + * + * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}. + * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls. + * + * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} + * does not match a RegExp which is obtained from the `ngPattern` attribute value: + * - the value is an AngularJS expression: + * - 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$')`. + * - If the value is a RegExp literal, e.g. `ngPattern="/^\d+$/"`, it is used directly. + * + *
+ * **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. + *
+ * + *
+ * **Note:** This directive is also added when the plain `pattern` attribute is used, with two + * differences: + *
    + *
  1. + * `ngPattern` does not set the `pattern` attribute and therefore HTML5 constraint validation is + * not available. + *
  2. + *
  3. + * The `ngPattern` attribute must be an expression, while the `pattern` value must be + * interpolated. + *
  4. + *
+ *
+ * + * @example + * + * + * + *
+ *
+ * + * + *
+ * + *
+ *
+ * input valid? = {{form.input.$valid}}
+ * model = {{model}} + *
+ *
+ *
+ * + var model = element(by.binding('model')); + var input = element(by.id('input')); + it('should validate the input with the default pattern', function() { + input.sendKeys('aaa'); + expect(model.getText()).not.toContain('aaa'); -var patternDirective = function() { + input.clear().then(function() { + input.sendKeys('123'); + expect(model.getText()).toContain('123'); + }); + }); + * + *
+ */ +var patternDirective = ['$parse', function($parse) { return { restrict: 'A', require: '?ngModel', - link: function(scope, elm, attr, ctrl) { - if (!ctrl) return; - - var regexp, patternExp = attr.ngPattern || attr.pattern; - attr.$observe('pattern', function(regex) { - if (isString(regex) && regex.length > 0) { - regex = new RegExp('^' + regex + '$'); + compile: function(tElm, tAttr) { + var patternExp; + var parseFn; + + if (tAttr.ngPattern) { + patternExp = tAttr.ngPattern; + + // ngPattern might be a scope expression, or an inlined regex, which is not parsable. + // We get value of the attribute here, so we can compare the old and the new value + // in the observer to avoid unnecessary validations + if (tAttr.ngPattern.charAt(0) === '/' && REGEX_STRING_REGEXP.test(tAttr.ngPattern)) { + parseFn = function() { return tAttr.ngPattern; }; + } else { + parseFn = $parse(tAttr.ngPattern); } + } + + return function(scope, elm, attr, ctrl) { + if (!ctrl) return; - if (regex && !regex.test) { - throw minErr('ngPattern')('noregexp', - 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp, - regex, startingTag(elm)); + var attrVal = attr.pattern; + + if (attr.ngPattern) { + attrVal = parseFn(scope); + } else { + patternExp = attr.pattern; } - regexp = regex || undefined; - ctrl.$validate(); - }); + var regexp = parsePatternAttr(attrVal, patternExp, elm); + + attr.$observe('pattern', function(newVal) { + var oldRegexp = regexp; + + regexp = parsePatternAttr(newVal, patternExp, elm); - ctrl.$validators.pattern = function(value) { - return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value); + if ((oldRegexp && oldRegexp.toString()) !== (regexp && regexp.toString())) { + ctrl.$validate(); + } + }); + + ctrl.$validators.pattern = function(modelValue, viewValue) { + // HTML5 pattern constraint validates the input value, so we validate the viewValue + return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue); + }; }; } + }; -}; +}]; + +/** + * @ngdoc directive + * @name ngMaxlength + * @restrict A + * + * @param {expression} ngMaxlength AngularJS expression that must evaluate to a `Number` or `String` + * parsable into a `Number`. Used as value for the `maxlength` + * {@link ngModel.NgModelController#$validators validator}. + * + * @description + * + * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}. + * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls. + * + * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} + * is longer than the integer obtained by evaluating the AngularJS expression given in the + * `ngMaxlength` attribute value. + * + *
+ * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two + * differences: + *
    + *
  1. + * `ngMaxlength` does not set the `maxlength` attribute and therefore HTML5 constraint + * validation is not available. + *
  2. + *
  3. + * The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be + * interpolated. + *
  4. + *
+ *
+ * + * @example + * + * + * + *
+ *
+ * + * + *
+ * + *
+ *
+ * input valid? = {{form.input.$valid}}
+ * model = {{model}} + *
+ *
+ *
+ * + var model = element(by.binding('model')); + var input = element(by.id('input')); + it('should validate the input with the default maxlength', function() { + input.sendKeys('abcdef'); + expect(model.getText()).not.toContain('abcdef'); -var maxlengthDirective = function() { + input.clear().then(function() { + input.sendKeys('abcde'); + expect(model.getText()).toContain('abcde'); + }); + }); + * + *
+ */ +var maxlengthDirective = ['$parse', function($parse) { return { restrict: 'A', require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; - var maxlength = -1; + var maxlength = attr.maxlength || $parse(attr.ngMaxlength)(scope); + var maxlengthParsed = parseLength(maxlength); + attr.$observe('maxlength', function(value) { - var intVal = int(value); - maxlength = isNaN(intVal) ? -1 : intVal; - ctrl.$validate(); + if (maxlength !== value) { + maxlengthParsed = parseLength(value); + maxlength = value; + ctrl.$validate(); + } }); ctrl.$validators.maxlength = function(modelValue, viewValue) { - return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength); + return (maxlengthParsed < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlengthParsed); }; } }; -}; +}]; + +/** + * @ngdoc directive + * @name ngMinlength + * @restrict A + * + * @param {expression} ngMinlength AngularJS expression that must evaluate to a `Number` or `String` + * parsable into a `Number`. Used as value for the `minlength` + * {@link ngModel.NgModelController#$validators validator}. + * + * @description + * + * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}. + * It is most often used for text-based {@link input `input`} controls, but can also be applied to custom text-based controls. + * + * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`} + * is shorter than the integer obtained by evaluating the AngularJS expression given in the + * `ngMinlength` attribute value. + * + *
+ * **Note:** This directive is also added when the plain `minlength` attribute is used, with two + * differences: + *
    + *
  1. + * `ngMinlength` does not set the `minlength` attribute and therefore HTML5 constraint + * validation is not available. + *
  2. + *
  3. + * The `ngMinlength` value must be an expression, while the `minlength` value must be + * interpolated. + *
  4. + *
+ *
+ * + * @example + * + * + * + *
+ *
+ * + * + *
+ * + *
+ *
+ * input valid? = {{form.input.$valid}}
+ * model = {{model}} + *
+ *
+ *
+ * + var model = element(by.binding('model')); + var input = element(by.id('input')); + + it('should validate the input with the default minlength', function() { + input.sendKeys('ab'); + expect(model.getText()).not.toContain('ab'); -var minlengthDirective = function() { + input.sendKeys('abc'); + expect(model.getText()).toContain('abc'); + }); + * + *
+ */ +var minlengthDirective = ['$parse', function($parse) { return { restrict: 'A', require: '?ngModel', link: function(scope, elm, attr, ctrl) { if (!ctrl) return; - var minlength = 0; + var minlength = attr.minlength || $parse(attr.ngMinlength)(scope); + var minlengthParsed = parseLength(minlength) || -1; + attr.$observe('minlength', function(value) { - minlength = int(value) || 0; - ctrl.$validate(); + if (minlength !== value) { + minlengthParsed = parseLength(value) || -1; + minlength = value; + ctrl.$validate(); + } + }); ctrl.$validators.minlength = function(modelValue, viewValue) { - return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength; + return ctrl.$isEmpty(viewValue) || viewValue.length >= minlengthParsed; }; } }; -}; +}]; - if (window.angular.bootstrap) { - //AngularJS is already loaded, so we can return here... - console.log('WARNING: Tried to load angular more than once.'); - return; + +function parsePatternAttr(regex, patternExp, elm) { + if (!regex) return undefined; + + if (isString(regex)) { + regex = new RegExp('^' + regex + '$'); + } + + if (!regex.test) { + throw minErr('ngPattern')('noregexp', + 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp, + regex, startingTag(elm)); + } + + return regex; +} + +function parseLength(val) { + var intVal = toInt(val); + return isNumberNaN(intVal) ? -1 : intVal; +} + +if (window.angular.bootstrap) { + // AngularJS is already loaded, so we can return here... + if (window.console) { + console.log('WARNING: Tried to load AngularJS more than once.'); + } + return; +} + +// try to bind to jquery now so that one can write jqLite(fn) +// but we will rebind on bootstrap again. +bindJQuery(); + +publishExternalAPI(angular); + +angular.module("ngLocale", [], ["$provide", function($provide) { +var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; +function getDecimals(n) { + n = n + ''; + var i = n.indexOf('.'); + return (i == -1) ? 0 : n.length - i - 1; +} + +function getVF(n, opt_precision) { + var v = opt_precision; + + if (undefined === v) { + v = Math.min(getDecimals(n), 3); } - //try to bind to jquery now so that one can write jqLite(document).ready() - //but we will rebind on bootstrap again. - bindJQuery(); + var base = Math.pow(10, v); + var f = ((n * base) | 0) % base; + return {v: v, f: f}; +} - publishExternalAPI(angular); +$provide.value("$locale", { + "DATETIME_FORMATS": { + "AMPMS": [ + "AM", + "PM" + ], + "DAY": [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ], + "ERANAMES": [ + "Before Christ", + "Anno Domini" + ], + "ERAS": [ + "BC", + "AD" + ], + "FIRSTDAYOFWEEK": 6, + "MONTH": [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ], + "SHORTDAY": [ + "Sun", + "Mon", + "Tue", + "Wed", + "Thu", + "Fri", + "Sat" + ], + "SHORTMONTH": [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + ], + "STANDALONEMONTH": [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ], + "WEEKENDRANGE": [ + 5, + 6 + ], + "fullDate": "EEEE, MMMM d, y", + "longDate": "MMMM d, y", + "medium": "MMM d, y h:mm:ss a", + "mediumDate": "MMM d, y", + "mediumTime": "h:mm:ss a", + "short": "M/d/yy h:mm a", + "shortDate": "M/d/yy", + "shortTime": "h:mm a" + }, + "NUMBER_FORMATS": { + "CURRENCY_SYM": "$", + "DECIMAL_SEP": ".", + "GROUP_SEP": ",", + "PATTERNS": [ + { + "gSize": 3, + "lgSize": 3, + "maxFrac": 3, + "minFrac": 0, + "minInt": 1, + "negPre": "-", + "negSuf": "", + "posPre": "", + "posSuf": "" + }, + { + "gSize": 3, + "lgSize": 3, + "maxFrac": 2, + "minFrac": 2, + "minInt": 1, + "negPre": "-\u00a4", + "negSuf": "", + "posPre": "\u00a4", + "posSuf": "" + } + ] + }, + "id": "en-us", + "localeID": "en_US", + "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} +}); +}]); - jqLite(document).ready(function() { - angularInit(document, bootstrap); + jqLite(function() { + angularInit(window.document, bootstrap); }); -})(window, document); +})(window); -!window.angular.$$csp() && window.angular.element(document).find('head').prepend(''); \ No newline at end of file +!window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend(window.angular.element(''); +(function(z){'use strict';function ve(a){if(D(a))w(a.objectMaxDepth)&&(Xb.objectMaxDepth=Yb(a.objectMaxDepth)?a.objectMaxDepth:NaN),w(a.urlErrorParamsEnabled)&&Ga(a.urlErrorParamsEnabled)&&(Xb.urlErrorParamsEnabled=a.urlErrorParamsEnabled);else return Xb}function Yb(a){return X(a)&&0c)return"...";var d=b.$$hashKey,f;if(H(a)){f=0;for(var g=a.length;f
").append(a).html();try{return a[0].nodeType===Pa?K(b):b.match(/^(<[^>]+>)/)[1].replace(/^<([\w-]+)/,function(a,b){return"<"+K(b)})}catch(d){return K(b)}}function Vc(a){try{return decodeURIComponent(a)}catch(b){}}function hc(a){var b={};r((a||"").split("&"), +function(a){var c,e,f;a&&(e=a=a.replace(/\+/g,"%20"),c=a.indexOf("="),-1!==c&&(e=a.substring(0,c),f=a.substring(c+1)),e=Vc(e),w(e)&&(f=w(f)?Vc(f):!0,ta.call(b,e)?H(b[e])?b[e].push(f):b[e]=[b[e],f]:b[e]=f))});return b}function Ce(a){var b=[];r(a,function(a,c){H(a)?r(a,function(a){b.push(ba(c,!0)+(!0===a?"":"="+ba(a,!0)))}):b.push(ba(c,!0)+(!0===a?"":"="+ba(a,!0)))});return b.length?b.join("&"):""}function ic(a){return ba(a,!0).replace(/%26/gi,"&").replace(/%3D/gi,"=").replace(/%2B/gi,"+")}function ba(a, +b){return encodeURIComponent(a).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%3B/gi,";").replace(/%20/g,b?"%20":"+")}function De(a,b){var d,c,e=Qa.length;for(c=0;c protocol indicates an extension, document.location.href does not match."))}function Wc(a,b,d){D(d)||(d={});d=S({strictDi:!1},d);var c=function(){a=x(a);if(a.injector()){var c=a[0]===z.document?"document":Aa(a);throw oa("btstrpd",c.replace(//,">"));}b=b||[];b.unshift(["$provide",function(b){b.value("$rootElement",a)}]);d.debugInfoEnabled&&b.push(["$compileProvider", +function(a){a.debugInfoEnabled(!0)}]);b.unshift("ng");c=fb(b,d.strictDi);c.invoke(["$rootScope","$rootElement","$compile","$injector",function(a,b,c,d){a.$apply(function(){b.data("$injector",d);c(b)(a)})}]);return c},e=/^NG_ENABLE_DEBUG_INFO!/,f=/^NG_DEFER_BOOTSTRAP!/;z&&e.test(z.name)&&(d.debugInfoEnabled=!0,z.name=z.name.replace(e,""));if(z&&!f.test(z.name))return c();z.name=z.name.replace(f,"");ca.resumeBootstrap=function(a){r(a,function(a){b.push(a)});return c()};B(ca.resumeDeferredBootstrap)&& +ca.resumeDeferredBootstrap()}function Ge(){z.name="NG_ENABLE_DEBUG_INFO!"+z.name;z.location.reload()}function He(a){a=ca.element(a).injector();if(!a)throw oa("test");return a.get("$$testability")}function Xc(a,b){b=b||"_";return a.replace(Ie,function(a,c){return(c?b:"")+a.toLowerCase()})}function Je(){var a;if(!Yc){var b=rb();(sb=A(b)?z.jQuery:b?z[b]:void 0)&&sb.fn.on?(x=sb,S(sb.fn,{scope:Wa.scope,isolateScope:Wa.isolateScope,controller:Wa.controller,injector:Wa.injector,inheritedData:Wa.inheritedData})): +x=U;a=x.cleanData;x.cleanData=function(b){for(var c,e=0,f;null!=(f=b[e]);e++)(c=(x._data(f)||{}).events)&&c.$destroy&&x(f).triggerHandler("$destroy");a(b)};ca.element=x;Yc=!0}}function Ke(){U.legacyXHTMLReplacement=!0}function gb(a,b,d){if(!a)throw oa("areq",b||"?",d||"required");return a}function tb(a,b,d){d&&H(a)&&(a=a[a.length-1]);gb(B(a),b,"not a function, got "+(a&&"object"===typeof a?a.constructor.name||"Object":typeof a));return a}function Ja(a,b){if("hasOwnProperty"===a)throw oa("badname", +b);}function Le(a,b,d){if(!b)return a;b=b.split(".");for(var c,e=a,f=b.length,g=0;g"):a;if(10>wa)for(c=hb[c]||hb._default,d.innerHTML=c[1]+e+c[2],k=c[0];k--;)d=d.firstChild;else{c=qa[c]||[];for(k=c.length;-1<--k;)d.appendChild(z.document.createElement(c[k])),d=d.firstChild;d.innerHTML=e}g=db(g,d.childNodes);d=f.firstChild;d.textContent=""}else g.push(b.createTextNode(a)); +f.textContent="";f.innerHTML="";r(g,function(a){f.appendChild(a)});return f}function U(a){if(a instanceof U)return a;var b;C(a)&&(a=V(a),b=!0);if(!(this instanceof U)){if(b&&"<"!==a.charAt(0))throw oc("nosel");return new U(a)}if(b){b=z.document;var d;a=(d=tg.exec(a))?[b.createElement(d[1])]:(d=gd(a,b))?d.childNodes:[];pc(this,a)}else B(a)?hd(a):pc(this,a)}function qc(a){return a.cloneNode(!0)}function zb(a,b){!b&&mc(a)&&x.cleanData([a]);a.querySelectorAll&&x.cleanData(a.querySelectorAll("*"))}function id(a){for(var b in a)return!1; +return!0}function jd(a){var b=a.ng339,d=b&&Ka[b],c=d&&d.events,d=d&&d.data;d&&!id(d)||c&&!id(c)||(delete Ka[b],a.ng339=void 0)}function kd(a,b,d,c){if(w(c))throw oc("offargs");var e=(c=Ab(a))&&c.events,f=c&&c.handle;if(f){if(b){var g=function(b){var c=e[b];w(d)&&cb(c||[],d);w(d)&&c&&0l&&this.remove(n.key);return b}},get:function(a){if(l";b=Fa.firstChild.attributes;var d=b[0];b.removeNamedItem(d.name);d.value=c;a.attributes.setNamedItem(d)}function sa(a,b){try{a.addClass(b)}catch(c){}}function da(a,b,c,d,e){a instanceof x||(a=x(a));var f=Xa(a,b,a,c,d,e);da.$$addScopeClass(a);var g=null;return function(b,c,d){if(!a)throw $("multilink");gb(b,"scope");e&&e.needsNewScope&&(b=b.$parent.$new());d=d||{};var h=d.parentBoundTranscludeFn,k=d.transcludeControllers;d=d.futureParentElement; +h&&h.$$boundTransclude&&(h=h.$$boundTransclude);g||(g=(d=d&&d[0])?"foreignobject"!==ua(d)&&la.call(d).match(/SVG/)?"svg":"html":"html");d="html"!==g?x(ja(g,x("
").append(a).html())):c?Wa.clone.call(a):a;if(k)for(var l in k)d.data("$"+l+"Controller",k[l].instance);da.$$addScopeInfo(d,b);c&&c(d,b);f&&f(b,d,d,h);c||(a=f=null);return d}}function Xa(a,b,c,d,e,f){function g(a,c,d,e){var f,k,l,m,p,I,t;if(n)for(t=Array(c.length),m=0;mu.priority)break;if(O=u.scope)u.templateUrl||(D(O)?(ba("new/isolated scope",s||t,u,y),s=u):ba("new/isolated scope",s,u,y)),t=t||u;Q=u.name;if(!ma&&(u.replace&&(u.templateUrl||u.template)||u.transclude&& +!u.$$tlb)){for(O=sa+1;ma=a[O++];)if(ma.transclude&&!ma.$$tlb||ma.replace&&(ma.templateUrl||ma.template)){Jb=!0;break}ma=!0}!u.templateUrl&&u.controller&&(J=J||T(),ba("'"+Q+"' controller",J[Q],u,y),J[Q]=u);if(O=u.transclude)if(G=!0,u.$$tlb||(ba("transclusion",L,u,y),L=u),"element"===O)N=!0,n=u.priority,M=y,y=d.$$element=x(da.$$createComment(Q,d[Q])),b=y[0],oa(f,Ha.call(M,0),b),R=Z(Jb,M,e,n,g&&g.name,{nonTlbTranscludeDirective:L});else{var ka=T();if(D(O)){M=z.document.createDocumentFragment();var Xa= +T(),F=T();r(O,function(a,b){var c="?"===a.charAt(0);a=c?a.substring(1):a;Xa[a]=b;ka[b]=null;F[b]=c});r(y.contents(),function(a){var b=Xa[xa(ua(a))];b?(F[b]=!0,ka[b]=ka[b]||z.document.createDocumentFragment(),ka[b].appendChild(a)):M.appendChild(a)});r(F,function(a,b){if(!a)throw $("reqslot",b);});for(var K in ka)ka[K]&&(R=x(ka[K].childNodes),ka[K]=Z(Jb,R,e));M=x(M.childNodes)}else M=x(qc(b)).contents();y.empty();R=Z(Jb,M,e,void 0,void 0,{needsNewScope:u.$$isolateScope||u.$$newScope});R.$$slots=ka}if(u.template)if(P= +!0,ba("template",v,u,y),v=u,O=B(u.template)?u.template(y,d):u.template,O=Na(O),u.replace){g=u;M=nc.test(O)?td(ja(u.templateNamespace,V(O))):[];b=M[0];if(1!==M.length||1!==b.nodeType)throw $("tplrt",Q,"");oa(f,y,b);C={$attr:{}};O=tc(b,[],C);var Ig=a.splice(sa+1,a.length-(sa+1));(s||t)&&fa(O,s,t);a=a.concat(O).concat(Ig);ga(d,C);C=a.length}else y.html(O);if(u.templateUrl)P=!0,ba("template",v,u,y),v=u,u.replace&&(g=u),p=ha(a.splice(sa,a.length-sa),y,d,f,G&&R,h,k,{controllerDirectives:J,newScopeDirective:t!== +u&&t,newIsolateScopeDirective:s,templateDirective:v,nonTlbTranscludeDirective:L}),C=a.length;else if(u.compile)try{q=u.compile(y,d,R);var Y=u.$$originalDirective||u;B(q)?m(null,Va(Y,q),E,jb):q&&m(Va(Y,q.pre),Va(Y,q.post),E,jb)}catch(ca){c(ca,Aa(y))}u.terminal&&(p.terminal=!0,n=Math.max(n,u.priority))}p.scope=t&&!0===t.scope;p.transcludeOnThisElement=G;p.templateOnThisElement=P;p.transclude=R;l.hasElementTranscludeDirective=N;return p}function X(a,b,c,d){var e;if(C(b)){var f=b.match(l);b=b.substring(f[0].length); +var g=f[1]||f[3],f="?"===f[2];"^^"===g?c=c.parent():e=(e=d&&d[b])&&e.instance;if(!e){var h="$"+b+"Controller";e="^^"===g&&c[0]&&9===c[0].nodeType?null:g?c.inheritedData(h):c.data(h)}if(!e&&!f)throw $("ctreq",b,a);}else if(H(b))for(e=[],g=0,f=b.length;gc.priority)&&-1!==c.restrict.indexOf(e)){k&&(c=bc(c,{$$start:k,$$end:l}));if(!c.$$bindings){var I=m=c,t=c.name,u={isolateScope:null,bindToController:null}; +D(I.scope)&&(!0===I.bindToController?(u.bindToController=d(I.scope,t,!0),u.isolateScope={}):u.isolateScope=d(I.scope,t,!1));D(I.bindToController)&&(u.bindToController=d(I.bindToController,t,!0));if(u.bindToController&&!I.controller)throw $("noctrl",t);m=m.$$bindings=u;D(m.isolateScope)&&(c.$$isolateBindings=m.isolateScope)}b.push(c);m=c}}return m}function ca(b){if(f.hasOwnProperty(b))for(var c=a.get(b+"Directive"),d=0,e=c.length;d"+b+"";return c.childNodes[0].childNodes;default:return b}}function qa(a,b){if("srcdoc"=== +b)return u.HTML;if("src"===b||"ngSrc"===b)return-1===["img","video","audio","source","track"].indexOf(a)?u.RESOURCE_URL:u.MEDIA_URL;if("xlinkHref"===b)return"image"===a?u.MEDIA_URL:"a"===a?u.URL:u.RESOURCE_URL;if("form"===a&&"action"===b||"base"===a&&"href"===b||"link"===a&&"href"===b)return u.RESOURCE_URL;if("a"===a&&("href"===b||"ngHref"===b))return u.URL}function ya(a,b){var c=b.toLowerCase();return v[a+"|"+c]||v["*|"+c]}function za(a){return ma(u.valueOf(a),"ng-prop-srcset")}function Ea(a,b,c, +d){if(m.test(d))throw $("nodomevents");a=ua(a);var e=ya(a,d),f=Ta;"srcset"!==d||"img"!==a&&"source"!==a?e&&(f=u.getTrusted.bind(u,e)):f=za;b.push({priority:100,compile:function(a,b){var e=p(b[c]),g=p(b[c],function(a){return u.valueOf(a)});return{pre:function(a,b){function c(){var g=e(a);b[0][d]=f(g)}c();a.$watch(g,c)}}}})}function Ia(a,c,d,e,f){var g=ua(a),k=qa(g,e),l=h[e]||f,p=b(d,!f,k,l);if(p){if("multiple"===e&&"select"===g)throw $("selmulti",Aa(a));if(m.test(e))throw $("nodomevents");c.push({priority:100, +compile:function(){return{pre:function(a,c,f){c=f.$$observers||(f.$$observers=T());var g=f[e];g!==d&&(p=g&&b(g,!0,k,l),d=g);p&&(f[e]=p(a),(c[e]||(c[e]=[])).$$inter=!0,(f.$$observers&&f.$$observers[e].$$scope||a).$watch(p,function(a,b){"class"===e&&a!==b?f.$updateClass(a,b):f.$set(e,a)}))}}}})}}function oa(a,b,c){var d=b[0],e=b.length,f=d.parentNode,g,h;if(a)for(g=0,h=a.length;g=b)return a;for(;b--;){var d=a[b];(8===d.nodeType||d.nodeType===Pa&&""===d.nodeValue.trim())&&Kg.call(a,b,1)}return a} +function Gg(a,b){if(b&&C(b))return b;if(C(a)){var d=wd.exec(a);if(d)return d[3]}}function Kf(){var a={};this.has=function(b){return a.hasOwnProperty(b)};this.register=function(b,d){Ja(b,"controller");D(b)?S(a,b):a[b]=d};this.$get=["$injector",function(b){function d(a,b,d,g){if(!a||!D(a.$scope))throw F("$controller")("noscp",g,b);a.$scope[b]=d}return function(c,e,f,g){var k,h,l;f=!0===f;g&&C(g)&&(l=g);if(C(c)){g=c.match(wd);if(!g)throw xd("ctrlfmt",c);h=g[1];l=l||g[3];c=a.hasOwnProperty(h)?a[h]:Le(e.$scope, +h,!0);if(!c)throw xd("ctrlreg",h);tb(c,h,!0)}if(f)return f=(H(c)?c[c.length-1]:c).prototype,k=Object.create(f||null),l&&d(e,l,k,h||c.name),S(function(){var a=b.invoke(c,k,e,h);a!==k&&(D(a)||B(a))&&(k=a,l&&d(e,l,k,h||c.name));return k},{instance:k,identifier:l});k=b.instantiate(c,e,h);l&&d(e,l,k,h||c.name);return k}}]}function Lf(){this.$get=["$window",function(a){return x(a.document)}]}function Mf(){this.$get=["$document","$rootScope",function(a,b){function d(){e=c.hidden}var c=a[0],e=c&&c.hidden; +a.on("visibilitychange",d);b.$on("$destroy",function(){a.off("visibilitychange",d)});return function(){return e}}]}function Nf(){this.$get=["$log",function(a){return function(b,d){a.error.apply(a,arguments)}}]}function vc(a){return D(a)?ha(a)?a.toISOString():eb(a):a}function Tf(){this.$get=function(){return function(a){if(!a)return"";var b=[];Qc(a,function(a,c){null===a||A(a)||B(a)||(H(a)?r(a,function(a){b.push(ba(c)+"="+ba(vc(a)))}):b.push(ba(c)+"="+ba(vc(a))))});return b.join("&")}}}function Uf(){this.$get= +function(){return function(a){function b(a,e,f){H(a)?r(a,function(a,c){b(a,e+"["+(D(a)?c:"")+"]")}):D(a)&&!ha(a)?Qc(a,function(a,c){b(a,e+(f?"":"[")+c+(f?"":"]"))}):(B(a)&&(a=a()),d.push(ba(e)+"="+(null==a?"":ba(vc(a)))))}if(!a)return"";var d=[];b(a,"",!0);return d.join("&")}}}function wc(a,b){if(C(a)){var d=a.replace(Lg,"").trim();if(d){var c=b("Content-Type"),c=c&&0===c.indexOf(yd),e;(e=c)||(e=(e=d.match(Mg))&&Ng[e[0]].test(d));if(e)try{a=Tc(d)}catch(f){if(!c)return a;throw Lb("baddata",a,f);}}}return a} +function zd(a){var b=T(),d;C(a)?r(a.split("\n"),function(a){d=a.indexOf(":");var e=K(V(a.substr(0,d)));a=V(a.substr(d+1));e&&(b[e]=b[e]?b[e]+", "+a:a)}):D(a)&&r(a,function(a,d){var f=K(d),g=V(a);f&&(b[f]=b[f]?b[f]+", "+g:g)});return b}function Ad(a){var b;return function(d){b||(b=zd(a));return d?(d=b[K(d)],void 0===d&&(d=null),d):b}}function Bd(a,b,d,c){if(B(c))return c(a,b,d);r(c,function(c){a=c(a,b,d)});return a}function Sf(){var a=this.defaults={transformResponse:[wc],transformRequest:[function(a){return D(a)&& +"[object File]"!==la.call(a)&&"[object Blob]"!==la.call(a)&&"[object FormData]"!==la.call(a)?eb(a):a}],headers:{common:{Accept:"application/json, text/plain, */*"},post:ja(xc),put:ja(xc),patch:ja(xc)},xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",paramSerializer:"$httpParamSerializer",jsonpCallbackParam:"callback"},b=!1;this.useApplyAsync=function(a){return w(a)?(b=!!a,this):b};var d=this.interceptors=[],c=this.xsrfTrustedOrigins=[];Object.defineProperty(this,"xsrfWhitelistedOrigins", +{get:function(){return this.xsrfTrustedOrigins},set:function(a){this.xsrfTrustedOrigins=a}});this.$get=["$browser","$httpBackend","$$cookieReader","$cacheFactory","$rootScope","$q","$injector","$sce",function(e,f,g,k,h,l,m,p){function n(b){function c(a,b){for(var d=0,e=b.length;da?b:l.reject(b)}if(!D(b))throw F("$http")("badreq",b);if(!C(p.valueOf(b.url)))throw F("$http")("badreq",b.url);var g=S({method:"get",transformRequest:a.transformRequest,transformResponse:a.transformResponse,paramSerializer:a.paramSerializer,jsonpCallbackParam:a.jsonpCallbackParam},b);g.headers=function(b){var c=a.headers,e=S({},b.headers),f,g,h,c=S({},c.common,c[K(b.method)]);a:for(f in c){g=K(f);for(h in e)if(K(h)===g)continue a;e[f]=c[f]}return d(e,ja(b))}(b);g.method= +vb(g.method);g.paramSerializer=C(g.paramSerializer)?m.get(g.paramSerializer):g.paramSerializer;e.$$incOutstandingRequestCount("$http");var h=[],k=[];b=l.resolve(g);r(v,function(a){(a.request||a.requestError)&&h.unshift(a.request,a.requestError);(a.response||a.responseError)&&k.push(a.response,a.responseError)});b=c(b,h);b=b.then(function(b){var c=b.headers,d=Bd(b.data,Ad(c),void 0,b.transformRequest);A(d)&&r(c,function(a,b){"content-type"===K(b)&&delete c[b]});A(b.withCredentials)&&!A(a.withCredentials)&& +(b.withCredentials=a.withCredentials);return s(b,d).then(f,f)});b=c(b,k);return b=b.finally(function(){e.$$completeOutstandingRequest(E,"$http")})}function s(c,d){function e(a){if(a){var c={};r(a,function(a,d){c[d]=function(c){function d(){a(c)}b?h.$applyAsync(d):h.$$phase?d():h.$apply(d)}});return c}}function k(a,c,d,e,f){function g(){m(c,a,d,e,f)}R&&(200<=a&&300>a?R.put(O,[a,c,zd(d),e,f]):R.remove(O));b?h.$applyAsync(g):(g(),h.$$phase||h.$apply())}function m(a,b,d,e,f){b=-1<=b?b:0;(200<=b&&300> +b?L.resolve:L.reject)({data:a,status:b,headers:Ad(d),config:c,statusText:e,xhrStatus:f})}function s(a){m(a.data,a.status,ja(a.headers()),a.statusText,a.xhrStatus)}function v(){var a=n.pendingRequests.indexOf(c);-1!==a&&n.pendingRequests.splice(a,1)}var L=l.defer(),u=L.promise,R,q,ma=c.headers,x="jsonp"===K(c.method),O=c.url;x?O=p.getTrustedResourceUrl(O):C(O)||(O=p.valueOf(O));O=G(O,c.paramSerializer(c.params));x&&(O=t(O,c.jsonpCallbackParam));n.pendingRequests.push(c);u.then(v,v);!c.cache&&!a.cache|| +!1===c.cache||"GET"!==c.method&&"JSONP"!==c.method||(R=D(c.cache)?c.cache:D(a.cache)?a.cache:N);R&&(q=R.get(O),w(q)?q&&B(q.then)?q.then(s,s):H(q)?m(q[1],q[0],ja(q[2]),q[3],q[4]):m(q,200,{},"OK","complete"):R.put(O,u));A(q)&&((q=kc(c.url)?g()[c.xsrfCookieName||a.xsrfCookieName]:void 0)&&(ma[c.xsrfHeaderName||a.xsrfHeaderName]=q),f(c.method,O,d,k,ma,c.timeout,c.withCredentials,c.responseType,e(c.eventHandlers),e(c.uploadEventHandlers)));return u}function G(a,b){0=h&&(t.resolve(s),f(r.$$intervalId));G||c.$apply()},k,t,G);return r}}}]}function Cd(a,b){var d=ga(a);b.$$protocol=d.protocol;b.$$host= +d.hostname;b.$$port=fa(d.port)||Rg[d.protocol]||null}function Dd(a,b,d){if(Sg.test(a))throw kb("badpath",a);var c="/"!==a.charAt(0);c&&(a="/"+a);a=ga(a);for(var c=(c&&"/"===a.pathname.charAt(0)?a.pathname.substring(1):a.pathname).split("/"),e=c.length;e--;)c[e]=decodeURIComponent(c[e]),d&&(c[e]=c[e].replace(/\//g,"%2F"));d=c.join("/");b.$$path=d;b.$$search=hc(a.search);b.$$hash=decodeURIComponent(a.hash);b.$$path&&"/"!==b.$$path.charAt(0)&&(b.$$path="/"+b.$$path)}function yc(a,b){return a.slice(0, +b.length)===b}function ya(a,b){if(yc(b,a))return b.substr(a.length)}function Da(a){var b=a.indexOf("#");return-1===b?a:a.substr(0,b)}function zc(a,b,d){this.$$html5=!0;d=d||"";Cd(a,this);this.$$parse=function(a){var d=ya(b,a);if(!C(d))throw kb("ipthprfx",a,b);Dd(d,this,!0);this.$$path||(this.$$path="/");this.$$compose()};this.$$normalizeUrl=function(a){return b+a.substr(1)};this.$$parseLinkUrl=function(c,e){if(e&&"#"===e[0])return this.hash(e.slice(1)),!0;var f,g;w(f=ya(a,c))?(g=f,g=d&&w(f=ya(d,f))? +b+(ya("/",f)||f):a+g):w(f=ya(b,c))?g=b+f:b===c+"/"&&(g=b);g&&this.$$parse(g);return!!g}}function Ac(a,b,d){Cd(a,this);this.$$parse=function(c){var e=ya(a,c)||ya(b,c),f;A(e)||"#"!==e.charAt(0)?this.$$html5?f=e:(f="",A(e)&&(a=c,this.replace())):(f=ya(d,e),A(f)&&(f=e));Dd(f,this,!1);c=this.$$path;var e=a,g=/^\/[A-Z]:(\/.*)/;yc(f,e)&&(f=f.replace(e,""));g.exec(f)||(c=(f=g.exec(c))?f[1]:c);this.$$path=c;this.$$compose()};this.$$normalizeUrl=function(b){return a+(b?d+b:"")};this.$$parseLinkUrl=function(b, +d){return Da(a)===Da(b)?(this.$$parse(b),!0):!1}}function Ed(a,b,d){this.$$html5=!0;Ac.apply(this,arguments);this.$$parseLinkUrl=function(c,e){if(e&&"#"===e[0])return this.hash(e.slice(1)),!0;var f,g;a===Da(c)?f=c:(g=ya(b,c))?f=a+d+g:b===c+"/"&&(f=b);f&&this.$$parse(f);return!!f};this.$$normalizeUrl=function(b){return a+d+b}}function Mb(a){return function(){return this[a]}}function Fd(a,b){return function(d){if(A(d))return this[a];this[a]=b(d);this.$$compose();return this}}function Yf(){var a="!", +b={enabled:!1,requireBase:!0,rewriteLinks:!0};this.hashPrefix=function(b){return w(b)?(a=b,this):a};this.html5Mode=function(a){if(Ga(a))return b.enabled=a,this;if(D(a)){Ga(a.enabled)&&(b.enabled=a.enabled);Ga(a.requireBase)&&(b.requireBase=a.requireBase);if(Ga(a.rewriteLinks)||C(a.rewriteLinks))b.rewriteLinks=a.rewriteLinks;return this}return b};this.$get=["$rootScope","$browser","$sniffer","$rootElement","$window",function(d,c,e,f,g){function k(a,b){return a===b||ga(a).href===ga(b).href}function h(a, +b,d){var e=m.url(),f=m.$$state;try{c.url(a,b,d),m.$$state=c.state()}catch(g){throw m.url(e),m.$$state=f,g;}}function l(a,b){d.$broadcast("$locationChangeSuccess",m.absUrl(),a,m.$$state,b)}var m,p;p=c.baseHref();var n=c.url(),s;if(b.enabled){if(!p&&b.requireBase)throw kb("nobase");s=n.substring(0,n.indexOf("/",n.indexOf("//")+2))+(p||"/");p=e.history?zc:Ed}else s=Da(n),p=Ac;var r=s.substr(0,Da(s).lastIndexOf("/")+1);m=new p(s,r,"#"+a);m.$$parseLinkUrl(n,n);m.$$state=c.state();var t=/^\s*(javascript|mailto):/i; +f.on("click",function(a){var e=b.rewriteLinks;if(e&&!a.ctrlKey&&!a.metaKey&&!a.shiftKey&&2!==a.which&&2!==a.button){for(var g=x(a.target);"a"!==ua(g[0]);)if(g[0]===f[0]||!(g=g.parent())[0])return;if(!C(e)||!A(g.attr(e))){var e=g.prop("href"),h=g.attr("href")||g.attr("xlink:href");D(e)&&"[object SVGAnimatedString]"===e.toString()&&(e=ga(e.animVal).href);t.test(e)||!e||g.attr("target")||a.isDefaultPrevented()||!m.$$parseLinkUrl(e,h)||(a.preventDefault(),m.absUrl()!==c.url()&&d.$apply())}}});m.absUrl()!== +n&&c.url(m.absUrl(),!0);var N=!0;c.onUrlChange(function(a,b){yc(a,r)?(d.$evalAsync(function(){var c=m.absUrl(),e=m.$$state,f;m.$$parse(a);m.$$state=b;f=d.$broadcast("$locationChangeStart",a,c,b,e).defaultPrevented;m.absUrl()===a&&(f?(m.$$parse(c),m.$$state=e,h(c,!1,e)):(N=!1,l(c,e)))}),d.$$phase||d.$digest()):g.location.href=a});d.$watch(function(){if(N||m.$$urlUpdatedByLocation){m.$$urlUpdatedByLocation=!1;var a=c.url(),b=m.absUrl(),f=c.state(),g=m.$$replace,n=!k(a,b)||m.$$html5&&e.history&&f!== +m.$$state;if(N||n)N=!1,d.$evalAsync(function(){var b=m.absUrl(),c=d.$broadcast("$locationChangeStart",b,a,m.$$state,f).defaultPrevented;m.absUrl()===b&&(c?(m.$$parse(a),m.$$state=f):(n&&h(b,g,f===m.$$state?null:m.$$state),l(a,f)))})}m.$$replace=!1});return m}]}function Zf(){var a=!0,b=this;this.debugEnabled=function(b){return w(b)?(a=b,this):a};this.$get=["$window",function(d){function c(a){dc(a)&&(a.stack&&f?a=a.message&&-1===a.stack.indexOf(a.message)?"Error: "+a.message+"\n"+a.stack:a.stack:a.sourceURL&& +(a=a.message+"\n"+a.sourceURL+":"+a.line));return a}function e(a){var b=d.console||{},e=b[a]||b.log||E;return function(){var a=[];r(arguments,function(b){a.push(c(b))});return Function.prototype.apply.call(e,b,a)}}var f=wa||/\bEdge\//.test(d.navigator&&d.navigator.userAgent);return{log:e("log"),info:e("info"),warn:e("warn"),error:e("error"),debug:function(){var c=e("debug");return function(){a&&c.apply(b,arguments)}}()}}]}function Tg(a){return a+""}function Ug(a,b){return"undefined"!==typeof a?a: +b}function Gd(a,b){return"undefined"===typeof a?b:"undefined"===typeof b?a:a+b}function Vg(a,b){switch(a.type){case q.MemberExpression:if(a.computed)return!1;break;case q.UnaryExpression:return 1;case q.BinaryExpression:return"+"!==a.operator?1:!1;case q.CallExpression:return!1}return void 0===b?Hd:b}function Z(a,b,d){var c,e,f=a.isPure=Vg(a,d);switch(a.type){case q.Program:c=!0;r(a.body,function(a){Z(a.expression,b,f);c=c&&a.expression.constant});a.constant=c;break;case q.Literal:a.constant=!0;a.toWatch= +[];break;case q.UnaryExpression:Z(a.argument,b,f);a.constant=a.argument.constant;a.toWatch=a.argument.toWatch;break;case q.BinaryExpression:Z(a.left,b,f);Z(a.right,b,f);a.constant=a.left.constant&&a.right.constant;a.toWatch=a.left.toWatch.concat(a.right.toWatch);break;case q.LogicalExpression:Z(a.left,b,f);Z(a.right,b,f);a.constant=a.left.constant&&a.right.constant;a.toWatch=a.constant?[]:[a];break;case q.ConditionalExpression:Z(a.test,b,f);Z(a.alternate,b,f);Z(a.consequent,b,f);a.constant=a.test.constant&& +a.alternate.constant&&a.consequent.constant;a.toWatch=a.constant?[]:[a];break;case q.Identifier:a.constant=!1;a.toWatch=[a];break;case q.MemberExpression:Z(a.object,b,f);a.computed&&Z(a.property,b,f);a.constant=a.object.constant&&(!a.computed||a.property.constant);a.toWatch=a.constant?[]:[a];break;case q.CallExpression:c=d=a.filter?!b(a.callee.name).$stateful:!1;e=[];r(a.arguments,function(a){Z(a,b,f);c=c&&a.constant;e.push.apply(e,a.toWatch)});a.constant=c;a.toWatch=d?e:[a];break;case q.AssignmentExpression:Z(a.left, +b,f);Z(a.right,b,f);a.constant=a.left.constant&&a.right.constant;a.toWatch=[a];break;case q.ArrayExpression:c=!0;e=[];r(a.elements,function(a){Z(a,b,f);c=c&&a.constant;e.push.apply(e,a.toWatch)});a.constant=c;a.toWatch=e;break;case q.ObjectExpression:c=!0;e=[];r(a.properties,function(a){Z(a.value,b,f);c=c&&a.value.constant;e.push.apply(e,a.value.toWatch);a.computed&&(Z(a.key,b,!1),c=c&&a.key.constant,e.push.apply(e,a.key.toWatch))});a.constant=c;a.toWatch=e;break;case q.ThisExpression:a.constant= +!1;a.toWatch=[];break;case q.LocalsExpression:a.constant=!1,a.toWatch=[]}}function Id(a){if(1===a.length){a=a[0].expression;var b=a.toWatch;return 1!==b.length?b:b[0]!==a?b:void 0}}function Jd(a){return a.type===q.Identifier||a.type===q.MemberExpression}function Kd(a){if(1===a.body.length&&Jd(a.body[0].expression))return{type:q.AssignmentExpression,left:a.body[0].expression,right:{type:q.NGValueParameter},operator:"="}}function Ld(a){this.$filter=a}function Md(a){this.$filter=a}function Nb(a,b,d){this.ast= +new q(a,d);this.astCompiler=d.csp?new Md(b):new Ld(b)}function Bc(a){return B(a.valueOf)?a.valueOf():Wg.call(a)}function $f(){var a=T(),b={"true":!0,"false":!1,"null":null,undefined:void 0},d,c;this.addLiteral=function(a,c){b[a]=c};this.setIdentifierFns=function(a,b){d=a;c=b;return this};this.$get=["$filter",function(e){function f(b,c){var d,f;switch(typeof b){case "string":return f=b=b.trim(),d=a[f],d||(d=new Ob(G),d=(new Nb(d,e,G)).parse(b),a[f]=p(d)),s(d,c);case "function":return s(b,c);default:return s(E, +c)}}function g(a,b,c){return null==a||null==b?a===b:"object"!==typeof a||(a=Bc(a),"object"!==typeof a||c)?a===b||a!==a&&b!==b:!1}function k(a,b,c,d,e){var f=d.inputs,h;if(1===f.length){var k=g,f=f[0];return a.$watch(function(a){var b=f(a);g(b,k,f.isPure)||(h=d(a,void 0,void 0,[b]),k=b&&Bc(b));return h},b,c,e)}for(var l=[],m=[],n=0,p=f.length;n=c.$$state.status&&e&&e.length&&a(function(){for(var a,c,f=0,g=e.length;fa)for(b in l++, +f)ta.call(e,b)||(t--,delete f[b])}else f!==e&&(f=e,l++);return l}}c.$$pure=g(a).literal;c.$stateful=!c.$$pure;var d=this,e,f,h,k=1r&&(A=4-r,N[A]||(N[A]=[]),N[A].push({msg:B(a.exp)?"fn: "+(a.exp.name||a.exp.toString()):a.exp,newVal:g,oldVal:h}));else if(a===c){s= +!1;break a}}catch(E){f(E)}if(!(n=!q.$$suspended&&q.$$watchersCount&&q.$$childHead||q!==y&&q.$$nextSibling))for(;q!==y&&!(n=q.$$nextSibling);)q=q.$parent}while(q=n);if((s||w.length)&&!r--)throw v.$$phase=null,d("infdig",b,N);}while(s||w.length);for(v.$$phase=null;Jwa)throw Ea("iequirks");var c=ja(W);c.isEnabled=function(){return a};c.trustAs=d.trustAs;c.getTrusted=d.getTrusted;c.valueOf=d.valueOf;a||(c.trustAs=c.getTrusted=function(a,b){return b},c.valueOf=Ta);c.parseAs=function(a,d){var e=b(d);return e.literal&&e.constant?e:b(d,function(b){return c.getTrusted(a,b)})};var e=c.parseAs,f=c.getTrusted,g=c.trustAs;r(W, +function(a,b){var d=K(b);c[("parse_as_"+d).replace(Dc,xb)]=function(b){return e(a,b)};c[("get_trusted_"+d).replace(Dc,xb)]=function(b){return f(a,b)};c[("trust_as_"+d).replace(Dc,xb)]=function(b){return g(a,b)}});return c}]}function fg(){this.$get=["$window","$document",function(a,b){var d={},c=!((!a.nw||!a.nw.process)&&a.chrome&&(a.chrome.app&&a.chrome.app.runtime||!a.chrome.app&&a.chrome.runtime&&a.chrome.runtime.id))&&a.history&&a.history.pushState,e=fa((/android (\d+)/.exec(K((a.navigator||{}).userAgent))|| +[])[1]),f=/Boxee/i.test((a.navigator||{}).userAgent),g=b[0]||{},k=g.body&&g.body.style,h=!1,l=!1;k&&(h=!!("transition"in k||"webkitTransition"in k),l=!!("animation"in k||"webkitAnimation"in k));return{history:!(!c||4>e||f),hasEvent:function(a){if("input"===a&&wa)return!1;if(A(d[a])){var b=g.createElement("div");d[a]="on"+a in b}return d[a]},csp:Ba(),transitions:h,animations:l,android:e}}]}function gg(){this.$get=ia(function(a){return new Yg(a)})}function Yg(a){function b(){var a=e.pop();return a&& +a.cb}function d(a){for(var b=e.length-1;0<=b;--b){var c=e[b];if(c.type===a)return e.splice(b,1),c.cb}}var c={},e=[],f=this.ALL_TASKS_TYPE="$$all$$",g=this.DEFAULT_TASK_TYPE="$$default$$";this.completeTask=function(e,h){h=h||g;try{e()}finally{var l;l=h||g;c[l]&&(c[l]--,c[f]--);l=c[h];var m=c[f];if(!m||!l)for(l=m?d:b;m=l(h);)try{m()}catch(p){a.error(p)}}};this.incTaskCount=function(a){a=a||g;c[a]=(c[a]||0)+1;c[f]=(c[f]||0)+1};this.notifyWhenNoPendingTasks=function(a,b){b=b||f;c[b]?e.push({type:b,cb:a}): +a()}}function ig(){var a;this.httpOptions=function(b){return b?(a=b,this):a};this.$get=["$exceptionHandler","$templateCache","$http","$q","$sce",function(b,d,c,e,f){function g(k,h){g.totalPendingRequests++;if(!C(k)||A(d.get(k)))k=f.getTrustedResourceUrl(k);var l=c.defaults&&c.defaults.transformResponse;H(l)?l=l.filter(function(a){return a!==wc}):l===wc&&(l=null);return c.get(k,S({cache:d,transformResponse:l},a)).finally(function(){g.totalPendingRequests--}).then(function(a){return d.put(k,a.data)}, +function(a){h||(a=Zg("tpload",k,a.status,a.statusText),b(a));return e.reject(a)})}g.totalPendingRequests=0;return g}]}function jg(){this.$get=["$rootScope","$browser","$location",function(a,b,d){return{findBindings:function(a,b,d){a=a.getElementsByClassName("ng-binding");var g=[];r(a,function(a){var c=ca.element(a).data("$binding");c&&r(c,function(c){d?(new RegExp("(^|\\s)"+Od(b)+"(\\s|\\||$)")).test(c)&&g.push(a):-1!==c.indexOf(b)&&g.push(a)})});return g},findModels:function(a,b,d){for(var g=["ng-", +"data-ng-","ng\\:"],k=0;kc&&(c=e),c+=+a.slice(e+1),a=a.substring(0,e)):0>c&&(c=a.length);for(e=0;a.charAt(e)===Fc;e++);if(e===(g=a.length))d=[0],c=1;else{for(g--;a.charAt(g)===Fc;)g--;c-=e;d=[];for(f=0;e<=g;e++,f++)d[f]=+a.charAt(e)}c>Yd&&(d=d.splice(0,Yd-1),b=c-1,c=1);return{d:d,e:b,i:c}}function ih(a, +b,d,c){var e=a.d,f=e.length-a.i;b=A(b)?Math.min(Math.max(d,f),c):+b;d=b+a.i;c=e[d];if(0d-1){for(c=0;c>d;c--)e.unshift(0),a.i++;e.unshift(1);a.i++}else e[d-1]++;for(;fk;)h.unshift(0),k++;0=b.lgSize&&k.unshift(h.splice(-b.lgSize,h.length).join(""));h.length>b.gSize;)k.unshift(h.splice(-b.gSize,h.length).join(""));h.length&&k.unshift(h.join(""));h=k.join(d);f.length&&(h+=c+f.join(""));e&&(h+="e+"+e)}return 0>a&&!g?b.negPre+h+b.negSuf:b.posPre+ +h+b.posSuf}function Pb(a,b,d,c){var e="";if(0>a||c&&0>=a)c?a=-a+1:(a=-a,e="-");for(a=""+a;a.length-d)f+=d;0===f&&-12===d&&(f=12);return Pb(f,b,c,e)}}function lb(a,b,d){return function(c,e){var f=c["get"+a](),g=vb((d?"STANDALONE":"")+(b?"SHORT":"")+a);return e[g][f]}}function Zd(a){var b=(new Date(a,0,1)).getDay();return new Date(a,0,(4>=b?5:12)-b)}function $d(a){return function(b){var d= +Zd(b.getFullYear());b=+new Date(b.getFullYear(),b.getMonth(),b.getDate()+(4-b.getDay()))-+d;b=1+Math.round(b/6048E5);return Pb(b,a)}}function Gc(a,b){return 0>=a.getFullYear()?b.ERAS[0]:b.ERAS[1]}function Td(a){function b(a){var b;if(b=a.match(d)){a=new Date(0);var f=0,g=0,k=b[8]?a.setUTCFullYear:a.setFullYear,h=b[8]?a.setUTCHours:a.setHours;b[9]&&(f=fa(b[9]+b[10]),g=fa(b[9]+b[11]));k.call(a,fa(b[1]),fa(b[2])-1,fa(b[3]));f=fa(b[4]||0)-f;g=fa(b[5]||0)-g;k=fa(b[6]||0);b=Math.round(1E3*parseFloat("0."+ +(b[7]||0)));h.call(a,f,g,k,b)}return a}var d=/^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;return function(c,d,f){var g="",k=[],h,l;d=d||"mediumDate";d=a.DATETIME_FORMATS[d]||d;C(c)&&(c=jh.test(c)?fa(c):b(c));X(c)&&(c=new Date(c));if(!ha(c)||!isFinite(c.getTime()))return c;for(;d;)(l=kh.exec(d))?(k=db(k,l,1),d=k.pop()):(k.push(d),d=null);var m=c.getTimezoneOffset();f&&(m=fc(f,m),c=gc(c,f,!0));r(k,function(b){h=lh[b];g+=h?h(c,a.DATETIME_FORMATS, +m):"''"===b?"'":b.replace(/(^'|'$)/g,"").replace(/''/g,"'")});return g}}function ch(){return function(a,b){A(b)&&(b=2);return eb(a,b)}}function dh(){return function(a,b,d){b=Infinity===Math.abs(Number(b))?Number(b):fa(b);if(Y(b))return a;X(a)&&(a=a.toString());if(!za(a))return a;d=!d||isNaN(d)?0:fa(d);d=0>d?Math.max(0,a.length+d):d;return 0<=b?Hc(a,d,d+b):0===d?Hc(a,b,a.length):Hc(a,Math.max(0,d+b),d)}}function Hc(a,b,d){return C(a)?a.slice(b,d):Ha.call(a,b,d)}function Vd(a){function b(b){return b.map(function(b){var c= +1,d=Ta;if(B(b))d=b;else if(C(b)){if("+"===b.charAt(0)||"-"===b.charAt(0))c="-"===b.charAt(0)?-1:1,b=b.substring(1);if(""!==b&&(d=a(b),d.constant))var e=d(),d=function(a){return a[e]}}return{get:d,descending:c}})}function d(a){switch(typeof a){case "number":case "boolean":case "string":return!0;default:return!1}}function c(a,b){var c=0,d=a.type,h=b.type;if(d===h){var h=a.value,l=b.value;"string"===d?(h=h.toLowerCase(),l=l.toLowerCase()):"object"===d&&(D(h)&&(h=a.index),D(l)&&(l=b.index));h!==l&&(c= +hb||37<=b&&40>=b|| +m(a,this,this.value)});if(e.hasEvent("paste"))b.on("paste cut drop",m)}b.on("change",l);if(ee[g]&&c.$$hasNativeValidators&&g===d.type)b.on("keydown wheel mousedown",function(a){if(!h){var b=this.validity,c=b.badInput,d=b.typeMismatch;h=f.defer(function(){h=null;b.badInput===c&&b.typeMismatch===d||l(a)})}});c.$render=function(){var a=c.$isEmpty(c.$viewValue)?"":c.$viewValue;b.val()!==a&&b.val(a)}}function Rb(a,b){return function(d,c){var e,f;if(ha(d))return d;if(C(d)){'"'===d.charAt(0)&&'"'===d.charAt(d.length- +1)&&(d=d.substring(1,d.length-1));if(mh.test(d))return new Date(d);a.lastIndex=0;if(e=a.exec(d))return e.shift(),f=c?{yyyy:c.getFullYear(),MM:c.getMonth()+1,dd:c.getDate(),HH:c.getHours(),mm:c.getMinutes(),ss:c.getSeconds(),sss:c.getMilliseconds()/1E3}:{yyyy:1970,MM:1,dd:1,HH:0,mm:0,ss:0,sss:0},r(e,function(a,c){cf.yyyy&&e.setFullYear(f.yyyy),e}return NaN}}function ob(a,b,d,c){return function(e,f,g,k,h,l,m, +p){function n(a){return a&&!(a.getTime&&a.getTime()!==a.getTime())}function s(a){return w(a)&&!ha(a)?r(a)||void 0:a}function r(a,b){var c=k.$options.getOption("timezone");v&&v!==c&&(b=Uc(b,fc(v)));var e=d(a,b);!isNaN(e)&&c&&(e=gc(e,c));return e}Jc(e,f,g,k,a);Sa(e,f,g,k,h,l);var t="time"===a||"datetimelocal"===a,q,v;k.$parsers.push(function(c){if(k.$isEmpty(c))return null;if(b.test(c))return r(c,q);k.$$parserName=a});k.$formatters.push(function(a){if(a&&!ha(a))throw pb("datefmt",a);if(n(a)){q=a;var b= +k.$options.getOption("timezone");b&&(v=b,q=gc(q,b,!0));var d=c;t&&C(k.$options.getOption("timeSecondsFormat"))&&(d=c.replace("ss.sss",k.$options.getOption("timeSecondsFormat")).replace(/:$/,""));a=m("date")(a,d,b);t&&k.$options.getOption("timeStripZeroSeconds")&&(a=a.replace(/(?::00)?(?:\.000)?$/,""));return a}v=q=null;return""});if(w(g.min)||g.ngMin){var x=g.min||p(g.ngMin)(e),z=s(x);k.$validators.min=function(a){return!n(a)||A(z)||d(a)>=z};g.$observe("min",function(a){a!==x&&(z=s(a),x=a,k.$validate())})}if(w(g.max)|| +g.ngMax){var y=g.max||p(g.ngMax)(e),J=s(y);k.$validators.max=function(a){return!n(a)||A(J)||d(a)<=J};g.$observe("max",function(a){a!==y&&(J=s(a),y=a,k.$validate())})}}}function Jc(a,b,d,c,e){(c.$$hasNativeValidators=D(b[0].validity))&&c.$parsers.push(function(a){var d=b.prop("validity")||{};if(d.badInput||d.typeMismatch)c.$$parserName=e;else return a})}function fe(a){a.$parsers.push(function(b){if(a.$isEmpty(b))return null;if(nh.test(b))return parseFloat(b);a.$$parserName="number"});a.$formatters.push(function(b){if(!a.$isEmpty(b)){if(!X(b))throw pb("numfmt", +b);b=b.toString()}return b})}function na(a){w(a)&&!X(a)&&(a=parseFloat(a));return Y(a)?void 0:a}function Kc(a){var b=a.toString(),d=b.indexOf(".");return-1===d?-1a&&(a=/e-(\d+)$/.exec(b))?Number(a[1]):0:b.length-d-1}function ge(a,b,d){a=Number(a);var c=(a|0)!==a,e=(b|0)!==b,f=(d|0)!==d;if(c||e||f){var g=c?Kc(a):0,k=e?Kc(b):0,h=f?Kc(d):0,g=Math.max(g,k,h),g=Math.pow(10,g);a*=g;b*=g;d*=g;c&&(a=Math.round(a));e&&(b=Math.round(b));f&&(d=Math.round(d))}return 0===(a-b)%d}function he(a,b,d,c,e){if(w(c)){a= +a(c);if(!a.constant)throw pb("constexpr",d,c);return a(b)}return e}function Lc(a,b){function d(a,b){if(!a||!a.length)return[];if(!b||!b.length)return a;var c=[],d=0;a:for(;d(?:<\/\1>|)$/,nc=/<|&#?\w+;/,rg=/<([\w:-]+)/,sg=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,qa={thead:["table"],col:["colgroup","table"],tr:["tbody","table"],td:["tr", +"tbody","table"]};qa.tbody=qa.tfoot=qa.colgroup=qa.caption=qa.thead;qa.th=qa.td;var hb={option:[1,'"],_default:[0,"",""]},Nc;for(Nc in qa){var le=qa[Nc],me=le.slice().reverse();hb[Nc]=[me.length,"<"+me.join("><")+">",""]}hb.optgroup=hb.option;var zg=z.Node.prototype.contains||function(a){return!!(this.compareDocumentPosition(a)&16)},Wa=U.prototype={ready:hd,toString:function(){var a=[];r(this,function(b){a.push(""+b)});return"["+a.join(", ")+ +"]"},eq:function(a){return 0<=a?x(this[a]):x(this[this.length+a])},length:0,push:ph,sort:[].sort,splice:[].splice},Hb={};r("multiple selected checked disabled readOnly required open".split(" "),function(a){Hb[K(a)]=a});var od={};r("input select option textarea button form details".split(" "),function(a){od[a]=!0});var vd={ngMinlength:"minlength",ngMaxlength:"maxlength",ngMin:"min",ngMax:"max",ngPattern:"pattern",ngStep:"step"};r({data:sc,removeData:rc,hasData:function(a){for(var b in Ka[a.ng339])return!0; +return!1},cleanData:function(a){for(var b=0,d=a.length;b/,Cg=/^[^(]*\(\s*([^)]*)\)/m,sh=/,/,th=/^\s*(_?)(\S+?)\1\s*$/,Ag=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,Ca=F("$injector");fb.$$annotate=function(a,b,d){var c;if("function"===typeof a){if(!(c=a.$inject)){c=[];if(a.length){if(b)throw C(d)&&d||(d=a.name||Dg(a)),Ca("strictdi",d);b=qd(a);r(b[1].split(sh),function(a){a.replace(th,function(a,b,d){c.push(d)})})}a.$inject=c}}else H(a)?(b=a.length-1,tb(a[b],"fn"),c=a.slice(0,b)):tb(a,"fn",!0);return c};var ne=F("$animate"), +Ef=function(){this.$get=E},Ff=function(){var a=new Ib,b=[];this.$get=["$$AnimateRunner","$rootScope",function(d,c){function e(a,b,c){var d=!1;b&&(b=C(b)?b.split(" "):H(b)?b:[],r(b,function(b){b&&(d=!0,a[b]=c)}));return d}function f(){r(b,function(b){var c=a.get(b);if(c){var d=Eg(b.attr("class")),e="",f="";r(c,function(a,b){a!==!!d[b]&&(a?e+=(e.length?" ":"")+b:f+=(f.length?" ":"")+b)});r(b,function(a){e&&Eb(a,e);f&&Db(a,f)});a.delete(b)}});b.length=0}return{enabled:E,on:E,off:E,pin:E,push:function(g, +k,h,l){l&&l();h=h||{};h.from&&g.css(h.from);h.to&&g.css(h.to);if(h.addClass||h.removeClass)if(k=h.addClass,l=h.removeClass,h=a.get(g)||{},k=e(h,k,!0),l=e(h,l,!1),k||l)a.set(g,h),b.push(g),1===b.length&&c.$$postDigest(f);g=new d;g.complete();return g}}}]},Cf=["$provide",function(a){var b=this,d=null,c=null;this.$$registeredAnimations=Object.create(null);this.register=function(c,d){if(c&&"."!==c.charAt(0))throw ne("notcsel",c);var g=c+"-animation";b.$$registeredAnimations[c.substr(1)]=g;a.factory(g, +d)};this.customFilter=function(a){1===arguments.length&&(c=B(a)?a:null);return c};this.classNameFilter=function(a){if(1===arguments.length&&(d=a instanceof RegExp?a:null)&&/[(\s|\/)]ng-animate[(\s|\/)]/.test(d.toString()))throw d=null,ne("nongcls","ng-animate");return d};this.$get=["$$animateQueue",function(a){function b(a,c,d){if(d){var e;a:{for(e=0;e <= >= && || ! = |".split(" "),function(a){Vb[a]= +!0});var wh={n:"\n",f:"\f",r:"\r",t:"\t",v:"\v","'":"'",'"':'"'},Ob=function(a){this.options=a};Ob.prototype={constructor:Ob,lex:function(a){this.text=a;this.index=0;for(this.tokens=[];this.index=a&&"string"=== +typeof a},isWhitespace:function(a){return" "===a||"\r"===a||"\t"===a||"\n"===a||"\v"===a||"\u00a0"===a},isIdentifierStart:function(a){return this.options.isIdentifierStart?this.options.isIdentifierStart(a,this.codePointAt(a)):this.isValidIdentifierStart(a)},isValidIdentifierStart:function(a){return"a"<=a&&"z">=a||"A"<=a&&"Z">=a||"_"===a||"$"===a},isIdentifierContinue:function(a){return this.options.isIdentifierContinue?this.options.isIdentifierContinue(a,this.codePointAt(a)):this.isValidIdentifierContinue(a)}, +isValidIdentifierContinue:function(a,b){return this.isValidIdentifierStart(a,b)||this.isNumber(a)},codePointAt:function(a){return 1===a.length?a.charCodeAt(0):(a.charCodeAt(0)<<10)+a.charCodeAt(1)-56613888},peekMultichar:function(){var a=this.text.charAt(this.index),b=this.peek();if(!b)return a;var d=a.charCodeAt(0),c=b.charCodeAt(0);return 55296<=d&&56319>=d&&56320<=c&&57343>=c?a+b:a},isExpOperator:function(a){return"-"===a||"+"===a||this.isNumber(a)},throwError:function(a,b,d){d=d||this.index;b= +w(b)?"s "+b+"-"+this.index+" ["+this.text.substring(b,d)+"]":" "+d;throw Ya("lexerr",a,b,this.text);},readNumber:function(){for(var a="",b=this.index;this.index","<=",">=");)a={type:q.BinaryExpression,operator:b.text, +left:a,right:this.additive()};return a},additive:function(){for(var a=this.multiplicative(),b;b=this.expect("+","-");)a={type:q.BinaryExpression,operator:b.text,left:a,right:this.multiplicative()};return a},multiplicative:function(){for(var a=this.unary(),b;b=this.expect("*","/","%");)a={type:q.BinaryExpression,operator:b.text,left:a,right:this.unary()};return a},unary:function(){var a;return(a=this.expect("+","-","!"))?{type:q.UnaryExpression,operator:a.text,prefix:!0,argument:this.unary()}:this.primary()}, +primary:function(){var a;this.expect("(")?(a=this.filterChain(),this.consume(")")):this.expect("[")?a=this.arrayDeclaration():this.expect("{")?a=this.object():this.selfReferential.hasOwnProperty(this.peek().text)?a=Ia(this.selfReferential[this.consume().text]):this.options.literals.hasOwnProperty(this.peek().text)?a={type:q.Literal,value:this.options.literals[this.consume().text]}:this.peek().identifier?a=this.identifier():this.peek().constant?a=this.constant():this.throwError("not a primary expression", +this.peek());for(var b;b=this.expect("(","[",".");)"("===b.text?(a={type:q.CallExpression,callee:a,arguments:this.parseArguments()},this.consume(")")):"["===b.text?(a={type:q.MemberExpression,object:a,property:this.expression(),computed:!0},this.consume("]")):"."===b.text?a={type:q.MemberExpression,object:a,property:this.identifier(),computed:!1}:this.throwError("IMPOSSIBLE");return a},filter:function(a){a=[a];for(var b={type:q.CallExpression,callee:this.identifier(),arguments:a,filter:!0};this.expect(":");)a.push(this.expression()); +return b},parseArguments:function(){var a=[];if(")"!==this.peekToken().text){do a.push(this.filterChain());while(this.expect(","))}return a},identifier:function(){var a=this.consume();a.identifier||this.throwError("is not a valid identifier",a);return{type:q.Identifier,name:a.text}},constant:function(){return{type:q.Literal,value:this.consume().value}},arrayDeclaration:function(){var a=[];if("]"!==this.peekToken().text){do{if(this.peek("]"))break;a.push(this.expression())}while(this.expect(","))}this.consume("]"); +return{type:q.ArrayExpression,elements:a}},object:function(){var a=[],b;if("}"!==this.peekToken().text){do{if(this.peek("}"))break;b={type:q.Property,kind:"init"};this.peek().constant?(b.key=this.constant(),b.computed=!1,this.consume(":"),b.value=this.expression()):this.peek().identifier?(b.key=this.identifier(),b.computed=!1,this.peek(":")?(this.consume(":"),b.value=this.expression()):b.value=b.key):this.peek("[")?(this.consume("["),b.key=this.expression(),this.consume("]"),b.computed=!0,this.consume(":"), +b.value=this.expression()):this.throwError("invalid key",this.peek());a.push(b)}while(this.expect(","))}this.consume("}");return{type:q.ObjectExpression,properties:a}},throwError:function(a,b){throw Ya("syntax",b.text,a,b.index+1,this.text,this.text.substring(b.index));},consume:function(a){if(0===this.tokens.length)throw Ya("ueoe",this.text);var b=this.expect(a);b||this.throwError("is unexpected, expecting ["+a+"]",this.peek());return b},peekToken:function(){if(0===this.tokens.length)throw Ya("ueoe", +this.text);return this.tokens[0]},peek:function(a,b,d,c){return this.peekAhead(0,a,b,d,c)},peekAhead:function(a,b,d,c,e){if(this.tokens.length>a){a=this.tokens[a];var f=a.text;if(f===b||f===d||f===c||f===e||!(b||d||c||e))return a}return!1},expect:function(a,b,d,c){return(a=this.peek(a,b,d,c))?(this.tokens.shift(),a):!1},selfReferential:{"this":{type:q.ThisExpression},$locals:{type:q.LocalsExpression}}};var Hd=2;Ld.prototype={compile:function(a){var b=this;this.state={nextId:0,filters:{},fn:{vars:[], +body:[],own:{}},assign:{vars:[],body:[],own:{}},inputs:[]};Z(a,b.$filter);var d="",c;this.stage="assign";if(c=Kd(a))this.state.computing="assign",d=this.nextId(),this.recurse(c,d),this.return_(d),d="fn.assign="+this.generateFunction("assign","s,v,l");c=Id(a.body);b.stage="inputs";r(c,function(a,c){var d="fn"+c;b.state[d]={vars:[],body:[],own:{}};b.state.computing=d;var k=b.nextId();b.recurse(a,k);b.return_(k);b.state.inputs.push({name:d,isPure:a.isPure});a.watchId=c});this.state.computing="fn";this.stage= +"main";this.recurse(a);a='"'+this.USE+" "+this.STRICT+'";\n'+this.filterPrefix()+"var fn="+this.generateFunction("fn","s,l,a,i")+d+this.watchFns()+"return fn;";a=(new Function("$filter","getStringValue","ifDefined","plus",a))(this.$filter,Tg,Ug,Gd);this.state=this.stage=void 0;return a},USE:"use",STRICT:"strict",watchFns:function(){var a=[],b=this.state.inputs,d=this;r(b,function(b){a.push("var "+b.name+"="+d.generateFunction(b.name,"s"));b.isPure&&a.push(b.name,".isPure="+JSON.stringify(b.isPure)+ +";")});b.length&&a.push("fn.inputs=["+b.map(function(a){return a.name}).join(",")+"];");return a.join("")},generateFunction:function(a,b){return"function("+b+"){"+this.varsPrefix(a)+this.body(a)+"};"},filterPrefix:function(){var a=[],b=this;r(this.state.filters,function(d,c){a.push(d+"=$filter("+b.escape(c)+")")});return a.length?"var "+a.join(",")+";":""},varsPrefix:function(a){return this.state[a].vars.length?"var "+this.state[a].vars.join(",")+";":""},body:function(a){return this.state[a].body.join("")}, +recurse:function(a,b,d,c,e,f){var g,k,h=this,l,m,p;c=c||E;if(!f&&w(a.watchId))b=b||this.nextId(),this.if_("i",this.lazyAssign(b,this.computedMember("i",a.watchId)),this.lazyRecurse(a,b,d,c,e,!0));else switch(a.type){case q.Program:r(a.body,function(b,c){h.recurse(b.expression,void 0,void 0,function(a){k=a});c!==a.body.length-1?h.current().body.push(k,";"):h.return_(k)});break;case q.Literal:m=this.escape(a.value);this.assign(b,m);c(b||m);break;case q.UnaryExpression:this.recurse(a.argument,void 0, +void 0,function(a){k=a});m=a.operator+"("+this.ifDefined(k,0)+")";this.assign(b,m);c(m);break;case q.BinaryExpression:this.recurse(a.left,void 0,void 0,function(a){g=a});this.recurse(a.right,void 0,void 0,function(a){k=a});m="+"===a.operator?this.plus(g,k):"-"===a.operator?this.ifDefined(g,0)+a.operator+this.ifDefined(k,0):"("+g+")"+a.operator+"("+k+")";this.assign(b,m);c(m);break;case q.LogicalExpression:b=b||this.nextId();h.recurse(a.left,b);h.if_("&&"===a.operator?b:h.not(b),h.lazyRecurse(a.right, +b));c(b);break;case q.ConditionalExpression:b=b||this.nextId();h.recurse(a.test,b);h.if_(b,h.lazyRecurse(a.alternate,b),h.lazyRecurse(a.consequent,b));c(b);break;case q.Identifier:b=b||this.nextId();d&&(d.context="inputs"===h.stage?"s":this.assign(this.nextId(),this.getHasOwnProperty("l",a.name)+"?l:s"),d.computed=!1,d.name=a.name);h.if_("inputs"===h.stage||h.not(h.getHasOwnProperty("l",a.name)),function(){h.if_("inputs"===h.stage||"s",function(){e&&1!==e&&h.if_(h.isNull(h.nonComputedMember("s",a.name)), +h.lazyAssign(h.nonComputedMember("s",a.name),"{}"));h.assign(b,h.nonComputedMember("s",a.name))})},b&&h.lazyAssign(b,h.nonComputedMember("l",a.name)));c(b);break;case q.MemberExpression:g=d&&(d.context=this.nextId())||this.nextId();b=b||this.nextId();h.recurse(a.object,g,void 0,function(){h.if_(h.notNull(g),function(){a.computed?(k=h.nextId(),h.recurse(a.property,k),h.getStringValue(k),e&&1!==e&&h.if_(h.not(h.computedMember(g,k)),h.lazyAssign(h.computedMember(g,k),"{}")),m=h.computedMember(g,k),h.assign(b, +m),d&&(d.computed=!0,d.name=k)):(e&&1!==e&&h.if_(h.isNull(h.nonComputedMember(g,a.property.name)),h.lazyAssign(h.nonComputedMember(g,a.property.name),"{}")),m=h.nonComputedMember(g,a.property.name),h.assign(b,m),d&&(d.computed=!1,d.name=a.property.name))},function(){h.assign(b,"undefined")});c(b)},!!e);break;case q.CallExpression:b=b||this.nextId();a.filter?(k=h.filter(a.callee.name),l=[],r(a.arguments,function(a){var b=h.nextId();h.recurse(a,b);l.push(b)}),m=k+"("+l.join(",")+")",h.assign(b,m),c(b)): +(k=h.nextId(),g={},l=[],h.recurse(a.callee,k,g,function(){h.if_(h.notNull(k),function(){r(a.arguments,function(b){h.recurse(b,a.constant?void 0:h.nextId(),void 0,function(a){l.push(a)})});m=g.name?h.member(g.context,g.name,g.computed)+"("+l.join(",")+")":k+"("+l.join(",")+")";h.assign(b,m)},function(){h.assign(b,"undefined")});c(b)}));break;case q.AssignmentExpression:k=this.nextId();g={};this.recurse(a.left,void 0,g,function(){h.if_(h.notNull(g.context),function(){h.recurse(a.right,k);m=h.member(g.context, +g.name,g.computed)+a.operator+k;h.assign(b,m);c(b||m)})},1);break;case q.ArrayExpression:l=[];r(a.elements,function(b){h.recurse(b,a.constant?void 0:h.nextId(),void 0,function(a){l.push(a)})});m="["+l.join(",")+"]";this.assign(b,m);c(b||m);break;case q.ObjectExpression:l=[];p=!1;r(a.properties,function(a){a.computed&&(p=!0)});p?(b=b||this.nextId(),this.assign(b,"{}"),r(a.properties,function(a){a.computed?(g=h.nextId(),h.recurse(a.key,g)):g=a.key.type===q.Identifier?a.key.name:""+a.key.value;k=h.nextId(); +h.recurse(a.value,k);h.assign(h.member(b,g,a.computed),k)})):(r(a.properties,function(b){h.recurse(b.value,a.constant?void 0:h.nextId(),void 0,function(a){l.push(h.escape(b.key.type===q.Identifier?b.key.name:""+b.key.value)+":"+a)})}),m="{"+l.join(",")+"}",this.assign(b,m));c(b||m);break;case q.ThisExpression:this.assign(b,"s");c(b||"s");break;case q.LocalsExpression:this.assign(b,"l");c(b||"l");break;case q.NGValueParameter:this.assign(b,"v"),c(b||"v")}},getHasOwnProperty:function(a,b){var d=a+"."+ +b,c=this.current().own;c.hasOwnProperty(d)||(c[d]=this.nextId(!1,a+"&&("+this.escape(b)+" in "+a+")"));return c[d]},assign:function(a,b){if(a)return this.current().body.push(a,"=",b,";"),a},filter:function(a){this.state.filters.hasOwnProperty(a)||(this.state.filters[a]=this.nextId(!0));return this.state.filters[a]},ifDefined:function(a,b){return"ifDefined("+a+","+this.escape(b)+")"},plus:function(a,b){return"plus("+a+","+b+")"},return_:function(a){this.current().body.push("return ",a,";")},if_:function(a, +b,d){if(!0===a)b();else{var c=this.current().body;c.push("if(",a,"){");b();c.push("}");d&&(c.push("else{"),d(),c.push("}"))}},not:function(a){return"!("+a+")"},isNull:function(a){return a+"==null"},notNull:function(a){return a+"!=null"},nonComputedMember:function(a,b){var d=/[^$_a-zA-Z0-9]/g;return/^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(b)?a+"."+b:a+'["'+b.replace(d,this.stringEscapeFn)+'"]'},computedMember:function(a,b){return a+"["+b+"]"},member:function(a,b,d){return d?this.computedMember(a,b):this.nonComputedMember(a, +b)},getStringValue:function(a){this.assign(a,"getStringValue("+a+")")},lazyRecurse:function(a,b,d,c,e,f){var g=this;return function(){g.recurse(a,b,d,c,e,f)}},lazyAssign:function(a,b){var d=this;return function(){d.assign(a,b)}},stringEscapeRegex:/[^ a-zA-Z0-9]/g,stringEscapeFn:function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)},escape:function(a){if(C(a))return"'"+a.replace(this.stringEscapeRegex,this.stringEscapeFn)+"'";if(X(a))return a.toString();if(!0===a)return"true";if(!1=== +a)return"false";if(null===a)return"null";if("undefined"===typeof a)return"undefined";throw Ya("esc");},nextId:function(a,b){var d="v"+this.state.nextId++;a||this.current().vars.push(d+(b?"="+b:""));return d},current:function(){return this.state[this.state.computing]}};Md.prototype={compile:function(a){var b=this;Z(a,b.$filter);var d,c;if(d=Kd(a))c=this.recurse(d);d=Id(a.body);var e;d&&(e=[],r(d,function(a,c){var d=b.recurse(a);d.isPure=a.isPure;a.input=d;e.push(d);a.watchId=c}));var f=[];r(a.body, +function(a){f.push(b.recurse(a.expression))});a=0===a.body.length?E:1===a.body.length?f[0]:function(a,b){var c;r(f,function(d){c=d(a,b)});return c};c&&(a.assign=function(a,b,d){return c(a,d,b)});e&&(a.inputs=e);return a},recurse:function(a,b,d){var c,e,f=this,g;if(a.input)return this.inputs(a.input,a.watchId);switch(a.type){case q.Literal:return this.value(a.value,b);case q.UnaryExpression:return e=this.recurse(a.argument),this["unary"+a.operator](e,b);case q.BinaryExpression:return c=this.recurse(a.left), +e=this.recurse(a.right),this["binary"+a.operator](c,e,b);case q.LogicalExpression:return c=this.recurse(a.left),e=this.recurse(a.right),this["binary"+a.operator](c,e,b);case q.ConditionalExpression:return this["ternary?:"](this.recurse(a.test),this.recurse(a.alternate),this.recurse(a.consequent),b);case q.Identifier:return f.identifier(a.name,b,d);case q.MemberExpression:return c=this.recurse(a.object,!1,!!d),a.computed||(e=a.property.name),a.computed&&(e=this.recurse(a.property)),a.computed?this.computedMember(c, +e,b,d):this.nonComputedMember(c,e,b,d);case q.CallExpression:return g=[],r(a.arguments,function(a){g.push(f.recurse(a))}),a.filter&&(e=this.$filter(a.callee.name)),a.filter||(e=this.recurse(a.callee,!0)),a.filter?function(a,c,d,f){for(var p=[],n=0;n":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)>b(c,e,f,g);return d?{value:c}:c}},"binary<=":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)<=b(c,e,f,g);return d?{value:c}:c}},"binary>=":function(a,b,d){return function(c,e,f,g){c= +a(c,e,f,g)>=b(c,e,f,g);return d?{value:c}:c}},"binary&&":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)&&b(c,e,f,g);return d?{value:c}:c}},"binary||":function(a,b,d){return function(c,e,f,g){c=a(c,e,f,g)||b(c,e,f,g);return d?{value:c}:c}},"ternary?:":function(a,b,d,c){return function(e,f,g,k){e=a(e,f,g,k)?b(e,f,g,k):d(e,f,g,k);return c?{value:e}:e}},value:function(a,b){return function(){return b?{context:void 0,name:void 0,value:a}:a}},identifier:function(a,b,d){return function(c,e,f,g){c= +e&&a in e?e:c;d&&1!==d&&c&&null==c[a]&&(c[a]={});e=c?c[a]:void 0;return b?{context:c,name:a,value:e}:e}},computedMember:function(a,b,d,c){return function(e,f,g,k){var h=a(e,f,g,k),l,m;null!=h&&(l=b(e,f,g,k),l+="",c&&1!==c&&h&&!h[l]&&(h[l]={}),m=h[l]);return d?{context:h,name:l,value:m}:m}},nonComputedMember:function(a,b,d,c){return function(e,f,g,k){e=a(e,f,g,k);c&&1!==c&&e&&null==e[b]&&(e[b]={});f=null!=e?e[b]:void 0;return d?{context:e,name:b,value:f}:f}},inputs:function(a,b){return function(d, +c,e,f){return f?f[b]:a(d,c,e)}}};Nb.prototype={constructor:Nb,parse:function(a){a=this.getAst(a);var b=this.astCompiler.compile(a.ast),d=a.ast;b.literal=0===d.body.length||1===d.body.length&&(d.body[0].expression.type===q.Literal||d.body[0].expression.type===q.ArrayExpression||d.body[0].expression.type===q.ObjectExpression);b.constant=a.ast.constant;b.oneTime=a.oneTime;return b},getAst:function(a){var b=!1;a=a.trim();":"===a.charAt(0)&&":"===a.charAt(1)&&(b=!0,a=a.substring(2));return{ast:this.ast.ast(a), +oneTime:b}}};var Ea=F("$sce"),W={HTML:"html",CSS:"css",MEDIA_URL:"mediaUrl",URL:"url",RESOURCE_URL:"resourceUrl",JS:"js"},Dc=/_([a-z])/g,Zg=F("$templateRequest"),$g=F("$timeout"),aa=z.document.createElement("a"),Qd=ga(z.location.href),Na;aa.href="http://[::1]";var ah="[::1]"===aa.hostname;Rd.$inject=["$document"];fd.$inject=["$provide"];var Yd=22,Xd=".",Fc="0";Sd.$inject=["$locale"];Ud.$inject=["$locale"];var lh={yyyy:ea("FullYear",4,0,!1,!0),yy:ea("FullYear",2,0,!0,!0),y:ea("FullYear",1,0,!1,!0), +MMMM:lb("Month"),MMM:lb("Month",!0),MM:ea("Month",2,1),M:ea("Month",1,1),LLLL:lb("Month",!1,!0),dd:ea("Date",2),d:ea("Date",1),HH:ea("Hours",2),H:ea("Hours",1),hh:ea("Hours",2,-12),h:ea("Hours",1,-12),mm:ea("Minutes",2),m:ea("Minutes",1),ss:ea("Seconds",2),s:ea("Seconds",1),sss:ea("Milliseconds",3),EEEE:lb("Day"),EEE:lb("Day",!0),a:function(a,b){return 12>a.getHours()?b.AMPMS[0]:b.AMPMS[1]},Z:function(a,b,d){a=-1*d;return a=(0<=a?"+":"")+(Pb(Math[0=a.getFullYear()?b.ERANAMES[0]:b.ERANAMES[1]}},kh=/((?:[^yMLdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|L+|d+|H+|h+|m+|s+|a|Z|G+|w+))([\s\S]*)/,jh=/^-?\d+$/;Td.$inject=["$locale"];var eh=ia(K),fh=ia(vb);Vd.$inject=["$parse"];var Re=ia({restrict:"E",compile:function(a,b){if(!b.href&&!b.xlinkHref)return function(a,b){if("a"===b[0].nodeName.toLowerCase()){var e="[object SVGAnimatedString]"===la.call(b.prop("href"))?"xlink:href":"href"; +b.on("click",function(a){b.attr(e)||a.preventDefault()})}}}}),wb={};r(Hb,function(a,b){function d(a,d,e){a.$watch(e[c],function(a){e.$set(b,!!a)})}if("multiple"!==a){var c=xa("ng-"+b),e=d;"checked"===a&&(e=function(a,b,e){e.ngModel!==e[c]&&d(a,b,e)});wb[c]=function(){return{restrict:"A",priority:100,link:e}}}});r(vd,function(a,b){wb[b]=function(){return{priority:100,link:function(a,c,e){if("ngPattern"===b&&"/"===e.ngPattern.charAt(0)&&(c=e.ngPattern.match(ke))){e.$set("ngPattern",new RegExp(c[1], +c[2]));return}a.$watch(e[b],function(a){e.$set(b,a)})}}}});r(["src","srcset","href"],function(a){var b=xa("ng-"+a);wb[b]=["$sce",function(d){return{priority:99,link:function(c,e,f){var g=a,k=a;"href"===a&&"[object SVGAnimatedString]"===la.call(e.prop("href"))&&(k="xlinkHref",f.$attr[k]="xlink:href",g=null);f.$set(b,d.getTrustedMediaUrl(f[b]));f.$observe(b,function(b){b?(f.$set(k,b),wa&&g&&e.prop(g,f[k])):"href"===a&&f.$set(k,null)})}}}]});var mb={$addControl:E,$getControls:ia([]),$$renameControl:function(a, +b){a.$name=b},$removeControl:E,$setValidity:E,$setDirty:E,$setPristine:E,$setSubmitted:E,$$setSubmitted:E};Qb.$inject=["$element","$attrs","$scope","$animate","$interpolate"];Qb.prototype={$rollbackViewValue:function(){r(this.$$controls,function(a){a.$rollbackViewValue()})},$commitViewValue:function(){r(this.$$controls,function(a){a.$commitViewValue()})},$addControl:function(a){Ja(a.$name,"input");this.$$controls.push(a);a.$name&&(this[a.$name]=a);a.$$parentForm=this},$getControls:function(){return ja(this.$$controls)}, +$$renameControl:function(a,b){var d=a.$name;this[d]===a&&delete this[d];this[b]=a;a.$name=b},$removeControl:function(a){a.$name&&this[a.$name]===a&&delete this[a.$name];r(this.$pending,function(b,d){this.$setValidity(d,null,a)},this);r(this.$error,function(b,d){this.$setValidity(d,null,a)},this);r(this.$$success,function(b,d){this.$setValidity(d,null,a)},this);cb(this.$$controls,a);a.$$parentForm=mb},$setDirty:function(){this.$$animate.removeClass(this.$$element,Za);this.$$animate.addClass(this.$$element, +Wb);this.$dirty=!0;this.$pristine=!1;this.$$parentForm.$setDirty()},$setPristine:function(){this.$$animate.setClass(this.$$element,Za,Wb+" ng-submitted");this.$dirty=!1;this.$pristine=!0;this.$submitted=!1;r(this.$$controls,function(a){a.$setPristine()})},$setUntouched:function(){r(this.$$controls,function(a){a.$setUntouched()})},$setSubmitted:function(){for(var a=this;a.$$parentForm&&a.$$parentForm!==mb;)a=a.$$parentForm;a.$$setSubmitted()},$$setSubmitted:function(){this.$$animate.addClass(this.$$element, +"ng-submitted");this.$submitted=!0;r(this.$$controls,function(a){a.$$setSubmitted&&a.$$setSubmitted()})}};ce({clazz:Qb,set:function(a,b,d){var c=a[b];c?-1===c.indexOf(d)&&c.push(d):a[b]=[d]},unset:function(a,b,d){var c=a[b];c&&(cb(c,d),0===c.length&&delete a[b])}});var oe=function(a){return["$timeout","$parse",function(b,d){function c(a){return""===a?d('this[""]').assign:d(a).assign||E}return{name:"form",restrict:a?"EAC":"E",require:["form","^^?form"],controller:Qb,compile:function(d,f){d.addClass(Za).addClass(nb); +var g=f.name?"name":a&&f.ngForm?"ngForm":!1;return{pre:function(a,d,e,f){var p=f[0];if(!("action"in e)){var n=function(b){a.$apply(function(){p.$commitViewValue();p.$setSubmitted()});b.preventDefault()};d[0].addEventListener("submit",n);d.on("$destroy",function(){b(function(){d[0].removeEventListener("submit",n)},0,!1)})}(f[1]||p.$$parentForm).$addControl(p);var s=g?c(p.$name):E;g&&(s(a,p),e.$observe(g,function(b){p.$name!==b&&(s(a,void 0),p.$$parentForm.$$renameControl(p,b),s=c(p.$name),s(a,p))})); +d.on("$destroy",function(){p.$$parentForm.$removeControl(p);s(a,void 0);S(p,mb)})}}}}}]},Se=oe(),df=oe(!0),mh=/^\d{4,}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+(?:[+-][0-2]\d:[0-5]\d|Z)$/,xh=/^[a-z][a-z\d.+-]*:\/*(?:[^:@]+(?::[^@]+)?@)?(?:[^\s:/?#]+|\[[a-f\d:]+])(?::\d+)?(?:\/[^?#]*)?(?:\?[^#]*)?(?:#.*)?$/i,yh=/^(?=.{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])?)*$/, +nh=/^\s*(-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/,pe=/^(\d{4,})-(\d{2})-(\d{2})$/,qe=/^(\d{4,})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,Oc=/^(\d{4,})-W(\d\d)$/,re=/^(\d{4,})-(\d\d)$/,se=/^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/,ee=T();r(["date","datetime-local","month","time","week"],function(a){ee[a]=!0});var te={text:function(a,b,d,c,e,f){Sa(a,b,d,c,e,f);Ic(c)},date:ob("date",pe,Rb(pe,["yyyy","MM","dd"]),"yyyy-MM-dd"),"datetime-local":ob("datetimelocal",qe,Rb(qe,"yyyy MM dd HH mm ss sss".split(" ")), +"yyyy-MM-ddTHH:mm:ss.sss"),time:ob("time",se,Rb(se,["HH","mm","ss","sss"]),"HH:mm:ss.sss"),week:ob("week",Oc,function(a,b){if(ha(a))return a;if(C(a)){Oc.lastIndex=0;var d=Oc.exec(a);if(d){var c=+d[1],e=+d[2],f=d=0,g=0,k=0,h=Zd(c),e=7*(e-1);b&&(d=b.getHours(),f=b.getMinutes(),g=b.getSeconds(),k=b.getMilliseconds());return new Date(c,0,h.getDate()+e,d,f,g,k)}}return NaN},"yyyy-Www"),month:ob("month",re,Rb(re,["yyyy","MM"]),"yyyy-MM"),number:function(a,b,d,c,e,f,g,k){Jc(a,b,d,c,"number");fe(c);Sa(a, +b,d,c,e,f);var h;if(w(d.min)||d.ngMin){var l=d.min||k(d.ngMin)(a);h=na(l);c.$validators.min=function(a,b){return c.$isEmpty(b)||A(h)||b>=h};d.$observe("min",function(a){a!==l&&(h=na(a),l=a,c.$validate())})}if(w(d.max)||d.ngMax){var m=d.max||k(d.ngMax)(a),p=na(m);c.$validators.max=function(a,b){return c.$isEmpty(b)||A(p)||b<=p};d.$observe("max",function(a){a!==m&&(p=na(a),m=a,c.$validate())})}if(w(d.step)||d.ngStep){var n=d.step||k(d.ngStep)(a),s=na(n);c.$validators.step=function(a,b){return c.$isEmpty(b)|| +A(s)||ge(b,h||0,s)};d.$observe("step",function(a){a!==n&&(s=na(a),n=a,c.$validate())})}},url:function(a,b,d,c,e,f){Sa(a,b,d,c,e,f);Ic(c);c.$validators.url=function(a,b){var d=a||b;return c.$isEmpty(d)||xh.test(d)}},email:function(a,b,d,c,e,f){Sa(a,b,d,c,e,f);Ic(c);c.$validators.email=function(a,b){var d=a||b;return c.$isEmpty(d)||yh.test(d)}},radio:function(a,b,d,c){var e=!d.ngTrim||"false"!==V(d.ngTrim);A(d.name)&&b.attr("name",++qb);b.on("change",function(a){var g;b[0].checked&&(g=d.value,e&&(g= +V(g)),c.$setViewValue(g,a&&a.type))});c.$render=function(){var a=d.value;e&&(a=V(a));b[0].checked=a===c.$viewValue};d.$observe("value",c.$render)},range:function(a,b,d,c,e,f){function g(a,c){b.attr(a,d[a]);var e=d[a];d.$observe(a,function(a){a!==e&&(e=a,c(a))})}function k(a){p=na(a);Y(c.$modelValue)||(m?(a=b.val(),p>a&&(a=p,b.val(a)),c.$setViewValue(a)):c.$validate())}function h(a){n=na(a);Y(c.$modelValue)||(m?(a=b.val(),n=p},g("min",k)); +e&&(n=na(d.max),c.$validators.max=m?function(){return!0}:function(a,b){return c.$isEmpty(b)||A(n)||b<=n},g("max",h));f&&(s=na(d.step),c.$validators.step=m?function(){return!r.stepMismatch}:function(a,b){return c.$isEmpty(b)||A(s)||ge(b,p||0,s)},g("step",l))},checkbox:function(a,b,d,c,e,f,g,k){var h=he(k,a,"ngTrueValue",d.ngTrueValue,!0),l=he(k,a,"ngFalseValue",d.ngFalseValue,!1);b.on("change",function(a){c.$setViewValue(b[0].checked,a&&a.type)});c.$render=function(){b[0].checked=c.$viewValue};c.$isEmpty= +function(a){return!1===a};c.$formatters.push(function(a){return va(a,h)});c.$parsers.push(function(a){return a?h:l})},hidden:E,button:E,submit:E,reset:E,file:E},$c=["$browser","$sniffer","$filter","$parse",function(a,b,d,c){return{restrict:"E",require:["?ngModel"],link:{pre:function(e,f,g,k){k[0]&&(te[K(g.type)]||te.text)(e,f,g,k[0],b,a,d,c)}}}}],Af=function(){var a={configurable:!0,enumerable:!1,get:function(){return this.getAttribute("value")||""},set:function(a){this.setAttribute("value",a)}}; +return{restrict:"E",priority:200,compile:function(b,d){if("hidden"===K(d.type))return{pre:function(b,d,f,g){b=d[0];b.parentNode&&b.parentNode.insertBefore(b,b.nextSibling);Object.defineProperty&&Object.defineProperty(b,"value",a)}}}}},zh=/^(true|false|\d+)$/,xf=function(){function a(a,d,c){var e=w(c)?c:9===wa?"":null;a.prop("value",e);d.$set("value",c)}return{restrict:"A",priority:100,compile:function(b,d){return zh.test(d.ngValue)?function(b,d,f){b=b.$eval(f.ngValue);a(d,f,b)}:function(b,d,f){b.$watch(f.ngValue, +function(b){a(d,f,b)})}}}},We=["$compile",function(a){return{restrict:"AC",compile:function(b){a.$$addBindingClass(b);return function(b,c,e){a.$$addBindingInfo(c,e.ngBind);c=c[0];b.$watch(e.ngBind,function(a){c.textContent=jc(a)})}}}}],Ye=["$interpolate","$compile",function(a,b){return{compile:function(d){b.$$addBindingClass(d);return function(c,d,f){c=a(d.attr(f.$attr.ngBindTemplate));b.$$addBindingInfo(d,c.expressions);d=d[0];f.$observe("ngBindTemplate",function(a){d.textContent=A(a)?"":a})}}}}], +Xe=["$sce","$parse","$compile",function(a,b,d){return{restrict:"A",compile:function(c,e){var f=b(e.ngBindHtml),g=b(e.ngBindHtml,function(b){return a.valueOf(b)});d.$$addBindingClass(c);return function(b,c,e){d.$$addBindingInfo(c,e.ngBindHtml);b.$watch(g,function(){var d=f(b);c.html(a.getTrustedHtml(d)||"")})}}}}],wf=ia({restrict:"A",require:"ngModel",link:function(a,b,d,c){c.$viewChangeListeners.push(function(){a.$eval(d.ngChange)})}}),Ze=Lc("",!0),af=Lc("Odd",0),$e=Lc("Even",1),bf=Ra({compile:function(a, +b){b.$set("ngCloak",void 0);a.removeClass("ng-cloak")}}),cf=[function(){return{restrict:"A",scope:!0,controller:"@",priority:500}}],ed={},Ah={blur:!0,focus:!0};r("click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste".split(" "),function(a){var b=xa("ng-"+a);ed[b]=["$parse","$rootScope","$exceptionHandler",function(d,c,e){return sd(d,c,e,b,a,Ah[a])}]});var ff=["$animate","$compile",function(a,b){return{multiElement:!0, +transclude:"element",priority:600,terminal:!0,restrict:"A",$$tlb:!0,link:function(d,c,e,f,g){var k,h,l;d.$watch(e.ngIf,function(d){d?h||g(function(d,f){h=f;d[d.length++]=b.$$createComment("end ngIf",e.ngIf);k={clone:d};a.enter(d,c.parent(),c)}):(l&&(l.remove(),l=null),h&&(h.$destroy(),h=null),k&&(l=ub(k.clone),a.leave(l).done(function(a){!1!==a&&(l=null)}),k=null))})}}}],gf=["$templateRequest","$anchorScroll","$animate",function(a,b,d){return{restrict:"ECA",priority:400,terminal:!0,transclude:"element", +controller:ca.noop,compile:function(c,e){var f=e.ngInclude||e.src,g=e.onload||"",k=e.autoscroll;return function(c,e,m,p,n){var r=0,q,t,x,v=function(){t&&(t.remove(),t=null);q&&(q.$destroy(),q=null);x&&(d.leave(x).done(function(a){!1!==a&&(t=null)}),t=x,x=null)};c.$watch(f,function(f){var m=function(a){!1===a||!w(k)||k&&!c.$eval(k)||b()},t=++r;f?(a(f,!0).then(function(a){if(!c.$$destroyed&&t===r){var b=c.$new();p.template=a;a=n(b,function(a){v();d.enter(a,null,e).done(m)});q=b;x=a;q.$emit("$includeContentLoaded", +f);c.$eval(g)}},function(){c.$$destroyed||t!==r||(v(),c.$emit("$includeContentError",f))}),c.$emit("$includeContentRequested",f)):(v(),p.template=null)})}}}}],zf=["$compile",function(a){return{restrict:"ECA",priority:-400,require:"ngInclude",link:function(b,d,c,e){la.call(d[0]).match(/SVG/)?(d.empty(),a(gd(e.template,z.document).childNodes)(b,function(a){d.append(a)},{futureParentElement:d})):(d.html(e.template),a(d.contents())(b))}}}],hf=Ra({priority:450,compile:function(){return{pre:function(a, +b,d){a.$eval(d.ngInit)}}}}),vf=function(){return{restrict:"A",priority:100,require:"ngModel",link:function(a,b,d,c){var e=d.ngList||", ",f="false"!==d.ngTrim,g=f?V(e):e;c.$parsers.push(function(a){if(!A(a)){var b=[];a&&r(a.split(g),function(a){a&&b.push(f?V(a):a)});return b}});c.$formatters.push(function(a){if(H(a))return a.join(e)});c.$isEmpty=function(a){return!a||!a.length}}}},nb="ng-valid",be="ng-invalid",Za="ng-pristine",Wb="ng-dirty",pb=F("ngModel");Sb.$inject="$scope $exceptionHandler $attrs $element $parse $animate $timeout $q $interpolate".split(" "); +Sb.prototype={$$initGetterSetters:function(){if(this.$options.getOption("getterSetter")){var a=this.$$parse(this.$$attr.ngModel+"()"),b=this.$$parse(this.$$attr.ngModel+"($$$p)");this.$$ngModelGet=function(b){var c=this.$$parsedNgModel(b);B(c)&&(c=a(b));return c};this.$$ngModelSet=function(a,c){B(this.$$parsedNgModel(a))?b(a,{$$$p:c}):this.$$parsedNgModelAssign(a,c)}}else if(!this.$$parsedNgModel.assign)throw pb("nonassign",this.$$attr.ngModel,Aa(this.$$element));},$render:E,$isEmpty:function(a){return A(a)|| +""===a||null===a||a!==a},$$updateEmptyClasses:function(a){this.$isEmpty(a)?(this.$$animate.removeClass(this.$$element,"ng-not-empty"),this.$$animate.addClass(this.$$element,"ng-empty")):(this.$$animate.removeClass(this.$$element,"ng-empty"),this.$$animate.addClass(this.$$element,"ng-not-empty"))},$setPristine:function(){this.$dirty=!1;this.$pristine=!0;this.$$animate.removeClass(this.$$element,Wb);this.$$animate.addClass(this.$$element,Za)},$setDirty:function(){this.$dirty=!0;this.$pristine=!1;this.$$animate.removeClass(this.$$element, +Za);this.$$animate.addClass(this.$$element,Wb);this.$$parentForm.$setDirty()},$setUntouched:function(){this.$touched=!1;this.$untouched=!0;this.$$animate.setClass(this.$$element,"ng-untouched","ng-touched")},$setTouched:function(){this.$touched=!0;this.$untouched=!1;this.$$animate.setClass(this.$$element,"ng-touched","ng-untouched")},$rollbackViewValue:function(){this.$$timeout.cancel(this.$$pendingDebounce);this.$viewValue=this.$$lastCommittedViewValue;this.$render()},$validate:function(){if(!Y(this.$modelValue)){var a= +this.$$lastCommittedViewValue,b=this.$$rawModelValue,d=this.$valid,c=this.$modelValue,e=this.$options.getOption("allowInvalid"),f=this;this.$$runValidators(b,a,function(a){e||d===a||(f.$modelValue=a?b:void 0,f.$modelValue!==c&&f.$$writeModelToScope())})}},$$runValidators:function(a,b,d){function c(){var c=!0;r(h.$validators,function(d,e){var g=Boolean(d(a,b));c=c&&g;f(e,g)});return c?!0:(r(h.$asyncValidators,function(a,b){f(b,null)}),!1)}function e(){var c=[],d=!0;r(h.$asyncValidators,function(e, +g){var h=e(a,b);if(!h||!B(h.then))throw pb("nopromise",h);f(g,void 0);c.push(h.then(function(){f(g,!0)},function(){d=!1;f(g,!1)}))});c.length?h.$$q.all(c).then(function(){g(d)},E):g(!0)}function f(a,b){k===h.$$currentValidationRunId&&h.$setValidity(a,b)}function g(a){k===h.$$currentValidationRunId&&d(a)}this.$$currentValidationRunId++;var k=this.$$currentValidationRunId,h=this;(function(){var a=h.$$parserName;if(A(h.$$parserValid))f(a,null);else return h.$$parserValid||(r(h.$validators,function(a, +b){f(b,null)}),r(h.$asyncValidators,function(a,b){f(b,null)})),f(a,h.$$parserValid),h.$$parserValid;return!0})()?c()?e():g(!1):g(!1)},$commitViewValue:function(){var a=this.$viewValue;this.$$timeout.cancel(this.$$pendingDebounce);if(this.$$lastCommittedViewValue!==a||""===a&&this.$$hasNativeValidators)this.$$updateEmptyClasses(a),this.$$lastCommittedViewValue=a,this.$pristine&&this.$setDirty(),this.$$parseAndValidate()},$$parseAndValidate:function(){var a=this.$$lastCommittedViewValue,b=this;this.$$parserValid= +A(a)?void 0:!0;this.$setValidity(this.$$parserName,null);this.$$parserName="parse";if(this.$$parserValid)for(var d=0;dg||e.$isEmpty(b)||b.length<=g}}}}}],cd= +["$parse",function(a){return{restrict:"A",require:"?ngModel",link:function(b,d,c,e){if(e){var f=c.minlength||a(c.ngMinlength)(b),g=Ub(f)||-1;c.$observe("minlength",function(a){f!==a&&(g=Ub(a)||-1,f=a,e.$validate())});e.$validators.minlength=function(a,b){return e.$isEmpty(b)||b.length>=g}}}}}];z.angular.bootstrap?z.console&&console.log("WARNING: Tried to load AngularJS more than once."):(Je(),Oe(ca),ca.module("ngLocale",[],["$provide",function(a){function b(a){a+="";var b=a.indexOf(".");return-1== +b?0:a.length-b-1}a.value("$locale",{DATETIME_FORMATS:{AMPMS:["AM","PM"],DAY:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),ERANAMES:["Before Christ","Anno Domini"],ERAS:["BC","AD"],FIRSTDAYOFWEEK:6,MONTH:"January February March April May June July August September October November December".split(" "),SHORTDAY:"Sun Mon Tue Wed Thu Fri Sat".split(" "),SHORTMONTH:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),STANDALONEMONTH:"January February March April May June July August September October November December".split(" "), +WEEKENDRANGE:[5,6],fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",medium:"MMM d, y h:mm:ss a",mediumDate:"MMM d, y",mediumTime:"h:mm:ss a","short":"M/d/yy h:mm a",shortDate:"M/d/yy",shortTime:"h:mm a"},NUMBER_FORMATS:{CURRENCY_SYM:"$",DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"-\u00a4",negSuf:"",posPre:"\u00a4",posSuf:""}]},id:"en-us",localeID:"en_US",pluralCat:function(a, +c){var e=a|0,f=c;void 0===f&&(f=Math.min(b(a),3));Math.pow(10,f);return 1==e&&0==f?"one":"other"}})}]),x(function(){Ee(z.document,Wc)}))})(window);!window.angular.$$csp().noInlineStyle&&window.angular.element(document.head).prepend(window.angular.element("'),angular.$$uibCarouselCss=!0}),angular.module("ui.bootstrap.position").run(function(){!angular.$$csp().noInlineStyle&&!angular.$$uibPositionCss&&angular.element(document).find("head").prepend(''),angular.$$uibPositionCss=!0}),angular.module("ui.bootstrap.datepicker").run(function(){!angular.$$csp().noInlineStyle&&!angular.$$uibDatepickerCss&&angular.element(document).find("head").prepend(''),angular.$$uibDatepickerCss=!0}),angular.module("ui.bootstrap.tooltip").run(function(){!angular.$$csp().noInlineStyle&&!angular.$$uibTooltipCss&&angular.element(document).find("head").prepend(''),angular.$$uibTooltipCss=!0}),angular.module("ui.bootstrap.timepicker").run(function(){!angular.$$csp().noInlineStyle&&!angular.$$uibTimepickerCss&&angular.element(document).find("head").prepend(''),angular.$$uibTimepickerCss=!0}),angular.module("ui.bootstrap.typeahead").run(function(){!angular.$$csp().noInlineStyle&&!angular.$$uibTypeaheadCss&&angular.element(document).find("head").prepend(''),angular.$$uibTypeaheadCss=!0}); \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/designer.js b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/designer.js index 267ecbfdd..e0f3d4f6a 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/designer.js +++ b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/designer.js @@ -1,7 +1,7 @@ - -(function ($) { +(function ($) { if (typeof ($telerik) != 'undefined') { $telerik.$(document).one('dialogRendered', function () { + angular.$$csp().noInlineStyle = true; angular.bootstrap($('.designer'), ['designer']); }); } @@ -20,7 +20,12 @@ var resolveTemplateUrl = function (view, serverData) { var widgetName = serverData.get('widgetName'); - var templatePath = String.format('Telerik.Sitefinity.Frontend/Designer/View/{0}/{1}?controlId={2}', widgetName, view, serverData.get('controlId')); + var templatePath = String.format('Telerik.Sitefinity.Frontend/Designer/View/{0}/{1}?controlId={2}&mediaType={3}', widgetName, view, serverData.get('controlId'), serverData.get("mediaType")); + + var moduleName = serverData.get('moduleName'); + if (moduleName) { + templatePath = String.format('{0}&moduleName={1}', templatePath, moduleName); + } return sitefinity.getRootedUrl(sitefinity.appendPackageParameter(templatePath)); }; @@ -45,14 +50,23 @@ redirectTo: '/' + resolveDefaultView(serverData) }); - $httpProvider.interceptors.push(function () { + $httpProvider.interceptors.push(function ($q, $window) { return { 'request': function (config) { if (config && config.method === 'GET' && config.headers && config.headers.SF_UI_CULTURE === undefined && config.url && endsWith(config.url, '.sf-cshtml')) { config.headers.SF_UI_CULTURE = serverData.get('culture'); } + config.headers['X-Requested-With'] = 'XMLHttpRequest'; return config; + }, + 'responseError': function (rejection) { + if (rejection.status === 401 || rejection.status === 403) { + rejection.data = rejection.statusText; + $window.onbeforeunload = null; + $window.location.reload(); + } + return $q.reject(rejection); } }; }); @@ -92,8 +106,14 @@ restrict: 'AC', link: function (scope, element, attr) { var placeholder = $('[placeholder="' + attr.section + '"]'); + var selectedScope; + if (attr.useElementScope === 'true') { + selectedScope = scope; + } else { + selectedScope = angular.element('.modal-body').scope(); + } if (placeholder.length > 0) { - placeholder.html($compile(element.html())(scope)); + placeholder.html($compile(element.html())(selectedScope)); } } }; @@ -115,32 +135,32 @@ propertyService.get() .then(function (data) { - if (data) { + if (data && data.Items) { $scope.properties = propertyService.toAssociativeArray(data.Items); } - }, - function (data) { - $scope.feedback.showError = true; - if (data) - $scope.feedback.errorMessage = data.Detail; - }) + }, + function (errorData) { + $scope.feedback.showError = true; + if (errorData && errorData.data) + $scope.feedback.errorMessage = errorData.data.Detail; + }) .finally(function () { $scope.feedback.showLoadingIndicator = false; }); }]); - designerModule.controller('DialogCtrl', ['$rootScope', '$scope', '$q', '$modalInstance', '$route', 'propertyService', 'widgetContext', - function ($rootScope, $scope, $q, $modalInstance, $route, propertyService, widgetContext) { + designerModule.controller('DialogCtrl', ['$rootScope', '$scope', '$q', '$uibModalInstance', '$route', 'propertyService', 'widgetContext', + function ($rootScope, $scope, $q, $uibModalInstance, $route, propertyService, widgetContext) { var isSaveToAllTranslations = true; // ------------------------------------------------------------------------ // Event handlers // ------------------------------------------------------------------------ - var onError = function (data) { + var onError = function (errorData) { $scope.feedback.showError = true; - if (data) - $scope.feedback.errorMessage = data.Detail ? data.Detail : data; + if (errorData && errorData.data) + $scope.feedback.errorMessage = errorData.data.Detail ? errorData.data.Detail : errorData.data; }; // ------------------------------------------------------------------------ @@ -183,6 +203,16 @@ $scope.feedback.showLoadingIndicator = true; $scope.feedback.showError = false; + var escKeyListener = function (event) { + if (event.key === "Escape") { + $scope.$apply($scope.cancel); + } + }; + + document.addEventListener('keydown', escKeyListener); + $scope.$on('$destroy', function () { + document.removeEventListener('keydown', escKeyListener); + }); //the save action - it will check which properties are changed and send only them to the server $scope.save = function (saveToAllTranslations) { @@ -221,11 +251,18 @@ $scope.close = function () { try { - $modalInstance.close(); + $uibModalInstance.close(); } catch (e) { } - if (typeof ($telerik) != 'undefined') + if (typeof ($telerik) !== 'undefined') $telerik.$(document).trigger('modalDialogClosed'); + + if (typeof CustomEvent == "function") { + var evt = new CustomEvent('sfModalDialogClosed'); + document.dispatchEvent(evt); + } + + $rootScope.$destroy(); }; $scope.hideSaveAllTranslations = widgetContext.hideSaveAllTranslations; @@ -233,7 +270,7 @@ $scope.isCurrentView = function (view) { return $route.current && $route.current.params.view === view; }; - + $scope.hideError = function () { $scope.feedback.showError = false; $scope.feedback.errorMessage = null; @@ -242,4 +279,4 @@ propertyService.get().catch(onError); } ]); -})(jQuery); \ No newline at end of file +})(jQuery); diff --git a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/designerview-propertygrid.js b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/designerview-propertygrid.js index 9f3ef463c..b33b1d174 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/designerview-propertygrid.js +++ b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/designerview-propertygrid.js @@ -7,14 +7,14 @@ function ($scope, propertyService) { var onGetPropertiesSuccess = function (data) { - if (data.Items) + if (data && data.Items) $scope.items = data.Items; }; - var onGetError = function (data) { + var onGetError = function (errorData) { $scope.feedback.showError = true; - if (data) - $scope.feedback.errorMessage = data.Detail; + if (errorData && errorData.data) + $scope.feedback.errorMessage = errorData.data.Detail; }; propertyService.get().then(onGetPropertiesSuccess, onGetError) @@ -28,6 +28,10 @@ $scope.propertyPath = propertyPath; $scope.propertyName = propertyName; }; + + $scope.isUndefined = function (value) { + return typeof value === 'undefined'; + }; }]); //filters property hierarchy @@ -40,6 +44,10 @@ var levelFilter = function (property) { var level = property.PropertyPath.split('/').length - 2; + if (currentLevel == 1 && property.PropertyName == 'FieldName' && property.PropertyPath.indexOf("MetaField") > -1) { + return true; + } + if (!propertyName || propertyName == 'Home') { return level <= currentLevel; } else { diff --git a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/grid-designer.js b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/grid-designer.js index be2fa47fd..8c3ef156f 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/grid-designer.js +++ b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/grid-designer.js @@ -12,17 +12,17 @@ var gridDesignerModule = angular.module('gridDesigner', ['pageEditorServices', 'modalDialog', 'serverDataModule']); - gridDesignerModule.controller('GridDialogCtrl', ['$rootScope', '$scope', '$q', '$modalInstance', 'serverData', 'gridService', - function ($rootScope, $scope, $q, $modalInstance, serverData, gridService) { + gridDesignerModule.controller('GridDialogCtrl', ['$rootScope', '$scope', '$q', '$uibModalInstance', 'serverData', 'gridService', + function ($rootScope, $scope, $q, $uibModalInstance, serverData, gridService) { // ------------------------------------------------------------------------ // Event handlers // ------------------------------------------------------------------------ - var onError = function (data) { + var onError = function (errorData) { $scope.feedback.showError = true; - if (data) - $scope.feedback.errorMessage = data.Detail ? data.Detail : data; + if (errorData && errorData.data) + $scope.feedback.errorMessage = errorData.data.Detail ? errorData.data.Detail : errorData.data; $scope.feedback.showLoadingIndicator = false; }; @@ -78,11 +78,16 @@ $scope.close = function () { try { - $modalInstance.close(); + $uibModalInstance.close(); } catch (e) { } if (typeof ($telerik) != 'undefined') $telerik.$(document).trigger('gridModalDialogClosed'); + + if (typeof CustomEvent == "function") { + var evt = new CustomEvent('sfModalDialogClosed'); + document.dispatchEvent(evt); + } }; $scope.hideError = function () { diff --git a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/modal-dialog.js b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/modal-dialog.js index f19fcca17..614fe2edd 100644 --- a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/modal-dialog.js +++ b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/modal-dialog.js @@ -27,7 +27,7 @@ }; }); - modalDialogModule.directive('modal', ['$modal', 'dialogsService', function ($modal, dialogsService) { + modalDialogModule.directive('modal', ['$uibModal', 'dialogsService', function ($uibModal, dialogsService) { var resolveControllerName = function (attrs) { if (!attrs.dialogController && !attrs.existingScope) { throw 'Please either insert an attribute named "dialog-controller" with the name of the controller for the modal dialog next to the "modal" directive ' + @@ -40,12 +40,12 @@ var modalDialogClass = 'modal-dialog-'; var backdropClass = 'div.modal-backdrop'; - var open = function (scope, attrs, resolve) { + var open = function (scope, attrs, resolve, onRenderedCb) { dialogsService.peek().hide(); var uniqueClass = modalDialogClass + dialogsService.count(); var windowClass = attrs.windowClass ? attrs.windowClass + ' ' + uniqueClass : uniqueClass; - var modalInstance = $modal.open({ + var modalInstance = $uibModal.open({ backdrop: 'static', scope: attrs.existingScope && scope, templateUrl: attrs.templateUrl, @@ -54,11 +54,18 @@ resolve: resolve }); - scope.$modalInstance = modalInstance; + scope.$uibModalInstance = modalInstance; dialogsService.pushSelector('.' + uniqueClass); - return scope.$modalInstance.result.finally(function () { + if (typeof onRenderedCb === 'function') { + scope.$uibModalInstance.rendered.then(function (res) { + onRenderedCb(res); + return res; + }); + } + + return scope.$uibModalInstance.result.finally(function () { dialogsService.pop().remove(); if (dialogsService.count() > 0) { @@ -67,6 +74,8 @@ else { $(backdropClass).remove(); } + }) + .catch(function () { }); }; @@ -77,8 +86,8 @@ open(scope, attrs); } else { - scope.$openModalDialog = function (resolve) { - return open(scope, attrs, resolve); + scope.$openModalDialog = function (resolve, onRenderedCb) { + return open(scope, attrs, resolve, onRenderedCb); }; } } diff --git a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/personalization-designer.js b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/personalization-designer.js new file mode 100644 index 000000000..8a69c656c --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Designer/personalization-designer.js @@ -0,0 +1,113 @@ + +(function ($) { + if (typeof ($telerik) != 'undefined') { + $telerik.$(document).one('dialogRendered', function () { + angular.bootstrap(document.querySelector('.personalization-designer'), ['personalizationDesigner']); + }); + } + + var endsWith = function (str, suffix) { + return str.indexOf(suffix, str.length - suffix.length) !== -1; + }; + + var personalizationDesignerModule = angular.module('personalizationDesigner', ['pageEditorServices', 'modalDialog', 'serverDataModule', 'personalizationServices']); + + personalizationDesignerModule.controller('personalizationDialogCtrl', ['$rootScope', '$scope', '$q', '$filter', '$uibModalInstance', 'serverData', 'personalizationService', + function ($rootScope, $scope, $q, $filter, $uibModalInstance, serverData, personalizationService) { + + // ------------------------------------------------------------------------ + var onError = function (errorData) { + $scope.feedback.showError = true; + if (errorData && errorData.data) + $scope.feedback.errorMessage = errorData.data.Detail; + }; + + var setSegmentName = function () { + var selectedSegments = $telerik.$.grep($scope.segments, function (value, index) { + return value.Id === $scope.model.segmentId; + }); + + if (selectedSegments && selectedSegments.length === 1) { + $scope.model.segmentName = selectedSegments[0].Name; + } + }; + + $scope.model = { + controlId: "", + segmentId: "" + }; + + $scope.segments = []; + $scope.filteredSegments = []; + personalizationService.getSegments($scope.model).then(function (data) { + $scope.segments = data; + $scope.filteredSegments = $filter('filter')($scope.segments, { IsAvailable: false }); + if ($scope.filteredSegments && $scope.filteredSegments.length > 0) { + $scope.model.segmentId = $scope.filteredSegments[0].Id; + } + + $scope.feedback.showLoadingIndicator = false; + }); + + $scope.goToCreateSegment = function () { + var newSegmentUrl = "Sitefinity/Marketing/Personalization?action=newSegment"; + var newSegmentRootedUrl = sitefinity.getRootedUrl(newSegmentUrl); + + window.location.href = newSegmentRootedUrl; + }; + + $scope.addPersonalization = function () { + $scope.feedback.showLoadingIndicator = true; + setSegmentName(); + + personalizationService.personalize($scope.model) + .then(function (args) { + $scope.close(true); + $telerik.$(document).trigger('personalizationDialogClosed', args); + }, onError) + .finally(function () { + $scope.feedback.showLoadingIndicator = false; + }); + }; + + $scope.feedback = { + showLoadingIndicator: true, + showError: false + }; + + $scope.cancel = function () { + var canceling = $q.defer(); + canceling.promise + .then(function () { + $scope.close(true); + }) + .catch(onError) + .finally(function () { + $scope.feedback.showLoadingIndicator = false; + }); + + $scope.feedback.showLoadingIndicator = true; + canceling.resolve(); + }; + + $scope.close = function (fireModalClosedEvent) { + try { + $uibModalInstance.close(); + } catch (e) { } + + if (typeof ($telerik) !== 'undefined' && fireModalClosedEvent) + $telerik.$(document).trigger('modalDialogClosed'); + + if (typeof CustomEvent == "function") { + var evt = new CustomEvent('sfModalDialogClosed'); + document.dispatchEvent(evt); + } + }; + + $scope.hideError = function () { + $scope.feedback.showError = false; + $scope.feedback.errorMessage = null; + }; + } + ]); +})(jQuery); \ No newline at end of file diff --git a/Telerik.Sitefinity.Frontend/Mvc/Scripts/JSBeautifier/beautify-html.js b/Telerik.Sitefinity.Frontend/Mvc/Scripts/JSBeautifier/beautify-html.js new file mode 100644 index 000000000..ea5a3b62f --- /dev/null +++ b/Telerik.Sitefinity.Frontend/Mvc/Scripts/JSBeautifier/beautify-html.js @@ -0,0 +1,1387 @@ +/*jshint curly:false, eqeqeq:true, laxbreak:true, noempty:false */ +/* AUTO-GENERATED. DO NOT MODIFY. */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + + + Style HTML +--------------- + + Written by Nochum Sossonko, (nsossonko@hotmail.com) + + Based on code initially developed by: Einar Lielmanis, + http://jsbeautifier.org/ + + Usage: + style_html(html_source); + + style_html(html_source, options); + + The options are: + indent_inner_html (default false) — indent and sections, + indent_size (default 4) — indentation size, + indent_char (default space) — character to indent with, + wrap_line_length (default 250) - maximum amount of characters per line (0 = disable) + brace_style (default "collapse") - "collapse" | "expand" | "end-expand" | "none" + put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line, or attempt to keep them where they are. + unformatted (defaults to inline tags) - list of tags, that shouldn't be reformatted + content_unformatted (defaults to pre tag) - list of tags, that its content shouldn't be reformatted + indent_scripts (default normal) - "keep"|"separate"|"normal" + preserve_newlines (default true) - whether existing line breaks before elements should be preserved + Only works before elements, not inside tags or for text. + max_preserve_newlines (default unlimited) - maximum number of line breaks to be preserved in one chunk + indent_handlebars (default false) - format and indent {{#foo}} and {{/foo}} + end_with_newline (false) - end with a newline + extra_liners (default [head,body,/html]) -List of tags that should have an extra newline before them. + + e.g. + + style_html(html_source, { + 'indent_inner_html': false, + 'indent_size': 2, + 'indent_char': ' ', + 'wrap_line_length': 78, + 'brace_style': 'expand', + 'preserve_newlines': true, + 'max_preserve_newlines': 5, + 'indent_handlebars': false, + 'extra_liners': ['/html'] + }); +*/ + +(function() { +var legacy_beautify_html = +/******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; +/******/ +/******/ // The require function +/******/ function __webpack_require__(moduleId) { +/******/ +/******/ // Check if module is in cache +/******/ if(installedModules[moduleId]) { +/******/ return installedModules[moduleId].exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = installedModules[moduleId] = { +/******/ i: moduleId, +/******/ l: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); +/******/ +/******/ // Flag the module as loaded +/******/ module.l = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/******/ +/******/ // expose the modules object (__webpack_modules__) +/******/ __webpack_require__.m = modules; +/******/ +/******/ // expose the module cache +/******/ __webpack_require__.c = installedModules; +/******/ +/******/ // identity function for calling harmony imports with the correct context +/******/ __webpack_require__.i = function(value) { return value; }; +/******/ +/******/ // define getter function for harmony exports +/******/ __webpack_require__.d = function(exports, name, getter) { +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } +/******/ }; +/******/ +/******/ // getDefaultExport function for compatibility with non-harmony modules +/******/ __webpack_require__.n = function(module) { +/******/ var getter = module && module.__esModule ? +/******/ function getDefault() { return module['default']; } : +/******/ function getModuleExports() { return module; }; +/******/ __webpack_require__.d(getter, 'a', getter); +/******/ return getter; +/******/ }; +/******/ +/******/ // Object.prototype.hasOwnProperty.call +/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; +/******/ +/******/ // __webpack_public_path__ +/******/ __webpack_require__.p = ""; +/******/ +/******/ // Load entry module and return exports +/******/ return __webpack_require__(__webpack_require__.s = 3); +/******/ }) +/************************************************************************/ +/******/ ([ +/* 0 */ +/***/ (function(module, exports, __webpack_require__) { + +/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */ +/* + + The MIT License (MIT) + + Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors. + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation files + (the "Software"), to deal in the Software without restriction, + including without limitation the rights to use, copy, modify, merge, + publish, distribute, sublicense, and/or sell copies of the Software, + and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ + +var mergeOpts = __webpack_require__(2).mergeOpts; +var acorn = __webpack_require__(1); + + +var lineBreak = acorn.lineBreak; +var allLineBreaks = acorn.allLineBreaks; + +// function trim(s) { +// return s.replace(/^\s+|\s+$/g, ''); +// } + +function ltrim(s) { + return s.replace(/^\s+/g, ''); +} + +function rtrim(s) { + return s.replace(/\s+$/g, ''); +} + +function Beautifier(html_source, options, js_beautify, css_beautify) { + //Wrapper function to invoke all the necessary constructors and deal with the output. + html_source = html_source || ''; + + var multi_parser, + indent_inner_html, + indent_body_inner_html, + indent_head_inner_html, + indent_size, + indent_character, + wrap_line_length, + brace_style, + unformatted, + content_unformatted, + preserve_newlines, + max_preserve_newlines, + indent_handlebars, + wrap_attributes, + wrap_attributes_indent_size, + is_wrap_attributes_force, + is_wrap_attributes_force_expand_multiline, + is_wrap_attributes_force_aligned, + end_with_newline, + extra_liners, + eol; + + options = options || {}; + + // Allow the setting of language/file-type specific options + // with inheritance of overall settings + options = mergeOpts(options, 'html'); + + // backwards compatibility to 1.3.4 + if ((options.wrap_line_length === undefined || parseInt(options.wrap_line_length, 10) === 0) && + (options.max_char !== undefined && parseInt(options.max_char, 10) !== 0)) { + options.wrap_line_length = options.max_char; + } + + indent_inner_html = (options.indent_inner_html === undefined) ? false : options.indent_inner_html; + indent_body_inner_html = (options.indent_body_inner_html === undefined) ? true : options.indent_body_inner_html; + indent_head_inner_html = (options.indent_head_inner_html === undefined) ? true : options.indent_head_inner_html; + indent_size = (options.indent_size === undefined) ? 4 : parseInt(options.indent_size, 10); + indent_character = (options.indent_char === undefined) ? ' ' : options.indent_char; + brace_style = (options.brace_style === undefined) ? 'collapse' : options.brace_style; + wrap_line_length = parseInt(options.wrap_line_length, 10) === 0 ? 32786 : parseInt(options.wrap_line_length || 250, 10); + unformatted = options.unformatted || [ + // https://www.w3.org/TR/html5/dom.html#phrasing-content + 'a', 'abbr', 'area', 'audio', 'b', 'bdi', 'bdo', 'br', 'button', 'canvas', 'cite', + 'code', 'data', 'datalist', 'del', 'dfn', 'em', 'embed', 'i', 'iframe', 'img', + 'input', 'ins', 'kbd', 'keygen', 'label', 'map', 'mark', 'math', 'meter', 'noscript', + 'object', 'output', 'progress', 'q', 'ruby', 's', 'samp', /* 'script', */ 'select', 'small', + 'span', 'strong', 'sub', 'sup', 'svg', 'template', 'textarea', 'time', 'u', 'var', + 'video', 'wbr', 'text', + // prexisting - not sure of full effect of removing, leaving in + 'acronym', 'address', 'big', 'dt', 'ins', 'strike', 'tt', + ]; + content_unformatted = options.content_unformatted || [ + 'pre', + ]; + preserve_newlines = (options.preserve_newlines === undefined) ? true : options.preserve_newlines; + max_preserve_newlines = preserve_newlines ? + (isNaN(parseInt(options.max_preserve_newlines, 10)) ? 32786 : parseInt(options.max_preserve_newlines, 10)) : + 0; + indent_handlebars = (options.indent_handlebars === undefined) ? false : options.indent_handlebars; + wrap_attributes = (options.wrap_attributes === undefined) ? 'auto' : options.wrap_attributes; + wrap_attributes_indent_size = (isNaN(parseInt(options.wrap_attributes_indent_size, 10))) ? indent_size : parseInt(options.wrap_attributes_indent_size, 10); + is_wrap_attributes_force = wrap_attributes.substr(0, 'force'.length) === 'force'; + is_wrap_attributes_force_expand_multiline = (wrap_attributes === 'force-expand-multiline'); + is_wrap_attributes_force_aligned = (wrap_attributes === 'force-aligned'); + end_with_newline = (options.end_with_newline === undefined) ? false : options.end_with_newline; + extra_liners = (typeof options.extra_liners === 'object') && options.extra_liners ? + options.extra_liners.concat() : (typeof options.extra_liners === 'string') ? + options.extra_liners.split(',') : 'head,body,/html'.split(','); + eol = options.eol ? options.eol : 'auto'; + + if (options.indent_with_tabs) { + indent_character = '\t'; + indent_size = 1; + } + + if (eol === 'auto') { + eol = '\n'; + if (html_source && lineBreak.test(html_source || '')) { + eol = html_source.match(lineBreak)[0]; + } + } + + eol = eol.replace(/\\r/, '\r').replace(/\\n/, '\n'); + + // HACK: newline parsing inconsistent. This brute force normalizes the input. + html_source = html_source.replace(allLineBreaks, '\n'); + + function Parser() { + + this.pos = 0; //Parser position + this.token = ''; + this.current_mode = 'CONTENT'; //reflects the current Parser mode: TAG/CONTENT + this.tags = { //An object to hold tags, their position, and their parent-tags, initiated with default values + parent: 'parent1', + parentcount: 1, + parent1: '' + }; + this.tag_type = ''; + this.token_text = this.last_token = this.last_text = this.token_type = ''; + this.newlines = 0; + this.indent_content = indent_inner_html; + this.indent_body_inner_html = indent_body_inner_html; + this.indent_head_inner_html = indent_head_inner_html; + + this.Utils = { //Uilities made available to the various functions + whitespace: "\n\r\t ".split(''), + + single_token: options.void_elements || [ + // HTLM void elements - aka self-closing tags - aka singletons + // https://www.w3.org/html/wg/drafts/html/master/syntax.html#void-elements + 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', + 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr', + // NOTE: Optional tags - are not understood. + // https://www.w3.org/TR/html5/syntax.html#optional-tags + // The rules for optional tags are too complex for a simple list + // Also, the content of these tags should still be indented in many cases. + // 'li' is a good exmple. + + // Doctype and xml elements + '!doctype', '?xml', + // ?php tag + '?php', + // other tags that were in this list, keeping just in case + 'basefont', 'isindex' + ], + extra_liners: extra_liners, //for tags that need a line of whitespace before them + in_array: function(what, arr) { + for (var i = 0; i < arr.length; i++) { + if (what === arr[i]) { + return true; + } + } + return false; + } + }; + + // Return true if the given text is composed entirely of whitespace. + this.is_whitespace = function(text) { + for (var n = 0; n < text.length; n++) { + if (!this.Utils.in_array(text.charAt(n), this.Utils.whitespace)) { + return false; + } + } + return true; + }; + + this.traverse_whitespace = function() { + var input_char = ''; + + input_char = this.input.charAt(this.pos); + if (this.Utils.in_array(input_char, this.Utils.whitespace)) { + this.newlines = 0; + while (this.Utils.in_array(input_char, this.Utils.whitespace)) { + if (preserve_newlines && input_char === '\n' && this.newlines <= max_preserve_newlines) { + this.newlines += 1; + } + + this.pos++; + input_char = this.input.charAt(this.pos); + } + return true; + } + return false; + }; + + // Append a space to the given content (string array) or, if we are + // at the wrap_line_length, append a newline/indentation. + // return true if a newline was added, false if a space was added + this.space_or_wrap = function(content) { + if (this.line_char_count >= this.wrap_line_length) { //insert a line when the wrap_line_length is reached + this.print_newline(false, content); + this.print_indentation(content); + return true; + } else { + this.line_char_count++; + content.push(' '); + return false; + } + }; + + this.get_content = function() { //function to capture regular content between tags + var input_char = '', + content = [], + handlebarsStarted = 0; + + while (this.input.charAt(this.pos) !== '<' || handlebarsStarted === 2) { + if (this.pos >= this.input.length) { + return content.length ? content.join('') : ['', 'TK_EOF']; + } + + if (handlebarsStarted < 2 && this.traverse_whitespace()) { + this.space_or_wrap(content); + continue; + } + + input_char = this.input.charAt(this.pos); + + if (indent_handlebars) { + if (input_char === '{') { + handlebarsStarted += 1; + } else if (handlebarsStarted < 2) { + handlebarsStarted = 0; + } + + if (input_char === '}' && handlebarsStarted > 0) { + if (handlebarsStarted-- === 0) { + break; + } + } + // Handlebars parsing is complicated. + // {{#foo}} and {{/foo}} are formatted tags. + // {{something}} should get treated as content, except: + // {{else}} specifically behaves like {{#if}} and {{/if}} + var peek3 = this.input.substr(this.pos, 3); + if (peek3 === '{{#' || peek3 === '{{/') { + // These are tags and not content. + break; + } else if (peek3 === '{{!') { + return [this.get_tag(), 'TK_TAG_HANDLEBARS_COMMENT']; + } else if (this.input.substr(this.pos, 2) === '{{') { + if (this.get_tag(true) === '{{else}}') { + break; + } + } + } + + this.pos++; + this.line_char_count++; + content.push(input_char); //letter at-a-time (or string) inserted to an array + } + return content.length ? content.join('') : ''; + }; + + this.get_contents_to = function(name) { //get the full content of a script or style to pass to js_beautify + if (this.pos === this.input.length) { + return ['', 'TK_EOF']; + } + var content = ''; + var reg_match = new RegExp('', 'igm'); + reg_match.lastIndex = this.pos; + var reg_array = reg_match.exec(this.input); + var end_script = reg_array ? reg_array.index : this.input.length; //absolute end of script + if (this.pos < end_script) { //get everything in between the script tags + content = this.input.substring(this.pos, end_script); + this.pos = end_script; + } + return content; + }; + + this.record_tag = function(tag) { //function to record a tag and its parent in this.tags Object + if (this.tags[tag + 'count']) { //check for the existence of this tag type + this.tags[tag + 'count']++; + this.tags[tag + this.tags[tag + 'count']] = this.indent_level; //and record the present indent level + } else { //otherwise initialize this tag type + this.tags[tag + 'count'] = 1; + this.tags[tag + this.tags[tag + 'count']] = this.indent_level; //and record the present indent level + } + this.tags[tag + this.tags[tag + 'count'] + 'parent'] = this.tags.parent; //set the parent (i.e. in the case of a div this.tags.div1parent) + this.tags.parent = tag + this.tags[tag + 'count']; //and make this the current parent (i.e. in the case of a div 'div1') + }; + + this.retrieve_tag = function(tag) { //function to retrieve the opening tag to the corresponding closer + if (this.tags[tag + 'count']) { //if the openener is not in the Object we ignore it + var temp_parent = this.tags.parent; //check to see if it's a closable tag. + while (temp_parent) { //till we reach '' (the initial value); + if (tag + this.tags[tag + 'count'] === temp_parent) { //if this is it use it + break; + } + temp_parent = this.tags[temp_parent + 'parent']; //otherwise keep on climbing up the DOM Tree + } + if (temp_parent) { //if we caught something + this.indent_level = this.tags[tag + this.tags[tag + 'count']]; //set the indent_level accordingly + this.tags.parent = this.tags[temp_parent + 'parent']; //and set the current parent + } + delete this.tags[tag + this.tags[tag + 'count'] + 'parent']; //delete the closed tags parent reference... + delete this.tags[tag + this.tags[tag + 'count']]; //...and the tag itself + if (this.tags[tag + 'count'] === 1) { + delete this.tags[tag + 'count']; + } else { + this.tags[tag + 'count']--; + } + } + }; + + this.indent_to_tag = function(tag) { + // Match the indentation level to the last use of this tag, but don't remove it. + if (!this.tags[tag + 'count']) { + return; + } + var temp_parent = this.tags.parent; + while (temp_parent) { + if (tag + this.tags[tag + 'count'] === temp_parent) { + break; + } + temp_parent = this.tags[temp_parent + 'parent']; + } + if (temp_parent) { + this.indent_level = this.tags[tag + this.tags[tag + 'count']]; + } + }; + + this.get_tag = function(peek) { //function to get a full tag and parse its type + var input_char = '', + content = [], + comment = '', + space = false, + first_attr = true, + has_wrapped_attrs = false, + tag_start, tag_end, + tag_start_char, + orig_pos = this.pos, + orig_line_char_count = this.line_char_count, + is_tag_closed = false, + tail; + + peek = peek !== undefined ? peek : false; + + do { + if (this.pos >= this.input.length) { + if (peek) { + this.pos = orig_pos; + this.line_char_count = orig_line_char_count; + } + return content.length ? content.join('') : ['', 'TK_EOF']; + } + + input_char = this.input.charAt(this.pos); + this.pos++; + + if (this.Utils.in_array(input_char, this.Utils.whitespace)) { //don't want to insert unnecessary space + space = true; + continue; + } + + if (input_char === "'" || input_char === '"') { + input_char += this.get_unformatted(input_char); + space = true; + } + + if (input_char === '=') { //no space before = + space = false; + } + tail = this.input.substr(this.pos - 1); + if (is_wrap_attributes_force_expand_multiline && has_wrapped_attrs && !is_tag_closed && (input_char === '>' || input_char === '/')) { + if (tail.match(/^\/?\s*>/)) { + space = false; + is_tag_closed = true; + this.print_newline(false, content); + this.print_indentation(content); + } + } + if (content.length && content[content.length - 1] !== '=' && input_char !== '>' && space) { + //no space after = or before > + var wrapped = this.space_or_wrap(content); + var indentAttrs = wrapped && input_char !== '/' && !is_wrap_attributes_force; + space = false; + + if (is_wrap_attributes_force && input_char !== '/') { + var force_first_attr_wrap = false; + if (is_wrap_attributes_force_expand_multiline && first_attr) { + var is_only_attribute = tail.match(/^\S*(="([^"]|\\")*")?\s*\/?\s*>/) !== null; + force_first_attr_wrap = !is_only_attribute; + } + if (!first_attr || force_first_attr_wrap) { + this.print_newline(false, content); + this.print_indentation(content); + indentAttrs = true; + } + } + if (indentAttrs) { + has_wrapped_attrs = true; + + //indent attributes an auto, forced, or forced-align line-wrap + var alignment_size = wrap_attributes_indent_size; + if (is_wrap_attributes_force_aligned) { + alignment_size = content.indexOf(' ') + 1; + } + + for (var count = 0; count < alignment_size; count++) { + // only ever further indent with spaces since we're trying to align characters + content.push(' '); + } + } + if (first_attr) { + for (var i = 0; i < content.length; i++) { + if (content[i] === ' ') { + first_attr = false; + break; + } + } + } + } + + if (indent_handlebars && tag_start_char === '<') { + // When inside an angle-bracket tag, put spaces around + // handlebars not inside of strings. + if ((input_char + this.input.charAt(this.pos)) === '{{') { + input_char += this.get_unformatted('}}'); + if (content.length && content[content.length - 1] !== ' ' && content[content.length - 1] !== '<') { + input_char = ' ' + input_char; + } + space = true; + } + } + + if (input_char === '<' && !tag_start_char) { + tag_start = this.pos - 1; + tag_start_char = '<'; + } + + if (indent_handlebars && !tag_start_char) { + if (content.length >= 2 && content[content.length - 1] === '{' && content[content.length - 2] === '{') { + if (input_char === '#' || input_char === '/' || input_char === '!') { + tag_start = this.pos - 3; + } else { + tag_start = this.pos - 2; + } + tag_start_char = '{'; + } + } + + this.line_char_count++; + content.push(input_char); //inserts character at-a-time (or string) + + if (content[1] && (content[1] === '!' || content[1] === '?' || content[1] === '%')) { //if we're in a comment, do something special + // We treat all comments as literals, even more than preformatted tags + // we just look for the appropriate close tag + content = [this.get_comment(tag_start)]; + break; + } + + if (indent_handlebars && content[1] && content[1] === '{' && content[2] && content[2] === '!') { //if we're in a comment, do something special + // We treat all comments as literals, even more than preformatted tags + // we just look for the appropriate close tag + content = [this.get_comment(tag_start)]; + break; + } + + if (indent_handlebars && tag_start_char === '{' && content.length > 2 && content[content.length - 2] === '}' && content[content.length - 1] === '}') { + break; + } + } while (input_char !== '>'); + + var tag_complete = content.join(''); + var tag_index; + var tag_offset; + + // must check for space first otherwise the tag could have the first attribute included, and + // then not un-indent correctly + if (tag_complete.indexOf(' ') !== -1) { //if there's whitespace, thats where the tag name ends + tag_index = tag_complete.indexOf(' '); + } else if (tag_complete.indexOf('\n') !== -1) { //if there's a line break, thats where the tag name ends + tag_index = tag_complete.indexOf('\n'); + } else if (tag_complete.charAt(0) === '{') { + tag_index = tag_complete.indexOf('}'); + } else { //otherwise go with the tag ending + tag_index = tag_complete.indexOf('>'); + } + if (tag_complete.charAt(0) === '<' || !indent_handlebars) { + tag_offset = 1; + } else { + tag_offset = tag_complete.charAt(2) === '#' ? 3 : 2; + } + var tag_check = tag_complete.substring(tag_offset, tag_index).toLowerCase(); + if (tag_complete.charAt(tag_complete.length - 2) === '/' || + this.Utils.in_array(tag_check, this.Utils.single_token)) { //if this tag name is a single tag type (either in the list or has a closing /) + if (!peek) { + this.tag_type = 'SINGLE'; + } + } else if (indent_handlebars && tag_complete.charAt(0) === '{' && tag_check === 'else') { + if (!peek) { + this.indent_to_tag('if'); + this.tag_type = 'HANDLEBARS_ELSE'; + this.indent_content = true; + this.traverse_whitespace(); + } + } else if (this.is_unformatted(tag_check, unformatted) || + this.is_unformatted(tag_check, content_unformatted)) { + // do not reformat the "unformatted" or "content_unformatted" tags + comment = this.get_unformatted('', tag_complete); //...delegate to get_unformatted function + content.push(comment); + tag_end = this.pos - 1; + this.tag_type = 'SINGLE'; + } else if (tag_check === 'script' && + (tag_complete.search('type') === -1 || + (tag_complete.search('type') > -1 && + tag_complete.search(/\b(text|application|dojo)\/(x-)?(javascript|ecmascript|jscript|livescript|(ld\+)?json|method|aspect)/) > -1))) { + if (!peek) { + this.record_tag(tag_check); + this.tag_type = 'SCRIPT'; + } + } else if (tag_check === 'style' && + (tag_complete.search('type') === -1 || + (tag_complete.search('type') > -1 && tag_complete.search('text/css') > -1))) { + if (!peek) { + this.record_tag(tag_check); + this.tag_type = 'STYLE'; + } + } else if (tag_check.charAt(0) === '!') { //peek for ', + matched = false; + + this.pos = start_pos; + var input_char = this.input.charAt(this.pos); + this.pos++; + + while (this.pos <= this.input.length) { + comment += input_char; + + // only need to check for the delimiter if the last chars match + if (comment.charAt(comment.length - 1) === delimiter.charAt(delimiter.length - 1) && + comment.indexOf(delimiter) !== -1) { + break; + } + + // only need to search for custom delimiter for the first few characters + if (!matched && comment.length < 10) { + if (comment.indexOf(''; + matched = true; + } else if (comment.indexOf(''; + matched = true; + } else if (comment.indexOf(''; + matched = true; + } else if (comment.indexOf(''; + matched = true; + } else if (comment.indexOf('{{!--') === 0) { // {{!-- handlebars comment + delimiter = '--}}'; + matched = true; + } else if (comment.indexOf('{{!') === 0) { // {{! handlebars comment + if (comment.length === 5 && comment.indexOf('{{!--') === -1) { + delimiter = '}}'; + matched = true; + } + } else if (comment.indexOf(''; + matched = true; + } else if (comment.indexOf('<%') === 0) { // {{! handlebars comment + delimiter = '%>'; + matched = true; + } + } + + input_char = this.input.charAt(this.pos); + this.pos++; + } + + return comment; + }; + + function tokenMatcher(delimiter) { + var token = ''; + + var add = function(str) { + var newToken = token + str.toLowerCase(); + token = newToken.length <= delimiter.length ? newToken : newToken.substr(newToken.length - delimiter.length, delimiter.length); + }; + + var doesNotMatch = function() { + return token.indexOf(delimiter) === -1; + }; + + return { + add: add, + doesNotMatch: doesNotMatch + }; + } + + this.get_unformatted = function(delimiter, orig_tag) { //function to return unformatted content in its entirety + if (orig_tag && orig_tag.toLowerCase().indexOf(delimiter) !== -1) { + return ''; + } + var input_char = ''; + var content = ''; + var space = true; + + var delimiterMatcher = tokenMatcher(delimiter); + + do { + + if (this.pos >= this.input.length) { + return content; + } + + input_char = this.input.charAt(this.pos); + this.pos++; + + if (this.Utils.in_array(input_char, this.Utils.whitespace)) { + if (!space) { + this.line_char_count--; + continue; + } + if (input_char === '\n' || input_char === '\r') { + content += '\n'; + /* Don't change tab indention for unformatted blocks. If using code for html editing, this will greatly affect
 tags if they are specified in the 'unformatted array'
+            for (var i=0; i]*>\s*$/);
+
+            // if next_tag comes back but is not an isolated tag, then
+            // let's treat the 'a' tag as having content
+            // and respect the unformatted option
+            if (!tag || this.Utils.in_array(tag[1], unformatted)) {
+                return true;
+            } else {
+                return false;
+            }
+        };
+
+        this.printer = function(js_source, indent_character, indent_size, wrap_line_length, brace_style) { //handles input/output and some other printing functions
+
+            this.input = js_source || ''; //gets the input for the Parser
+
+            // HACK: newline parsing inconsistent. This brute force normalizes the input.
+            this.input = this.input.replace(/\r\n|[\r\u2028\u2029]/g, '\n');
+
+            this.output = [];
+            this.indent_character = indent_character;
+            this.indent_string = '';
+            this.indent_size = indent_size;
+            this.brace_style = brace_style;
+            this.indent_level = 0;
+            this.wrap_line_length = wrap_line_length;
+            this.line_char_count = 0; //count to see if wrap_line_length was exceeded
+
+            for (var i = 0; i < this.indent_size; i++) {
+                this.indent_string += this.indent_character;
+            }
+
+            this.print_newline = function(force, arr) {
+                this.line_char_count = 0;
+                if (!arr || !arr.length) {
+                    return;
+                }
+                if (force || (arr[arr.length - 1] !== '\n')) { //we might want the extra line
+                    if ((arr[arr.length - 1] !== '\n')) {
+                        arr[arr.length - 1] = rtrim(arr[arr.length - 1]);
+                    }
+                    arr.push('\n');
+                }
+            };
+
+            this.print_indentation = function(arr) {
+                for (var i = 0; i < this.indent_level; i++) {
+                    arr.push(this.indent_string);
+                    this.line_char_count += this.indent_string.length;
+                }
+            };
+
+            this.print_token = function(text) {
+                // Avoid printing initial whitespace.
+                if (this.is_whitespace(text) && !this.output.length) {
+                    return;
+                }
+                if (text || text !== '') {
+                    if (this.output.length && this.output[this.output.length - 1] === '\n') {
+                        this.print_indentation(this.output);
+                        text = ltrim(text);
+                    }
+                }
+                this.print_token_raw(text);
+            };
+
+            this.print_token_raw = function(text) {
+                // If we are going to print newlines, truncate trailing
+                // whitespace, as the newlines will represent the space.
+                if (this.newlines > 0) {
+                    text = rtrim(text);
+                }
+
+                if (text && text !== '') {
+                    if (text.length > 1 && text.charAt(text.length - 1) === '\n') {
+                        // unformatted tags can grab newlines as their last character
+                        this.output.push(text.slice(0, -1));
+                        this.print_newline(false, this.output);
+                    } else {
+                        this.output.push(text);
+                    }
+                }
+
+                for (var n = 0; n < this.newlines; n++) {
+                    this.print_newline(n > 0, this.output);
+                }
+                this.newlines = 0;
+            };
+
+            this.indent = function() {
+                this.indent_level++;
+            };
+
+            this.unindent = function() {
+                if (this.indent_level > 0) {
+                    this.indent_level--;
+                }
+            };
+        };
+        return this;
+    }
+
+    /*_____________________--------------------_____________________*/
+
+    this.beautify = function() {
+        multi_parser = new Parser(); //wrapping functions Parser
+        multi_parser.printer(html_source, indent_character, indent_size, wrap_line_length, brace_style); //initialize starting values
+        while (true) {
+            var t = multi_parser.get_token();
+            multi_parser.token_text = t[0];
+            multi_parser.token_type = t[1];
+
+            if (multi_parser.token_type === 'TK_EOF') {
+                break;
+            }
+
+            switch (multi_parser.token_type) {
+                case 'TK_TAG_START':
+                    multi_parser.print_newline(false, multi_parser.output);
+                    multi_parser.print_token(multi_parser.token_text);
+                    if (multi_parser.indent_content) {
+                        if ((multi_parser.indent_body_inner_html || !multi_parser.token_text.match(//)) &&
+                            (multi_parser.indent_head_inner_html || !multi_parser.token_text.match(//))) {
+
+                            multi_parser.indent();
+                        }
+
+                        multi_parser.indent_content = false;
+                    }
+                    multi_parser.current_mode = 'CONTENT';
+                    break;
+                case 'TK_TAG_STYLE':
+                case 'TK_TAG_SCRIPT':
+                    multi_parser.print_newline(false, multi_parser.output);
+                    multi_parser.print_token(multi_parser.token_text);
+                    multi_parser.current_mode = 'CONTENT';
+                    break;
+                case 'TK_TAG_END':
+                    //Print new line only if the tag has no content and has child
+                    if (multi_parser.last_token === 'TK_CONTENT' && multi_parser.last_text === '') {
+                        var tag_name = (multi_parser.token_text.match(/\w+/) || [])[0];
+                        var tag_extracted_from_last_output = null;
+                        if (multi_parser.output.length) {
+                            tag_extracted_from_last_output = multi_parser.output[multi_parser.output.length - 1].match(/(?:<|{{#)\s*(\w+)/);
+                        }
+                        if (tag_extracted_from_last_output === null ||
+                            (tag_extracted_from_last_output[1] !== tag_name && !multi_parser.Utils.in_array(tag_extracted_from_last_output[1], unformatted))) {
+                            multi_parser.print_newline(false, multi_parser.output);
+                        }
+                    }
+                    multi_parser.print_token(multi_parser.token_text);
+                    multi_parser.current_mode = 'CONTENT';
+                    break;
+                case 'TK_TAG_SINGLE':
+                    // Don't add a newline before elements that should remain unformatted.
+                    var tag_check = multi_parser.token_text.match(/^\s*<([a-z-]+)/i);
+                    if (!tag_check || !multi_parser.Utils.in_array(tag_check[1], unformatted)) {
+                        multi_parser.print_newline(false, multi_parser.output);
+                    }
+                    multi_parser.print_token(multi_parser.token_text);
+                    multi_parser.current_mode = 'CONTENT';
+                    break;
+                case 'TK_TAG_HANDLEBARS_ELSE':
+                    // Don't add a newline if opening {{#if}} tag is on the current line
+                    var foundIfOnCurrentLine = false;
+                    for (var lastCheckedOutput = multi_parser.output.length - 1; lastCheckedOutput >= 0; lastCheckedOutput--) {
+                        if (multi_parser.output[lastCheckedOutput] === '\n') {
+                            break;
+                        } else {
+                            if (multi_parser.output[lastCheckedOutput].match(/{{#if/)) {
+                                foundIfOnCurrentLine = true;
+                                break;
+                            }
+                        }
+                    }
+                    if (!foundIfOnCurrentLine) {
+                        multi_parser.print_newline(false, multi_parser.output);
+                    }
+                    multi_parser.print_token(multi_parser.token_text);
+                    if (multi_parser.indent_content) {
+                        multi_parser.indent();
+                        multi_parser.indent_content = false;
+                    }
+                    multi_parser.current_mode = 'CONTENT';
+                    break;
+                case 'TK_TAG_HANDLEBARS_COMMENT':
+                    multi_parser.print_token(multi_parser.token_text);
+                    multi_parser.current_mode = 'TAG';
+                    break;
+                case 'TK_CONTENT':
+                    multi_parser.print_token(multi_parser.token_text);
+                    multi_parser.current_mode = 'TAG';
+                    break;
+                case 'TK_STYLE':
+                case 'TK_SCRIPT':
+                    if (multi_parser.token_text !== '') {
+                        multi_parser.print_newline(false, multi_parser.output);
+                        var text = multi_parser.token_text,
+                            _beautifier,
+                            script_indent_level = 1;
+                        if (multi_parser.token_type === 'TK_SCRIPT') {
+                            _beautifier = typeof js_beautify === 'function' && js_beautify;
+                        } else if (multi_parser.token_type === 'TK_STYLE') {
+                            _beautifier = typeof css_beautify === 'function' && css_beautify;
+                        }
+
+                        if (options.indent_scripts === "keep") {
+                            script_indent_level = 0;
+                        } else if (options.indent_scripts === "separate") {
+                            script_indent_level = -multi_parser.indent_level;
+                        }
+
+                        var indentation = multi_parser.get_full_indent(script_indent_level);
+                        if (_beautifier) {
+
+                            // call the Beautifier if avaliable
+                            var Child_options = function() {
+                                this.eol = '\n';
+                            };
+                            Child_options.prototype = options;
+                            var child_options = new Child_options();
+                            text = _beautifier(text.replace(/^\s*/, indentation), child_options);
+                        } else {
+                            // simply indent the string otherwise
+                            var white = text.match(/^\s*/)[0];
+                            var _level = white.match(/[^\n\r]*$/)[0].split(multi_parser.indent_string).length - 1;
+                            var reindent = multi_parser.get_full_indent(script_indent_level - _level);
+                            text = text.replace(/^\s*/, indentation)
+                                .replace(/\r\n|\r|\n/g, '\n' + reindent)
+                                .replace(/\s+$/, '');
+                        }
+                        if (text) {
+                            multi_parser.print_token_raw(text);
+                            multi_parser.print_newline(true, multi_parser.output);
+                        }
+                    }
+                    multi_parser.current_mode = 'TAG';
+                    break;
+                default:
+                    // We should not be getting here but we don't want to drop input on the floor
+                    // Just output the text and move on
+                    if (multi_parser.token_text !== '') {
+                        multi_parser.print_token(multi_parser.token_text);
+                    }
+                    break;
+            }
+            multi_parser.last_token = multi_parser.token_type;
+            multi_parser.last_text = multi_parser.token_text;
+        }
+        var sweet_code = multi_parser.output.join('').replace(/[\r\n\t ]+$/, '');
+
+        // establish end_with_newline
+        if (end_with_newline) {
+            sweet_code += '\n';
+        }
+
+        if (eol !== '\n') {
+            sweet_code = sweet_code.replace(/[\n]/g, eol);
+        }
+
+        return sweet_code;
+    };
+}
+
+module.exports.Beautifier = Beautifier;
+
+
+/***/ }),
+/* 1 */
+/***/ (function(module, exports) {
+
+/* jshint curly: false */
+// This section of code is taken from acorn.
+//
+// Acorn was written by Marijn Haverbeke and released under an MIT
+// license. The Unicode regexps (for identifiers and whitespace) were
+// taken from [Esprima](http://esprima.org) by Ariya Hidayat.
+//
+// Git repositories for Acorn are available at
+//
+//     http://marijnhaverbeke.nl/git/acorn
+//     https://github.com/marijnh/acorn.git
+
+// ## Character categories
+
+// Big ugly regular expressions that match characters in the
+// whitespace, identifier, and identifier-start categories. These
+// are only applied when a character is found to actually have a
+// code point above 128.
+
+var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/; // jshint ignore:line
+var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
+var nonASCIIidentifierChars = "\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
+var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
+var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
+
+// Whether a single character denotes a newline.
+
+exports.newline = /[\n\r\u2028\u2029]/;
+
+// Matches a whole line break (where CRLF is considered a single
+// line break). Used to count lines.
+
+// in javascript, these two differ
+// in python they are the same, different methods are called on them
+exports.lineBreak = new RegExp('\r\n|' + exports.newline.source);
+exports.allLineBreaks = new RegExp(exports.lineBreak.source, 'g');
+
+
+// Test whether a given character code starts an identifier.
+
+exports.isIdentifierStart = function(code) {
+    // permit $ (36) and @ (64). @ is used in ES7 decorators.
+    if (code < 65) return code === 36 || code === 64;
+    // 65 through 91 are uppercase letters.
+    if (code < 91) return true;
+    // permit _ (95).
+    if (code < 97) return code === 95;
+    // 97 through 123 are lowercase letters.
+    if (code < 123) return true;
+    return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
+};
+
+// Test whether a given character is part of an identifier.
+
+exports.isIdentifierChar = function(code) {
+    if (code < 48) return code === 36;
+    if (code < 58) return true;
+    if (code < 65) return false;
+    if (code < 91) return true;
+    if (code < 97) return code === 95;
+    if (code < 123) return true;
+    return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
+};
+
+
+/***/ }),
+/* 2 */
+/***/ (function(module, exports) {
+
+/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */
+/*
+
+    The MIT License (MIT)
+
+    Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors.
+
+    Permission is hereby granted, free of charge, to any person
+    obtaining a copy of this software and associated documentation files
+    (the "Software"), to deal in the Software without restriction,
+    including without limitation the rights to use, copy, modify, merge,
+    publish, distribute, sublicense, and/or sell copies of the Software,
+    and to permit persons to whom the Software is furnished to do so,
+    subject to the following conditions:
+
+    The above copyright notice and this permission notice shall be
+    included in all copies or substantial portions of the Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+    BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+    ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+    CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+    SOFTWARE.
+*/
+
+function mergeOpts(allOptions, targetType) {
+    var finalOpts = {};
+    var name;
+
+    for (name in allOptions) {
+        if (name !== targetType) {
+            finalOpts[name] = allOptions[name];
+        }
+    }
+
+    //merge in the per type settings for the targetType
+    if (targetType in allOptions) {
+        for (name in allOptions[targetType]) {
+            finalOpts[name] = allOptions[targetType][name];
+        }
+    }
+    return finalOpts;
+}
+
+module.exports.mergeOpts = mergeOpts;
+
+
+/***/ }),
+/* 3 */
+/***/ (function(module, exports, __webpack_require__) {
+
+/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */
+/*
+
+    The MIT License (MIT)
+
+    Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors.
+
+    Permission is hereby granted, free of charge, to any person
+    obtaining a copy of this software and associated documentation files
+    (the "Software"), to deal in the Software without restriction,
+    including without limitation the rights to use, copy, modify, merge,
+    publish, distribute, sublicense, and/or sell copies of the Software,
+    and to permit persons to whom the Software is furnished to do so,
+    subject to the following conditions:
+
+    The above copyright notice and this permission notice shall be
+    included in all copies or substantial portions of the Software.
+
+    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+    BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+    ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+    CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+    SOFTWARE.
+*/
+
+var Beautifier = __webpack_require__(0).Beautifier;
+
+function style_html(html_source, options, js_beautify, css_beautify) {
+    var beautifier = new Beautifier(html_source, options, js_beautify, css_beautify);
+    return beautifier.beautify();
+}
+
+module.exports = style_html;
+
+/***/ })
+/******/ ]);
+var style_html = legacy_beautify_html;
+/* Footer */
+if (typeof define === "function" && define.amd) {
+    // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- )
+    define(["require", "./beautify", "./beautify-css"], function(requireamd) {
+        var js_beautify = requireamd("./beautify");
+        var css_beautify = requireamd("./beautify-css");
+
+        return {
+            html_beautify: function(html_source, options) {
+                return style_html(html_source, options, js_beautify.js_beautify, css_beautify.css_beautify);
+            }
+        };
+    });
+} else if (typeof exports !== "undefined") {
+    // Add support for CommonJS. Just put this file somewhere on your require.paths
+    // and you will be able to `var html_beautify = require("beautify").html_beautify`.
+    var js_beautify = require('./beautify.js');
+    var css_beautify = require('./beautify-css.js');
+
+    exports.html_beautify = function(html_source, options) {
+        return style_html(html_source, options, js_beautify.js_beautify, css_beautify.css_beautify);
+    };
+} else if (typeof window !== "undefined") {
+    // If we're running a web page and don't have either of the above, add our one global
+    window.html_beautify = function(html_source, options) {
+        return style_html(html_source, options, window.js_beautify, window.css_beautify);
+    };
+} else if (typeof global !== "undefined") {
+    // If we don't even have window, try global.
+    global.html_beautify = function(html_source, options) {
+        return style_html(html_source, options, global.js_beautify, global.css_beautify);
+    };
+}
+
+}());
diff --git a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Kendo/kendo.all.min.js b/Telerik.Sitefinity.Frontend/Mvc/Scripts/Kendo/kendo.all.min.js
deleted file mode 100644
index 03fececef..000000000
--- a/Telerik.Sitefinity.Frontend/Mvc/Scripts/Kendo/kendo.all.min.js
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
-* Kendo UI v2015.2.624 (http://www.telerik.com/kendo-ui)
-* Copyright 2015 Telerik AD. All rights reserved.
-*
-* Kendo UI commercial licenses may be obtained at
-* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
-* If you do not own a commercial license, this file shall be governed by the trial license terms.
-*/
-(function(f,define){define([],f)})(function(){"bundle all";!function(e,t,n){function i(){}function r(e,t){if(t)return"'"+e.split("'").join("\\'").split('\\"').join('\\\\\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t")+"'";var n=e.charAt(0),i=e.substring(1);return"="===n?"+("+i+")+":":"===n?"+$kendoHtmlEncode("+i+")+":";"+e+";$kendoOutput+="}function o(e,t,n){return e+="",t=t||2,n=t-e.length,n?V[t].substring(0,n)+e:e}function a(e){var t=e.css(mt.support.transitions.css+"box-shadow")||e.css("box-shadow"),n=t?t.match(Dt)||[0,0,0,0,0]:[0,0,0,0,0],i=kt.max(+n[3],+(n[4]||0));return{left:-n[1]+i,right:+n[1]+i,bottom:+n[2]+i}}function s(t,n){var i,r,o,s,l,c,d,u,h=Ct.browser,p="rtl"==t.css("direction");return t.parent().hasClass("k-animation-container")?(d=t.parent(".k-animation-container"),u=d[0].style,d.is(":hidden")&&d.show(),i=St.test(u.width)||St.test(u.height),i||d.css({width:t.outerWidth(),height:t.outerHeight(),boxSizing:"content-box",mozBoxSizing:"content-box",webkitBoxSizing:"content-box"})):(r=a(t),o=t[0].style.width,s=t[0].style.height,l=St.test(o),c=St.test(s),h.opera&&(r.left=r.right=r.bottom=5),i=l||c,!l&&(!n||n&&o)&&(o=t.outerWidth()),!c&&(!n||n&&s)&&(s=t.outerHeight()),t.wrap(e("
").addClass("k-animation-container").css({width:o,height:s,marginLeft:r.left*(p?1:-1),paddingLeft:r.left,paddingRight:r.right,paddingBottom:r.bottom})),i&&t.css({width:"100%",height:"100%",boxSizing:"border-box",mozBoxSizing:"border-box",webkitBoxSizing:"border-box"})),h.msie&&kt.floor(h.version)<=7&&(t.css({zoom:1}),t.children(".k-menu").width(t.width())),t.parent()}function l(e){var t=1,n=arguments.length;for(t=1;n>t;t++)c(e,arguments[t]);return e}function c(e,t){var n,i,r,o,a,s=mt.data.ObservableArray,l=mt.data.LazyObservableArray,d=mt.data.DataSource,u=mt.data.HierarchicalDataSource;for(n in t)i=t[n],r=typeof i,o=r===Mt&&null!==i?i.constructor:null,o&&o!==Array&&o!==s&&o!==l&&o!==d&&o!==u?i instanceof Date?e[n]=new Date(i.getTime()):P(i.clone)?e[n]=i.clone():(a=e[n],e[n]=typeof a===Mt?a||{}:{},c(e[n],i)):r!==Rt&&(e[n]=i);return e}function d(e,t,i){for(var r in t)if(t.hasOwnProperty(r)&&t[r].test(e))return r;return i!==n?i:e}function u(e){return e.replace(/([a-z][A-Z])/g,function(e){return e.charAt(0)+"-"+e.charAt(1).toLowerCase()})}function h(e){return e.replace(/\-(\w)/g,function(e,t){return t.toUpperCase()})}function p(t,n){var i,r={};return document.defaultView&&document.defaultView.getComputedStyle?(i=document.defaultView.getComputedStyle(t,""),n&&e.each(n,function(e,t){r[t]=i.getPropertyValue(t)})):(i=t.currentStyle,n&&e.each(n,function(e,t){r[t]=i[h(t)]})),mt.size(r)||(r=i),r}function f(e){return"visible"!=p(e,["overflow"]).overflow}function g(e){var t,n=0;for(t in e)e.hasOwnProperty(t)&&"toJSON"!=t&&n++;return n}function m(e,n,i){n||(n="offset");var r=e[n]();return Ct.browser.msie&&(Ct.pointers||Ct.msPointers)&&!i&&(r.top-=t.pageYOffset-document.documentElement.scrollTop,r.left-=t.pageXOffset-document.documentElement.scrollLeft),r}function v(e){var t={};return _t("string"==typeof e?e.split(" "):e,function(e){t[e]=this}),t}function _(e){return new mt.effects.Element(e)}function w(e,t,n,i){return typeof e===It&&(P(t)&&(i=t,t=400,n=!1),P(n)&&(i=n,n=!1),typeof t===Ft&&(n=t,t=400),e={effects:e,duration:t,reverse:n,complete:i}),vt({effects:{},duration:400,reverse:!1,init:yt,teardown:yt,hide:!1},e,{completeCallback:e.complete,complete:yt})}function b(t,n,i,r,o){for(var a,s=0,l=t.length;l>s;s++)a=e(t[s]),a.queue(function(){W.promise(a,w(n,i,r,o))});return t}function y(e,t,n,i){return t&&(t=t.split(" "),_t(t,function(t,n){e.toggleClass(n,i)})),e}function k(e){return(""+e).replace(j,"&").replace(G,"<").replace(Y,">").replace(q,""").replace($,"'")}function x(e,t){var i;return 0===t.indexOf("data")&&(t=t.substring(4),t=t.charAt(0).toLowerCase()+t.substring(1)),t=t.replace(it,"-$1"),i=e.getAttribute("data-"+mt.ns+t),null===i?i=n:"null"===i?i=null:"true"===i?i=!0:"false"===i?i=!1:At.test(i)?i=parseFloat(i):tt.test(i)&&!nt.test(i)&&(i=Function("return ("+i+")")()),i}function C(t,i){var r,o,a={};for(r in i)o=x(t,r),o!==n&&(et.test(r)&&(o=mt.template(e("#"+o).html())),a[r]=o);return a}function S(t,n){return e.contains(t,n)?-1:1}function T(){var t=e(this);return e.inArray(t.attr("data-"+mt.ns+"role"),["slider","rangeslider"])>-1||t.is(":visible")}function D(e,t){var n=e.nodeName.toLowerCase();return(/input|select|textarea|button|object/.test(n)?!e.disabled:"a"===n?e.href||t:t)&&A(e)}function A(t){return!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")||e.expr.filters.hidden(this)}).length}function E(e,t){return new E.fn.init(e,t)}var I,P,M,z,F,R,H,B,L,N,O,V,U,W,j,G,q,$,Y,Q,K,X,Z,J,et,tt,nt,it,rt,ot,at,st,lt,ct,dt,ut,ht,pt,ft,gt,mt=t.kendo=t.kendo||{cultures:{}},vt=e.extend,_t=e.each,wt=e.isArray,bt=e.proxy,yt=e.noop,kt=Math,xt=t.JSON||{},Ct={},St=/%/,Tt=/\{(\d+)(:[^\}]+)?\}/g,Dt=/(\d+(?:\.?)\d*)px\s*(\d+(?:\.?)\d*)px\s*(\d+(?:\.?)\d*)px\s*(\d+)?/i,At=/^(\+|-?)\d+(\.?)\d*$/,Et="function",It="string",Pt="number",Mt="object",zt="null",Ft="boolean",Rt="undefined",Ht={},Bt={},Lt=[].slice,Nt=t.Globalize;mt.version="2015.2.624",i.extend=function(e){var t,n,i=function(){},r=this,o=e&&e.init?e.init:function(){r.apply(this,arguments)};i.prototype=r.prototype,n=o.fn=o.prototype=new i;for(t in e)n[t]=null!=e[t]&&e[t].constructor===Object?vt(!0,{},i.prototype[t],e[t]):e[t];return n.constructor=o,o.extend=r.extend,o},i.prototype._initOptions=function(e){this.options=l({},this.options,e)},P=mt.isFunction=function(e){return"function"==typeof e},M=function(){this._defaultPrevented=!0},z=function(){return this._defaultPrevented===!0},F=i.extend({init:function(){this._events={}},bind:function(e,t,i){var r,o,a,s,l,c=this,d=typeof e===It?[e]:e,u=typeof t===Et;if(t===n){for(r in e)c.bind(r,e[r]);return c}for(r=0,o=d.length;o>r;r++)e=d[r],s=u?t:t[e],s&&(i&&(a=s,s=function(){c.unbind(e,s),a.apply(c,arguments)},s.original=a),l=c._events[e]=c._events[e]||[],l.push(s));return c},one:function(e,t){return this.bind(e,t,!0)},first:function(e,t){var n,i,r,o,a=this,s=typeof e===It?[e]:e,l=typeof t===Et;for(n=0,i=s.length;i>n;n++)e=s[n],r=l?t:t[e],r&&(o=a._events[e]=a._events[e]||[],o.unshift(r));return a},trigger:function(e,t){var n,i,r=this,o=r._events[e];if(o){for(t=t||{},t.sender=r,t._defaultPrevented=!1,t.preventDefault=M,t.isDefaultPrevented=z,o=o.slice(),n=0,i=o.length;i>n;n++)o[n].call(r,t);return t._defaultPrevented===!0}return!1},unbind:function(e,t){var i,r=this,o=r._events[e];if(e===n)r._events={};else if(o)if(t)for(i=o.length-1;i>=0;i--)(o[i]===t||o[i].original===t)&&o.splice(i,1);else r._events[e]=[];return r}}),R=/^\w+/,H=/\$\{([^}]*)\}/g,B=/\\\}/g,L=/__CURLY__/g,N=/\\#/g,O=/__SHARP__/g,V=["","0","00","000","0000"],I={paramName:"data",useWithBlock:!0,render:function(e,t){var n,i,r="";for(n=0,i=t.length;i>n;n++)r+=e(t[n]);return r},compile:function(e,t){var n,i,o,a=vt({},this,t),s=a.paramName,l=s.match(R)[0],c=a.useWithBlock,d="var $kendoOutput, $kendoHtmlEncode = kendo.htmlEncode;";if(P(e))return e;for(d+=c?"with("+s+"){":"",d+="$kendoOutput=",i=e.replace(B,"__CURLY__").replace(H,"#=$kendoHtmlEncode($1)#").replace(L,"}").replace(N,"__SHARP__").split("#"),o=0;i.length>o;o++)d+=r(i[o],o%2===0);d+=c?";}":";",d+="return $kendoOutput;",d=d.replace(O,"#");try{return n=Function(l,d),n._slotCount=Math.floor(i.length/2),n}catch(u){throw Error(mt.format("Invalid template:'{0}' Generated code:'{1}'",e,d))}}},function(){function e(e){return a.lastIndex=0,a.test(e)?'"'+e.replace(a,function(e){var t=s[e];return typeof t===It?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function t(o,a){var s,c,d,u,h,p,f=n,g=a[o];if(g&&typeof g===Mt&&typeof g.toJSON===Et&&(g=g.toJSON(o)),typeof r===Et&&(g=r.call(a,o,g)),p=typeof g,p===It)return e(g);if(p===Pt)return isFinite(g)?g+"":zt;if(p===Ft||p===zt)return g+"";if(p===Mt){if(!g)return zt;if(n+=i,h=[],"[object Array]"===l.apply(g)){for(u=g.length,s=0;u>s;s++)h[s]=t(s,g)||zt;return d=0===h.length?"[]":n?"[\n"+n+h.join(",\n"+n)+"\n"+f+"]":"["+h.join(",")+"]",n=f,d}if(r&&typeof r===Mt)for(u=r.length,s=0;u>s;s++)typeof r[s]===It&&(c=r[s],d=t(c,g),d&&h.push(e(c)+(n?": ":":")+d));else for(c in g)Object.hasOwnProperty.call(g,c)&&(d=t(c,g),d&&h.push(e(c)+(n?": ":":")+d));return d=0===h.length?"{}":n?"{\n"+n+h.join(",\n"+n)+"\n"+f+"}":"{"+h.join(",")+"}",n=f,d}}var n,i,r,a=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,s={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},l={}.toString;typeof Date.prototype.toJSON!==Et&&(Date.prototype.toJSON=function(){var e=this;return isFinite(e.valueOf())?o(e.getUTCFullYear(),4)+"-"+o(e.getUTCMonth()+1)+"-"+o(e.getUTCDate())+"T"+o(e.getUTCHours())+":"+o(e.getUTCMinutes())+":"+o(e.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}),typeof xt.stringify!==Et&&(xt.stringify=function(e,o,a){var s;if(n="",i="",typeof a===Pt)for(s=0;a>s;s+=1)i+=" ";else typeof a===It&&(i=a);if(r=o,o&&typeof o!==Et&&(typeof o!==Mt||typeof o.length!==Pt))throw Error("JSON.stringify");return t("",{"":e})})}(),function(){function t(e){if(e){if(e.numberFormat)return e;if(typeof e===It){var t=mt.cultures;return t[e]||t[e.split("-")[0]]||null}return null}return null}function i(e){return e&&(e=t(e)),e||mt.cultures.current}function r(e){e.groupSizes=e.groupSize,e.percent.groupSizes=e.percent.groupSize,e.currency.groupSizes=e.currency.groupSize}function a(e,t,r){r=i(r);var a=r.calendars.standard,s=a.days,l=a.months;return t=a.patterns[t]||t,t.replace(d,function(t){var i,r,c;return"d"===t?r=e.getDate():"dd"===t?r=o(e.getDate()):"ddd"===t?r=s.namesAbbr[e.getDay()]:"dddd"===t?r=s.names[e.getDay()]:"M"===t?r=e.getMonth()+1:"MM"===t?r=o(e.getMonth()+1):"MMM"===t?r=l.namesAbbr[e.getMonth()]:"MMMM"===t?r=l.names[e.getMonth()]:"yy"===t?r=o(e.getFullYear()%100):"yyyy"===t?r=o(e.getFullYear(),4):"h"===t?r=e.getHours()%12||12:"hh"===t?r=o(e.getHours()%12||12):"H"===t?r=e.getHours():"HH"===t?r=o(e.getHours()):"m"===t?r=e.getMinutes():"mm"===t?r=o(e.getMinutes()):"s"===t?r=e.getSeconds():"ss"===t?r=o(e.getSeconds()):"f"===t?r=kt.floor(e.getMilliseconds()/100):"ff"===t?(r=e.getMilliseconds(),r>99&&(r=kt.floor(r/10)),r=o(r)):"fff"===t?r=o(e.getMilliseconds(),3):"tt"===t?r=e.getHours()<12?a.AM[0]:a.PM[0]:"zzz"===t?(i=e.getTimezoneOffset(),c=0>i,r=(""+kt.abs(i/60)).split(".")[0],i=kt.abs(i)-60*r,r=(c?"+":"-")+o(r),r+=":"+o(i)):("zz"===t||"z"===t)&&(r=e.getTimezoneOffset()/60,c=0>r,r=(""+kt.abs(r)).split(".")[0],r=(c?"+":"-")+("zz"===t?o(r):r)),r!==n?r:t.slice(1,t.length-1)})}function s(e,t,r){r=i(r);var o,a,s,c,d,b,y,k,x,C,S,T,D,A,E,I,P,M,z,F,R,H,B,L=r.numberFormat,N=L.groupSize[0],O=L[m],V=L[g],U=L.decimals,W=L.pattern[0],j=[],G=0>e,q=f,$=f,Y=-1;if(e===n)return f;if(!isFinite(e))return e;if(!t)return r.name.length?e.toLocaleString():""+e;if(d=u.exec(t)){if(t=d[1].toLowerCase(),a="c"===t,s="p"===t,(a||s)&&(L=a?L.currency:L.percent,N=L.groupSize[0],O=L[m],V=L[g],U=L.decimals,o=L.symbol,W=L.pattern[G?0:1]),c=d[2],c&&(U=+c),"e"===t)return c?e.toExponential(U):e.toExponential();if(s&&(e*=100),e=l(e,U),G=0>e,e=e.split(g),b=e[0],y=e[1],G&&(b=b.substring(1)),$=b,k=b.length,k>=N)for($=f,C=0;k>C;C++)C>0&&(k-C)%N===0&&($+=O),$+=b.charAt(C);if(y&&($+=V+y),"n"===t&&!G)return $;for(e=f,C=0,S=W.length;S>C;C++)T=W.charAt(C),e+="n"===T?$:"$"===T||"%"===T?o:T;return e}if(G&&(e=-e),(t.indexOf("'")>-1||t.indexOf('"')>-1||t.indexOf("\\")>-1)&&(t=t.replace(h,function(e){var t=e.charAt(0).replace("\\",""),n=e.slice(1).replace(t,"");return j.push(n),w})),t=t.split(";"),G&&t[1])t=t[1],A=!0;else if(0===e){if(t=t[2]||t[0],-1==t.indexOf(v)&&-1==t.indexOf(_))return t}else t=t[0];if(F=t.indexOf("%"),R=t.indexOf("$"),s=-1!=F,a=-1!=R,s&&(e*=100),a&&"\\"===t[R-1]&&(t=t.split("\\").join(""),a=!1),(a||s)&&(L=a?L.currency:L.percent,N=L.groupSize[0],O=L[m],V=L[g],U=L.decimals,o=L.symbol),D=t.indexOf(m)>-1,D&&(t=t.replace(p,f)),E=t.indexOf(g),S=t.length,-1!=E?(y=(""+e).split("e"),y=y[1]?l(e,Math.abs(y[1])):y[0],y=y.split(g)[1]||f,P=t.lastIndexOf(_)-E,I=t.lastIndexOf(v)-E,M=P>-1,z=I>-1,C=y.length,M||z||(t=t.substring(0,E)+t.substring(E+1),S=t.length,E=-1,C=0),M&&P>I?C=P:I>P&&(z&&C>I?C=I:M&&P>C&&(C=P)),C>-1&&(e=l(e,C))):e=l(e),I=t.indexOf(v),H=P=t.indexOf(_),Y=-1==I&&-1!=P?P:-1!=I&&-1==P?I:I>P?P:I,I=t.lastIndexOf(v),P=t.lastIndexOf(_),B=-1==I&&-1!=P?P:-1!=I&&-1==P?I:I>P?I:P,Y==S&&(B=Y),-1!=Y){if($=(""+e).split(g),b=$[0],y=$[1]||f,k=b.length,x=y.length,G&&-1*e>=0&&(G=!1),D)if(k===N&&E-H>k)b=O+b;else if(k>N){for($=f,C=0;k>C;C++)C>0&&(k-C)%N===0&&($+=O),$+=b.charAt(C);b=$}for(e=t.substring(0,Y),G&&!A&&(e+="-"),C=Y;S>C;C++){if(T=t.charAt(C),-1==E){if(k>B-C){e+=b;break}}else if(-1!=P&&C>P&&(q=f),k>=E-C&&E-C>-1&&(e+=b,C=E),E===C){e+=(y?V:f)+y,C+=B-E+1;continue}T===_?(e+=T,q=T):T===v&&(e+=q)}if(B>=Y&&(e+=t.substring(B+1)),a||s){for($=f,C=0,S=e.length;S>C;C++)T=e.charAt(C),$+="$"===T||"%"===T?o:T;e=$}if(S=j.length)for(C=0;S>C;C++)e=e.replace(w,j[C])}return e}var l,c,d=/dddd|ddd|dd|d|MMMM|MMM|MM|M|yyyy|yy|HH|H|hh|h|mm|m|fff|ff|f|tt|ss|s|zzz|zz|z|"[^"]*"|'[^']*'/g,u=/^(n|c|p|e)(\d*)$/i,h=/(\\.)|(['][^']*[']?)|(["][^"]*["]?)/g,p=/\,/g,f="",g=".",m=",",v="#",_="0",w="??",b="en-US",y={}.toString;mt.cultures["en-US"]={name:b,numberFormat:{pattern:["-n"],decimals:2,",":",",".":".",groupSize:[3],percent:{pattern:["-n %","n %"],decimals:2,",":",",".":".",groupSize:[3],symbol:"%"},currency:{pattern:["($n)","$n"],decimals:2,",":",",".":".",groupSize:[3],symbol:"$"}},calendars:{standard:{days:{names:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],namesAbbr:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],namesShort:["Su","Mo","Tu","We","Th","Fr","Sa"]},months:{names:["January","February","March","April","May","June","July","August","September","October","November","December"],namesAbbr:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},AM:["AM","am","AM"],PM:["PM","pm","PM"],patterns:{d:"M/d/yyyy",D:"dddd, MMMM dd, yyyy",F:"dddd, MMMM dd, yyyy h:mm:ss tt",g:"M/d/yyyy h:mm tt",G:"M/d/yyyy h:mm:ss tt",m:"MMMM dd",M:"MMMM dd",s:"yyyy'-'MM'-'ddTHH':'mm':'ss",t:"h:mm tt",T:"h:mm:ss tt",u:"yyyy'-'MM'-'dd HH':'mm':'ss'Z'",y:"MMMM, yyyy",Y:"MMMM, yyyy"},"/":"/",":":":",firstDay:0,twoDigitYearMax:2029}}},mt.culture=function(e){var i,o=mt.cultures;return e===n?o.current:(i=t(e)||o[b],i.calendar=i.calendars.standard,o.current=i,Nt&&!Nt.load&&r(i.numberFormat),n)},mt.findCulture=t,mt.getCulture=i,mt.culture(b),l=function(e,t){return t=t||0,e=(""+e).split("e"),e=Math.round(+(e[0]+"e"+(e[1]?+e[1]+t:t))),e=(""+e).split("e"),e=+(e[0]+"e"+(e[1]?+e[1]-t:-t)),e.toFixed(t)},c=function(e,t,i){if(t){if("[object Date]"===y.call(e))return a(e,t,i);if(typeof e===Pt)return s(e,t,i)}return e!==n?e:""},Nt&&!Nt.load&&(c=function(t,n,i){return e.isPlainObject(i)&&(i=i.name),Nt.format(t,n,i)}),mt.format=function(e){var t=arguments;return e.replace(Tt,function(e,n,i){var r=t[parseInt(n,10)+1];return c(r,i?i.substring(1):"")})},mt._extractFormat=function(e){return"{0:"===e.slice(0,3)&&(e=e.slice(3,e.length-1)),e},mt._activeElement=function(){try{return document.activeElement}catch(e){return document.documentElement.activeElement}},mt._round=l,mt.toString=c}(),function(){function t(e,t,n){return!(e>=t&&n>=e)}function i(e){return e.charAt(0)}function r(t){return e.map(t,i)}function o(e,t){t||23!==e.getHours()||e.setHours(e.getHours()+2)}function a(e){for(var t=0,n=e.length,i=[];n>t;t++)i[t]=(e[t]+"").toLowerCase();return i}function s(e){var t,n={};for(t in e)n[t]=a(e[t]);return n}function l(e,i,a){if(!e)return null;var l,c,d,u,f,g,m,_,w,b,y,k,x,C=function(e){for(var t=0;i[H]===e;)t++,H++;return t>0&&(H-=1),t},S=function(t){var n=v[t]||RegExp("^\\d{1,"+t+"}"),i=e.substr(B,t).match(n);return i?(i=i[0],B+=i.length,parseInt(i,10)):null},T=function(t,n){for(var i,r,o,a=0,s=t.length;s>a;a++)if(i=t[a],r=i.length,o=e.substr(B,r),n&&(o=o.toLowerCase()),o==i)return B+=r,a+1;return null},D=function(){var t=!1;return e.charAt(B)===i[H]&&(B++,t=!0),t},A=a.calendars.standard,E=null,I=null,P=null,M=null,z=null,F=null,R=null,H=0,B=0,L=!1,N=new Date,O=A.twoDigitYearMax||2029,V=N.getFullYear();for(i||(i="d"),u=A.patterns[i],u&&(i=u),i=i.split(""),d=i.length;d>H;H++)if(l=i[H],L)"'"===l?L=!1:D();else if("d"===l){if(c=C("d"),A._lowerDays||(A._lowerDays=s(A.days)),null!==P&&c>2)continue;if(P=3>c?S(2):T(A._lowerDays[3==c?"namesAbbr":"names"],!0),null===P||t(P,1,31))return null}else if("M"===l){if(c=C("M"),A._lowerMonths||(A._lowerMonths=s(A.months)),I=3>c?S(2):T(A._lowerMonths[3==c?"namesAbbr":"names"],!0),null===I||t(I,1,12))return null;I-=1}else if("y"===l){if(c=C("y"),E=S(c),null===E)return null;2==c&&("string"==typeof O&&(O=V+parseInt(O,10)),E=V-V%100+E,E>O&&(E-=100))}else if("h"===l){if(C("h"),M=S(2),12==M&&(M=0),null===M||t(M,0,11))return null}else if("H"===l){if(C("H"),M=S(2),null===M||t(M,0,23))return null}else if("m"===l){if(C("m"),z=S(2),null===z||t(z,0,59))return null}else if("s"===l){if(C("s"),F=S(2),null===F||t(F,0,59))return null}else if("f"===l){if(c=C("f"),x=e.substr(B,c).match(v[3]),R=S(c),null!==R&&(x=x[0].length,3>x&&(R*=Math.pow(10,3-x)),c>3&&(R=parseInt((""+R).substring(0,3),10))),null===R||t(R,0,999))return null}else if("t"===l){if(c=C("t"),_=A.AM,w=A.PM,1===c&&(_=r(_),w=r(w)),f=T(w),!f&&!T(_))return null}else if("z"===l){if(g=!0,c=C("z"),"Z"===e.substr(B,1)){D();continue}if(m=e.substr(B,6).match(c>2?p:h),!m)return null;if(m=m[0].split(":"),b=m[0],y=m[1],!y&&b.length>3&&(B=b.length-2,y=b.substring(B),b=b.substring(0,B)),b=parseInt(b,10),t(b,-12,13))return null;if(c>2&&(y=parseInt(y,10),isNaN(y)||t(y,0,59)))return null}else if("'"===l)L=!0,D();else if(!D())return null;return k=null!==M||null!==z||F||null,null===E&&null===I&&null===P&&k?(E=V,I=N.getMonth(),P=N.getDate()):(null===E&&(E=V),null===P&&(P=1)),f&&12>M&&(M+=12),g?(b&&(M+=-b),y&&(z+=-y),e=new Date(Date.UTC(E,I,P,M,z,F,R))):(e=new Date(E,I,P,M,z,F,R),o(e,M)),100>E&&e.setFullYear(E),e.getDate()!==P&&g===n?null:e}function c(e){var t="-"===e.substr(0,1)?-1:1;return e=e.substring(1),e=60*parseInt(e.substr(0,2),10)+parseInt(e.substring(2),10),t*e}var d=/\u00A0/g,u=/[eE][\-+]?[0-9]+/,h=/[+|\-]\d{1,2}/,p=/[+|\-]\d{1,2}:?\d{2}/,f=/^\/Date\((.*?)\)\/$/,g=/[+-]\d*/,m=["G","g","d","F","D","y","m","T","t"],v={2:/^\d{1,2}/,3:/^\d{1,3}/,4:/^\d{4}/},_={}.toString;mt.parseDate=function(e,t,n){var i,r,o,a,s;if("[object Date]"===_.call(e))return e;if(i=0,r=null,e&&0===e.indexOf("/D")&&(r=f.exec(e)))return r=r[1],s=g.exec(r.substring(1)),r=new Date(parseInt(r,10)),s&&(s=c(s[0]),r=mt.timezone.apply(r,0),r=mt.timezone.convert(r,0,-1*s)),r;if(n=mt.getCulture(n),!t){for(t=[],a=n.calendar.patterns,o=m.length;o>i;i++)t[i]=a[m[i]];i=0,t=["yyyy/MM/dd HH:mm:ss","yyyy/MM/dd HH:mm","yyyy/MM/dd","ddd MMM dd yyyy HH:mm:ss","yyyy-MM-ddTHH:mm:ss.fffffffzzz","yyyy-MM-ddTHH:mm:ss.fffzzz","yyyy-MM-ddTHH:mm:sszzz","yyyy-MM-ddTHH:mm:ss.fffffff","yyyy-MM-ddTHH:mm:ss.fff","yyyy-MM-ddTHH:mmzzz","yyyy-MM-ddTHH:mmzz","yyyy-MM-ddTHH:mm:ss","yyyy-MM-ddTHH:mm","yyyy-MM-dd HH:mm:ss","yyyy-MM-dd HH:mm","yyyy-MM-dd","HH:mm:ss","HH:mm"].concat(t)}for(t=wt(t)?t:[t],o=t.length;o>i;i++)if(r=l(e,t[i],n))return r;return r},mt.parseInt=function(e,t){var n=mt.parseFloat(e,t);return n&&(n=0|n),n},mt.parseFloat=function(e,t,n){if(!e&&0!==e)return null;if(typeof e===Pt)return e;e=""+e,t=mt.getCulture(t);var i,r,o=t.numberFormat,a=o.percent,s=o.currency,l=s.symbol,c=a.symbol,h=e.indexOf("-");return u.test(e)?(e=parseFloat(e.replace(o["."],".")),isNaN(e)&&(e=null),e):h>0?null:(h=h>-1,e.indexOf(l)>-1||n&&n.toLowerCase().indexOf("c")>-1?(o=s,i=o.pattern[0].replace("$",l).split("n"),e.indexOf(i[0])>-1&&e.indexOf(i[1])>-1&&(e=e.replace(i[0],"").replace(i[1],""),h=!0)):e.indexOf(c)>-1&&(r=!0,o=a,l=c),e=e.replace("-","").replace(l,"").replace(d," ").split(o[","].replace(d," ")).join("").replace(o["."],"."),e=parseFloat(e),isNaN(e)?e=null:h&&(e*=-1),e&&r&&(e/=100),e)},Nt&&!Nt.load&&(mt.parseDate=function(e,t,n){return"[object Date]"===_.call(e)?e:Nt.parseDate(e,t,n)},mt.parseFloat=function(t,i){return typeof t===Pt?t:t===n||null===t?null:(e.isPlainObject(i)&&(i=i.name),t=Nt.parseFloat(t,i),isNaN(t)?null:t)})}(),function(){var i,r,o,a,s,l,c;Ct._scrollbar=n,Ct.scrollbar=function(e){if(isNaN(Ct._scrollbar)||e){var t,n=document.createElement("div");return n.style.cssText="overflow:scroll;overflow-x:hidden;zoom:1;clear:both;display:block",n.innerHTML=" ",document.body.appendChild(n),Ct._scrollbar=t=n.offsetWidth-n.scrollWidth,document.body.removeChild(n),t}return Ct._scrollbar},Ct.isRtl=function(t){return e(t).closest(".k-rtl").length>0},i=document.createElement("table");try{i.innerHTML="",Ct.tbodyInnerHtml=!0}catch(u){Ct.tbodyInnerHtml=!1}Ct.touch="ontouchstart"in t,Ct.msPointers=t.MSPointerEvent,Ct.pointers=t.PointerEvent,r=Ct.transitions=!1,o=Ct.transforms=!1,a="HTMLElement"in t?HTMLElement.prototype:[],Ct.hasHW3D="WebKitCSSMatrix"in t&&"m11"in new t.WebKitCSSMatrix||"MozPerspective"in document.documentElement.style||"msPerspective"in document.documentElement.style,_t(["Moz","webkit","O","ms"],function(){var e,t=""+this,a=typeof i.style[t+"Transition"]===It;return a||typeof i.style[t+"Transform"]===It?(e=t.toLowerCase(),o={css:"ms"!=e?"-"+e+"-":"",prefix:t,event:"o"===e||"webkit"===e?e:""},a&&(r=o,r.event=r.event?r.event+"TransitionEnd":"transitionend"),!1):n}),i=null,Ct.transforms=o,Ct.transitions=r,Ct.devicePixelRatio=t.devicePixelRatio===n?1:t.devicePixelRatio;try{Ct.screenWidth=t.outerWidth||t.screen?t.screen.availWidth:t.innerWidth,Ct.screenHeight=t.outerHeight||t.screen?t.screen.availHeight:t.innerHeight}catch(u){Ct.screenWidth=t.screen.availWidth,Ct.screenHeight=t.screen.availHeight}Ct.detectOS=function(e){var n,i,r=!1,o=[],a=!/mobile safari/i.test(e),s={wp:/(Windows Phone(?: OS)?)\s(\d+)\.(\d+(\.\d+)?)/,fire:/(Silk)\/(\d+)\.(\d+(\.\d+)?)/,android:/(Android|Android.*(?:Opera|Firefox).*?\/)\s*(\d+)\.(\d+(\.\d+)?)/,iphone:/(iPhone|iPod).*OS\s+(\d+)[\._]([\d\._]+)/,ipad:/(iPad).*OS\s+(\d+)[\._]([\d_]+)/,meego:/(MeeGo).+NokiaBrowser\/(\d+)\.([\d\._]+)/,webos:/(webOS)\/(\d+)\.(\d+(\.\d+)?)/,blackberry:/(BlackBerry|BB10).*?Version\/(\d+)\.(\d+(\.\d+)?)/,playbook:/(PlayBook).*?Tablet\s*OS\s*(\d+)\.(\d+(\.\d+)?)/,windows:/(MSIE)\s+(\d+)\.(\d+(\.\d+)?)/,tizen:/(tizen).*?Version\/(\d+)\.(\d+(\.\d+)?)/i,sailfish:/(sailfish).*rv:(\d+)\.(\d+(\.\d+)?).*firefox/i,ffos:/(Mobile).*rv:(\d+)\.(\d+(\.\d+)?).*Firefox/},l={ios:/^i(phone|pad|pod)$/i,android:/^android|fire$/i,blackberry:/^blackberry|playbook/i,windows:/windows/,wp:/wp/,flat:/sailfish|ffos|tizen/i,meego:/meego/},c={tablet:/playbook|ipad|fire/i},u={omini:/Opera\sMini/i,omobile:/Opera\sMobi/i,firefox:/Firefox|Fennec/i,mobilesafari:/version\/.*safari/i,ie:/MSIE|Windows\sPhone/i,chrome:/chrome|crios/i,webkit:/webkit/i};for(i in s)if(s.hasOwnProperty(i)&&(o=e.match(s[i]))){if("windows"==i&&"plugins"in navigator)return!1;r={},r.device=i,r.tablet=d(i,c,!1),r.browser=d(e,u,"default"),r.name=d(i,l),r[r.name]=!0,r.majorVersion=o[2],r.minorVersion=o[3].replace("_","."),n=r.minorVersion.replace(".","").substr(0,2),r.flatVersion=r.majorVersion+n+Array(3-(3>n.length?n.length:2)).join("0"),r.cordova=typeof t.PhoneGap!==Rt||typeof t.cordova!==Rt,r.appMode=t.navigator.standalone||/file|local|wmapp/.test(t.location.protocol)||r.cordova,r.android&&(1.5>Ct.devicePixelRatio&&400>r.flatVersion||a)&&(Ct.screenWidth>800||Ct.screenHeight>800)&&(r.tablet=i);break}return r},s=Ct.mobileOS=Ct.detectOS(navigator.userAgent),Ct.wpDevicePixelRatio=s.wp?screen.width/320:0,Ct.kineticScrollNeeded=s&&(Ct.touch||Ct.msPointers||Ct.pointers),Ct.hasNativeScrolling=!1,(s.ios||s.android&&s.majorVersion>2||s.wp)&&(Ct.hasNativeScrolling=s),Ct.mouseAndTouchPresent=Ct.touch&&!(Ct.mobileOS.ios||Ct.mobileOS.android),Ct.detectBrowser=function(e){var t,n=!1,i=[],r={webkit:/(chrome)[ \/]([\w.]+)/i,safari:/(webkit)[ \/]([\w.]+)/i,opera:/(opera)(?:.*version|)[ \/]([\w.]+)/i,msie:/(msie\s|trident.*? rv:)([\w.]+)/i,mozilla:/(mozilla)(?:.*? rv:([\w.]+)|)/i};for(t in r)if(r.hasOwnProperty(t)&&(i=e.match(r[t]))){n={},n[t]=!0,n[i[1].toLowerCase().split(" ")[0].split("/")[0]]=!0,n.version=parseInt(document.documentMode||i[2],10);break}return n},Ct.browser=Ct.detectBrowser(navigator.userAgent),Ct.zoomLevel=function(){var e,n,i;try{return e=Ct.browser,n=0,i=document.documentElement,e.msie&&11==e.version&&i.scrollHeight>i.clientHeight&&!Ct.touch&&(n=Ct.scrollbar()),Ct.touch?i.clientWidth/t.innerWidth:e.msie&&e.version>=10?((top||t).document.documentElement.offsetWidth+n)/(top||t).innerWidth:1}catch(r){return 1}},Ct.cssBorderSpacing=n!==document.documentElement.style.borderSpacing&&!(Ct.browser.msie&&8>Ct.browser.version),function(t){var n="",i=e(document.documentElement),r=parseInt(t.version,10);t.msie?n="ie":t.mozilla?n="ff":t.safari?n="safari":t.webkit?n="webkit":t.opera&&(n="opera"),n&&(n="k-"+n+" k-"+n+r),Ct.mobileOS&&(n+=" k-mobile"),i.addClass(n)}(Ct.browser),Ct.eventCapture=document.documentElement.addEventListener,l=document.createElement("input"),Ct.placeholder="placeholder"in l,Ct.propertyChangeEvent="onpropertychange"in l,Ct.input=function(){for(var e,t=["number","date","time","month","week","datetime","datetime-local"],n=t.length,i="test",r={},o=0;n>o;o++)e=t[o],l.setAttribute("type",e),l.value=i,r[e.replace("-","")]="text"!==l.type&&l.value!==i;return r}(),l.style.cssText="float:left;",Ct.cssFloat=!!l.style.cssFloat,l=null,Ct.stableSort=function(){var e,t=513,n=[{index:0,field:"b"}];for(e=1;t>e;e++)n.push({index:e,field:"a"});return n.sort(function(e,t){return e.field>t.field?1:t.field>e.field?-1:0}),1===n[0].index}(),Ct.matchesSelector=a.webkitMatchesSelector||a.mozMatchesSelector||a.msMatchesSelector||a.oMatchesSelector||a.matchesSelector||a.matches||function(t){for(var n=document.querySelectorAll?(this.parentNode||document).querySelectorAll(t)||[]:e(t),i=n.length;i--;)if(n[i]==this)return!0;return!1},Ct.pushState=t.history&&t.history.pushState,c=document.documentMode,Ct.hashChange="onhashchange"in t&&!(Ct.browser.msie&&(!c||8>=c))}(),U={left:{reverse:"right"},right:{reverse:"left"},down:{reverse:"up"},up:{reverse:"down"},top:{reverse:"bottom"},bottom:{reverse:"top"},"in":{reverse:"out"},out:{reverse:"in"}},W={},e.extend(W,{enabled:!0,Element:function(t){this.element=e(t)},promise:function(e,t){e.is(":visible")||e.css({display:e.data("olddisplay")||"block"}).css("display"),t.hide&&e.data("olddisplay",e.css("display")).hide(),t.init&&t.init(),t.completeCallback&&t.completeCallback(e),e.dequeue()},disable:function(){this.enabled=!1,this.promise=this.promiseShim},enable:function(){this.enabled=!0,this.promise=this.animatedPromise}}),W.promiseShim=W.promise,"kendoAnimate"in e.fn||vt(e.fn,{kendoStop:function(e,t){return this.stop(e,t)},kendoAnimate:function(e,t,n,i){return b(this,e,t,n,i)},kendoAddClass:function(e,t){return mt.toggleClass(this,e,t,!0)},kendoRemoveClass:function(e,t){return mt.toggleClass(this,e,t,!1)},kendoToggleClass:function(e,t,n){return mt.toggleClass(this,e,t,n)}}),j=/&/g,G=//g,Q=function(e){return e.target},Ct.touch&&(Q=function(e){var t="originalEvent"in e?e.originalEvent.changedTouches:"changedTouches"in e?e.changedTouches:null;return t?document.elementFromPoint(t[0].clientX,t[0].clientY):e.target},_t(["swipe","swipeLeft","swipeRight","swipeUp","swipeDown","doubleTap","tap"],function(t,n){e.fn[n]=function(e){return this.bind(n,e)}})),Ct.touch?Ct.mobileOS?(Ct.mousedown="touchstart",Ct.mouseup="touchend",Ct.mousemove="touchmove",Ct.mousecancel="touchcancel",Ct.click="touchend",Ct.resize="orientationchange"):(Ct.mousedown="mousedown touchstart",Ct.mouseup="mouseup touchend",Ct.mousemove="mousemove touchmove",Ct.mousecancel="mouseleave touchcancel",Ct.click="click",Ct.resize="resize"):Ct.pointers?(Ct.mousemove="pointermove",Ct.mousedown="pointerdown",Ct.mouseup="pointerup",Ct.mousecancel="pointercancel",Ct.click="pointerup",Ct.resize="orientationchange resize"):Ct.msPointers?(Ct.mousemove="MSPointerMove",Ct.mousedown="MSPointerDown",Ct.mouseup="MSPointerUp",Ct.mousecancel="MSPointerCancel",Ct.click="MSPointerUp",Ct.resize="orientationchange resize"):(Ct.mousemove="mousemove",Ct.mousedown="mousedown",Ct.mouseup="mouseup",Ct.mousecancel="mouseleave",Ct.click="click",Ct.resize="resize"),K=function(e,t){var n,i,r,o,a=t||"d",s=1;for(i=0,r=e.length;r>i;i++)o=e[i],""!==o&&(n=o.indexOf("["),0!==n&&(-1==n?o="."+o:(s++,o="."+o.substring(0,n)+" || {})"+o.substring(n))),s++,a+=o+(r-1>i?" || {})":")"));return Array(s).join("(")+a},X=/^([a-z]+:)?\/\//i,vt(mt,{ui:mt.ui||{},fx:mt.fx||_,effects:mt.effects||W,mobile:mt.mobile||{},data:mt.data||{},dataviz:mt.dataviz||{},keys:{INSERT:45,DELETE:46,BACKSPACE:8,TAB:9,ENTER:13,ESC:27,LEFT:37,UP:38,RIGHT:39,DOWN:40,END:35,HOME:36,SPACEBAR:32,PAGEUP:33,PAGEDOWN:34,F2:113,F10:121,F12:123,NUMPAD_PLUS:107,NUMPAD_MINUS:109,NUMPAD_DOT:110},support:mt.support||Ct,animate:mt.animate||b,ns:"",attr:function(e){return"data-"+mt.ns+e},getShadows:a,wrap:s,deepExtend:l,getComputedStyles:p,isScrollable:f,size:g,toCamelCase:h,toHyphens:u,getOffset:mt.getOffset||m,parseEffects:mt.parseEffects||v,toggleClass:mt.toggleClass||y,directions:mt.directions||U,Observable:F,Class:i,Template:I,template:bt(I.compile,I),render:bt(I.render,I),stringify:bt(xt.stringify,xt),eventTarget:Q,htmlEncode:k,isLocalUrl:function(e){return e&&!X.test(e)},expr:function(e,t,n){return e=e||"",typeof t==It&&(n=t,t=!1),n=n||"d",e&&"["!==e.charAt(0)&&(e="."+e),t?(e=e.replace(/"([^.]*)\.([^"]*)"/g,'"$1_$DOT$_$2"'),e=e.replace(/'([^.]*)\.([^']*)'/g,"'$1_$DOT$_$2'"),e=K(e.split("."),n),e=e.replace(/_\$DOT\$_/g,".")):e=n+e,e},getter:function(e,t){var n=e+t;return Ht[n]=Ht[n]||Function("d","return "+mt.expr(e,t))},setter:function(e){return Bt[e]=Bt[e]||Function("d,value",mt.expr(e)+"=value")},accessor:function(e){return{get:mt.getter(e),set:mt.setter(e)}},guid:function(){var e,t,n="";for(e=0;32>e;e++)t=16*kt.random()|0,(8==e||12==e||16==e||20==e)&&(n+="-"),n+=(12==e?4:16==e?3&t|8:t).toString(16);return n},roleSelector:function(e){return e.replace(/(\S+)/g,"["+mt.attr("role")+"=$1],").slice(0,-1)},directiveSelector:function(e){var t,n=e.split(" ");if(n)for(t=0;n.length>t;t++)"view"!=n[t]&&(n[t]=n[t].replace(/(\w*)(view|bar|strip|over)$/,"$1-$2"));return n.join(" ").replace(/(\S+)/g,"kendo-mobile-$1,").slice(0,-1)},triggeredByInput:function(e){return/^(label|input|textarea|select)$/i.test(e.target.tagName)},logToConsole:function(e){var i=t.console;!mt.suppressLog&&n!==i&&i.log&&i.log(e)}}),Z=F.extend({init:function(e,t){var n,i=this;i.element=mt.jQuery(e).handler(i),i.angular("init",t),F.fn.init.call(i),n=t?t.dataSource:null,n&&(t=vt({},t,{dataSource:{}})),t=i.options=vt(!0,{},i.options,t),n&&(t.dataSource=n),i.element.attr(mt.attr("role"))||i.element.attr(mt.attr("role"),(t.name||"").toLowerCase()),i.element.data("kendo"+t.prefix+t.name,i),i.bind(i.events,t)},events:[],options:{prefix:""},_hasBindingTarget:function(){return!!this.element[0].kendoBindingTarget},_tabindex:function(e){e=e||this.wrapper;var t=this.element,n="tabindex",i=e.attr(n)||t.attr(n);t.removeAttr(n),e.attr(n,isNaN(i)?0:i)},setOptions:function(t){this._setEvents(t),e.extend(this.options,t)},_setEvents:function(e){for(var t,n=this,i=0,r=n.events.length;r>i;i++)t=n.events[i],n.options[t]&&e[t]&&n.unbind(t,n.options[t]);n.bind(n.events,e)},resize:function(e){var t=this.getSize(),n=this._size;(e||(t.width>0||t.height>0)&&(!n||t.width!==n.width||t.height!==n.height))&&(this._size=t,this._resize(t,e),this.trigger("resize",t))},getSize:function(){return mt.dimensions(this.element)},size:function(e){return e?(this.setSize(e),n):this.getSize()},setSize:e.noop,_resize:e.noop,destroy:function(){var e=this;e.element.removeData("kendo"+e.options.prefix+e.options.name),e.element.removeData("handler"),e.unbind()},angular:function(){}}),J=Z.extend({dataItems:function(){return this.dataSource.flatView()},_angularItems:function(t){var n=this; -n.angular(t,function(){return{elements:n.items(),data:e.map(n.dataItems(),function(e){return{dataItem:e}})}})}}),mt.dimensions=function(e,t){var n=e[0];return t&&e.css(t),{width:n.offsetWidth,height:n.offsetHeight}},mt.notify=yt,et=/template$/i,tt=/^\s*(?:\{(?:.|\r\n|\n)*\}|\[(?:.|\r\n|\n)*\])\s*$/,nt=/^\{(\d+)(:[^\}]+)?\}|^\[[A-Za-z_]*\]$/,it=/([A-Z])/g,mt.initWidget=function(i,r,o){var a,s,l,c,d,u,h,p,f,g,m,v,_;if(o?o.roles&&(o=o.roles):o=mt.ui.roles,i=i.nodeType?i:i[0],u=i.getAttribute("data-"+mt.ns+"role")){f=-1===u.indexOf("."),l=f?o[u]:mt.getter(u)(t),m=e(i).data(),v=l?"kendo"+l.fn.options.prefix+l.fn.options.name:"",g=f?RegExp("^kendo.*"+u+"$","i"):RegExp("^"+v+"$","i");for(_ in m)if(_.match(g)){if(_!==v)return m[_];a=m[_]}if(l){for(p=x(i,"dataSource"),r=e.extend({},C(i,l.fn.options),r),p&&(r.dataSource=typeof p===It?mt.getter(p)(t):p),c=0,d=l.fn.events.length;d>c;c++)s=l.fn.events[c],h=x(i,s),h!==n&&(r[s]=mt.getter(h)(t));return a?e.isEmptyObject(r)||a.setOptions(r):a=new l(i,r),a}}},mt.rolesFromNamespaces=function(e){var t,n,i=[];for(e[0]||(e=[mt.ui,mt.dataviz.ui]),t=0,n=e.length;n>t;t++)i[t]=e[t].roles;return vt.apply(null,[{}].concat(i.reverse()))},mt.init=function(t){var n=mt.rolesFromNamespaces(Lt.call(arguments,1));e(t).find("[data-"+mt.ns+"role]").addBack().each(function(){mt.initWidget(this,{},n)})},mt.destroy=function(t){e(t).find("[data-"+mt.ns+"role]").addBack().each(function(){var t,n=e(this).data();for(t in n)0===t.indexOf("kendo")&&typeof n[t].destroy===Et&&n[t].destroy()})},mt.resize=function(t,n){var i,r=e(t).find("[data-"+mt.ns+"role]").addBack().filter(T);r.length&&(i=e.makeArray(r),i.sort(S),e.each(i,function(){var t=mt.widgetInstance(e(this));t&&t.resize(n)}))},mt.parseOptions=C,vt(mt.ui,{Widget:Z,DataBoundWidget:J,roles:{},progress:function(t,n){var i,r,o,a,s=t.find(".k-loading-mask"),l=mt.support,c=l.browser;n?s.length||(i=l.isRtl(t),r=i?"right":"left",a=t.scrollLeft(),o=c.webkit&&i?t[0].scrollWidth-t.width()-2*a:0,s=e("
Loading...
").width("100%").height("100%").css("top",t.scrollTop()).css(r,Math.abs(a)+o).prependTo(t)):s&&s.remove()},plugin:function(t,i,r){var o,a=t.fn.options.name;i=i||mt.ui,r=r||"",i[a]=t,i.roles[a.toLowerCase()]=t,o="getKendo"+r+a,a="kendo"+r+a,e.fn[a]=function(i){var r,o=this;return typeof i===It?(r=Lt.call(arguments,1),this.each(function(){var t,s,l=e.data(this,a);if(!l)throw Error(mt.format("Cannot call method '{0}' of {1} before it is initialized",i,a));if(t=l[i],typeof t!==Et)throw Error(mt.format("Cannot find method '{0}' of {1}",i,a));return s=t.apply(l,r),s!==n?(o=s,!1):n})):this.each(function(){new t(this,i)}),o},e.fn[a].widget=t,e.fn[o]=function(){return this.data(a)}}}),rt={bind:function(){return this},nullObject:!0,options:{}},ot=Z.extend({init:function(e,t){Z.fn.init.call(this,e,t),this.element.autoApplyNS(),this.wrapper=this.element,this.element.addClass("km-widget")},destroy:function(){Z.fn.destroy.call(this),this.element.kendoDestroy()},options:{prefix:"Mobile"},events:[],view:function(){var e=this.element.closest(mt.roleSelector("view splitview modalview drawer"));return mt.widgetInstance(e,mt.mobile.ui)||rt},viewHasNativeScrolling:function(){var e=this.view();return e&&e.options.useNativeScrolling},container:function(){var e=this.element.closest(mt.roleSelector("view layout modalview drawer splitview"));return mt.widgetInstance(e.eq(0),mt.mobile.ui)||rt}}),vt(mt.mobile,{init:function(e){mt.init(e,mt.mobile.ui,mt.ui,mt.dataviz.ui)},appLevelNativeScrolling:function(){return mt.mobile.application&&mt.mobile.application.options&&mt.mobile.application.options.useNativeScrolling},roles:{},ui:{Widget:ot,DataBoundWidget:J.extend(ot.prototype),roles:{},plugin:function(e){mt.ui.plugin(e,mt.mobile.ui,"Mobile")}}}),l(mt.dataviz,{init:function(e){mt.init(e,mt.dataviz.ui)},ui:{roles:{},themes:{},views:[],plugin:function(e){mt.ui.plugin(e,mt.dataviz.ui)}},roles:{}}),mt.touchScroller=function(t,n){return e(t).map(function(t,i){return i=e(i),Ct.kineticScrollNeeded&&mt.mobile.ui.Scroller&&!i.data("kendoMobileScroller")?(i.kendoMobileScroller(n),i.data("kendoMobileScroller")):!1})[0]},mt.preventDefault=function(e){e.preventDefault()},mt.widgetInstance=function(e,n){var i,r,o,a,s=e.data(mt.ns+"role"),l=[];if(s){if("content"===s&&(s="scroller"),n)if(n[0])for(i=0,r=n.length;r>i;i++)l.push(n[i].roles[s]);else l.push(n.roles[s]);else l=[mt.ui.roles[s],mt.dataviz.ui.roles[s],mt.mobile.ui.roles[s]];for(s.indexOf(".")>=0&&(l=[mt.getter(s)(t)]),i=0,r=l.length;r>i;i++)if(o=l[i],o&&(a=e.data("kendo"+o.fn.options.prefix+o.fn.options.name)))return a}},mt.onResize=function(n){var i=n;return Ct.mobileOS.android&&(i=function(){setTimeout(n,600)}),e(t).on(Ct.resize,i),i},mt.unbindResize=function(n){e(t).off(Ct.resize,n)},mt.attrValue=function(e,t){return e.data(mt.ns+t)},mt.days={Sunday:0,Monday:1,Tuesday:2,Wednesday:3,Thursday:4,Friday:5,Saturday:6},e.extend(e.expr[":"],{kendoFocusable:function(t){var n=e.attr(t,"tabindex");return D(t,!isNaN(n)&&n>-1)}}),at=["mousedown","mousemove","mouseenter","mouseleave","mouseover","mouseout","mouseup","click"],st="label, input, [data-rel=external]",lt={setupMouseMute:function(){var t,n=0,i=at.length,r=document.documentElement;if(!lt.mouseTrap&&Ct.eventCapture)for(lt.mouseTrap=!0,lt.bustClick=!1,lt.captureMouse=!1,t=function(t){lt.captureMouse&&("click"===t.type?lt.bustClick&&!e(t.target).is(st)&&(t.preventDefault(),t.stopPropagation()):t.stopPropagation())};i>n;n++)r.addEventListener(at[n],t,!0)},muteMouse:function(e){lt.captureMouse=!0,e.data.bustClick&&(lt.bustClick=!0),clearTimeout(lt.mouseTrapTimeoutID)},unMuteMouse:function(){clearTimeout(lt.mouseTrapTimeoutID),lt.mouseTrapTimeoutID=setTimeout(function(){lt.captureMouse=!1,lt.bustClick=!1},400)}},ct={down:"touchstart mousedown",move:"mousemove touchmove",up:"mouseup touchend touchcancel",cancel:"mouseleave touchcancel"},Ct.touch&&(Ct.mobileOS.ios||Ct.mobileOS.android)?ct={down:"touchstart",move:"touchmove",up:"touchend touchcancel",cancel:"touchcancel"}:Ct.pointers?ct={down:"pointerdown",move:"pointermove",up:"pointerup",cancel:"pointercancel pointerleave"}:Ct.msPointers&&(ct={down:"MSPointerDown",move:"MSPointerMove",up:"MSPointerUp",cancel:"MSPointerCancel MSPointerLeave"}),!Ct.msPointers||"onmspointerenter"in t||e.each({MSPointerEnter:"MSPointerOver",MSPointerLeave:"MSPointerOut"},function(t,n){e.event.special[t]={delegateType:n,bindType:n,handle:function(t){var i,r=this,o=t.relatedTarget,a=t.handleObj;return(!o||o!==r&&!e.contains(r,o))&&(t.type=a.origType,i=a.handler.apply(this,arguments),t.type=n),i}}}),dt=function(e){return ct[e]||e},ut=/([^ ]+)/g,mt.applyEventMap=function(e,t){return e=e.replace(ut,dt),t&&(e=e.replace(ut,"$1."+t)),e},ht=e.fn.on,vt(!0,E,e),E.fn=E.prototype=new e,E.fn.constructor=E,E.fn.init=function(t,n){return n&&n instanceof e&&!(n instanceof E)&&(n=E(n)),e.fn.init.call(this,t,n,pt)},E.fn.init.prototype=E.fn,pt=E(document),vt(E.fn,{handler:function(e){return this.data("handler",e),this},autoApplyNS:function(e){return this.data("kendoNS",e||mt.guid()),this},on:function(){var e,t,n,i,r,o,a=this,s=a.data("kendoNS");return 1===arguments.length?ht.call(a,arguments[0]):(e=a,t=Lt.call(arguments),typeof t[t.length-1]===Rt&&t.pop(),n=t[t.length-1],i=mt.applyEventMap(t[0],s),Ct.mouseAndTouchPresent&&i.search(/mouse|click/)>-1&&this[0]!==document.documentElement&&(lt.setupMouseMute(),r=2===t.length?null:t[1],o=i.indexOf("click")>-1&&i.indexOf("touchend")>-1,ht.call(this,{touchstart:lt.muteMouse,touchend:lt.unMuteMouse},r,{bustClick:o})),typeof n===It&&(e=a.data("handler"),n=e[n],t[t.length-1]=function(t){n.call(e,t)}),t[0]=i,ht.apply(a,t),a)},kendoDestroy:function(e){return e=e||this.data("kendoNS"),e&&this.off("."+e),this}}),mt.jQuery=E,mt.eventMap=ct,mt.timezone=function(){function e(e,t){var n,i,r,o=t[3],a=t[4],s=t[5],l=t[8];return l||(t[8]=l={}),l[e]?l[e]:(isNaN(a)?0===a.indexOf("last")?(n=new Date(Date.UTC(e,d[o]+1,1,s[0]-24,s[1],s[2],0)),i=u[a.substr(4,3)],r=n.getUTCDay(),n.setUTCDate(n.getUTCDate()+i-r-(i>r?7:0))):a.indexOf(">=")>=0&&(n=new Date(Date.UTC(e,d[o],a.substr(5),s[0],s[1],s[2],0)),i=u[a.substr(0,3)],r=n.getUTCDay(),n.setUTCDate(n.getUTCDate()+i-r+(r>i?7:0))):n=new Date(Date.UTC(e,d[o],a,s[0],s[1],s[2],0)),l[e]=n)}function t(t,n,i){var r,o,a,s;return(n=n[i])?(a=new Date(t).getUTCFullYear(),n=jQuery.grep(n,function(e){var t=e[0],n=e[1];return a>=t&&(n>=a||t==a&&"only"==n||"max"==n)}),n.push(t),n.sort(function(t,n){return"number"!=typeof t&&(t=+e(a,t)),"number"!=typeof n&&(n=+e(a,n)),t-n}),s=n[jQuery.inArray(t,n)-1]||n[n.length-1],isNaN(s)?s:null):(r=i.split(":"),o=0,r.length>1&&(o=60*r[0]+ +r[1]),[-1e6,"max","-","Jan",1,[0,0,0],o,"-"])}function n(e,t,n){var i,r,o,a=t[n];if("string"==typeof a&&(a=t[a]),!a)throw Error('Timezone "'+n+'" is either incorrect, or kendo.timezones.min.js is not included.');for(i=a.length-1;i>=0&&(r=a[i][3],!(r&&e>r));i--);if(o=a[i+1],!o)throw Error('Timezone "'+n+'" not found on '+e+".");return o}function i(e,i,r,o){typeof e!=Pt&&(e=Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));var a=n(e,i,o);return{zone:a,rule:t(e,r,a[1])}}function r(e,t){var n,r,o;return"Etc/UTC"==t||"Etc/GMT"==t?0:(n=i(e,this.zones,this.rules,t),r=n.zone,o=n.rule,mt.parseFloat(o?r[0]-o[6]:r[0]))}function o(e,t){var n=i(e,this.zones,this.rules,t),r=n.zone,o=n.rule,a=r[2];return a.indexOf("/")>=0?a.split("/")[o&&+o[6]?1:0]:a.indexOf("%s")>=0?a.replace("%s",o&&"-"!=o[7]?o[7]:""):a}function a(e,t,n){var i,r;return typeof t==It&&(t=this.offset(e,t)),typeof n==It&&(n=this.offset(e,n)),i=e.getTimezoneOffset(),e=new Date(e.getTime()+6e4*(t-n)),r=e.getTimezoneOffset(),new Date(e.getTime()+6e4*(r-i))}function s(e,t){return this.convert(e,e.getTimezoneOffset(),t)}function l(e,t){return this.convert(e,t,e.getTimezoneOffset())}function c(e){return this.apply(new Date(e),"Etc/UTC")}var d={Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11},u={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6};return{zones:{},rules:{},offset:r,convert:a,apply:s,remove:l,abbr:o,toLocalDate:c}}(),mt.date=function(){function e(e,t){return 0===t&&23===e.getHours()?(e.setHours(e.getHours()+2),!0):!1}function t(t,n,i){var r=t.getHours();i=i||1,n=(n-t.getDay()+7*i)%7,t.setDate(t.getDate()+n),e(t,r)}function n(e,n,i){return e=new Date(e),t(e,n,i),e}function i(e){return new Date(e.getFullYear(),e.getMonth(),1)}function r(e){var t=new Date(e.getFullYear(),e.getMonth()+1,0),n=i(e),r=Math.abs(t.getTimezoneOffset()-n.getTimezoneOffset());return r&&t.setHours(n.getHours()+r/60),t}function o(t){return t=new Date(t.getFullYear(),t.getMonth(),t.getDate(),0,0,0),e(t,0),t}function a(e){return Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}function s(e){return e.getTime()-o(e)}function l(e,t,n){var i,r=s(t),o=s(n);return e&&r!=o?(t>=n&&(n+=m),i=s(e),r>i&&(i+=m),r>o&&(o+=m),i>=r&&o>=i):!0}function c(e,t,n){var i,r=t.getTime(),o=n.getTime();return r>=o&&(o+=m),i=e.getTime(),i>=r&&o>=i}function d(t,n){var i=t.getHours();return t=new Date(t),u(t,n*m),e(t,i),t}function u(e,t,n){var i,r=e.getTimezoneOffset();e.setTime(e.getTime()+t),n||(i=e.getTimezoneOffset()-r,e.setTime(e.getTime()+i*g))}function h(){return o(new Date)}function p(e){return o(e).getTime()==h().getTime()}function f(e){var t=new Date(1980,1,1,0,0,0);return e&&t.setHours(e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()),t}var g=6e4,m=864e5;return{adjustDST:e,dayOfWeek:n,setDayOfWeek:t,getDate:o,isInDateRange:c,isInTimeRange:l,isToday:p,nextDay:function(e){return d(e,1)},previousDay:function(e){return d(e,-1)},toUtcTime:a,MS_PER_DAY:m,MS_PER_HOUR:60*g,MS_PER_MINUTE:g,setTime:u,addDays:d,today:h,toInvariantTime:f,firstDayOfMonth:i,lastDayOfMonth:r,getMilliseconds:s}}(),mt.stripWhitespace=function(e){var t,n,i;if(document.createNodeIterator)for(t=document.createNodeIterator(e,NodeFilter.SHOW_TEXT,function(t){return t.parentNode==e?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT},!1);t.nextNode();)t.referenceNode&&!t.referenceNode.textContent.trim()&&t.referenceNode.parentNode.removeChild(t.referenceNode);else for(n=0;e.childNodes.length>n;n++)i=e.childNodes[n],3!=i.nodeType||/\S/.test(i.nodeValue)||(e.removeChild(i),n--),1==i.nodeType&&mt.stripWhitespace(i)},ft=t.requestAnimationFrame||t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||t.oRequestAnimationFrame||t.msRequestAnimationFrame||function(e){setTimeout(e,1e3/60)},mt.animationFrame=function(e){ft.call(t,e)},gt=[],mt.queueAnimation=function(e){gt[gt.length]=e,1===gt.length&&mt.runNextAnimation()},mt.runNextAnimation=function(){mt.animationFrame(function(){gt[0]&&(gt.shift()(),gt[0]&&mt.runNextAnimation())})},mt.parseQueryStringParams=function(e){for(var t=e.split("?")[1]||"",n={},i=t.split(/&|=/),r=i.length,o=0;r>o;o+=2)""!==i[o]&&(n[decodeURIComponent(i[o])]=decodeURIComponent(i[o+1]));return n},mt.elementUnderCursor=function(e){return n!==e.x.client?document.elementFromPoint(e.x.client,e.y.client):n},mt.wheelDeltaY=function(e){var t,i=e.originalEvent,r=i.wheelDeltaY;return i.wheelDelta?(r===n||r)&&(t=i.wheelDelta):i.detail&&i.axis===i.VERTICAL_AXIS&&(t=10*-i.detail),t},mt.throttle=function(e,t){var i,r,o=0;return!t||0>=t?e:(r=function(){function r(){e.apply(a,l),o=+new Date}var a=this,s=+new Date-o,l=arguments;return o?(i&&clearTimeout(i),s>t?r():i=setTimeout(r,t-s),n):r()},r.cancel=function(){clearTimeout(i)},r)},mt.caret=function(t,i,r){var o,a,s,l,c=i!==n;if(r===n&&(r=i),t[0]&&(t=t[0]),!c||!t.disabled){try{t.selectionStart!==n?c?(t.focus(),t.setSelectionRange(i,r)):i=[t.selectionStart,t.selectionEnd]:document.selection&&(e(t).is(":visible")&&t.focus(),o=t.createTextRange(),c?(o.collapse(!0),o.moveStart("character",i),o.moveEnd("character",r-i),o.select()):(a=o.duplicate(),o.moveToBookmark(document.selection.createRange().getBookmark()),a.setEndPoint("EndToStart",o),s=a.text.length,l=s+o.text.length,i=[s,l]))}catch(d){i=[]}return i}},mt.compileMobileDirective=function(e,n){var i=t.angular;return e.attr("data-"+mt.ns+"role",e[0].tagName.toLowerCase().replace("kendo-mobile-","").replace("-","")),i.element(e).injector().invoke(["$compile",function(t){t(e)(n),/^\$(digest|apply)$/.test(n.$$phase)||n.$digest()}]),mt.widgetInstance(e,mt.mobile.ui)},mt.antiForgeryTokens=function(){var t={},i=e("meta[name=csrf-token],meta[name=_csrf]").attr("content"),r=e("meta[name=csrf-param],meta[name=_csrf_header]").attr("content");return e("input[name^='__RequestVerificationToken']").each(function(){t[this.name]=this.value}),r!==n&&i!==n&&(t[r]=i),t},mt.cycleForm=function(e){function t(e){var t=mt.widgetInstance(e);t&&t.focus?t.focus():e.focus()}var n=e.find("input, .k-widget").first(),i=e.find("button, .k-button").last();i.on("keydown",function(e){e.keyCode!=mt.keys.TAB||e.shiftKey||(e.preventDefault(),t(n))}),n.on("keydown",function(e){e.keyCode==mt.keys.TAB&&e.shiftKey&&(e.preventDefault(),t(i))})},function(){function n(t,n,i,r){var o,a,s=e("
").attr({action:i,method:"POST",target:r}),l=mt.antiForgeryTokens();l.fileName=n,o=t.split(";base64,"),l.contentType=o[0].replace("data:",""),l.base64=o[1];for(a in l)l.hasOwnProperty(a)&&e("").attr({value:l[a],name:a,type:"hidden"}).appendTo(s);s.appendTo("body").submit().remove()}function i(e,t){var n,i,r,o,a,s=e;if("string"==typeof e){for(n=e.split(";base64,"),i=n[0],r=atob(n[1]),o=new Uint8Array(r.length),a=0;r.length>a;a++)o[a]=r.charCodeAt(a);s=new Blob([o.buffer],{type:i})}navigator.msSaveBlob(s,t)}function r(e,n){t.Blob&&e instanceof Blob&&(e=URL.createObjectURL(e)),o.download=n,o.href=e;var i=document.createEvent("MouseEvents");i.initMouseEvent("click",!0,!1,t,0,0,0,0,0,!1,!1,!1,!1,0,null),o.dispatchEvent(i)}var o=document.createElement("a"),a="download"in o;mt.saveAs=function(e){var t=n;e.forceProxy||(a?t=r:navigator.msSaveBlob&&(t=i)),t(e.dataURI,e.fileName,e.proxyURL,e.proxyTarget)}}()}(jQuery,window),function(e,t){function n(e,t){if(!t)return e;e+"/"===t&&(e=t);var n=RegExp("^"+t,"i");return n.test(e)||(e=t+"/"+e),p.protocol+"//"+(p.host+"/"+e).replace(/\/\/+/g,"/")}function i(e){return e?"#!":"#"}function r(e){var t=p.href;return"#!"===e&&t.indexOf("#")>-1&&t.indexOf("#!")<0?null:t.split(e)[1]||""}function o(e,t){return 0===t.indexOf(e)?t.substr(e.length).replace(/\/\//g,"/"):t}function a(e){return e.replace(/^(#)?/,"#")}function s(e){return e.replace(/^(#(!)?)?/,"#!")}var l=window.kendo,c="change",d="back",u="same",h=l.support,p=window.location,f=window.history,g=50,m=l.support.browser.msie,v=/^#*/,_=window.document,w=l.Class.extend({back:function(){m?setTimeout(function(){f.back()}):f.back()},forward:function(){m?setTimeout(function(){f.forward()}):f.forward()},length:function(){return f.length},replaceLocation:function(e){p.replace(e)}}),b=w.extend({init:function(e){this.root=e},navigate:function(e){f.pushState({},_.title,n(e,this.root))},replace:function(e){f.replaceState({},_.title,n(e,this.root))},normalize:function(e){return o(this.root,e)},current:function(){var e=p.pathname;return p.search&&(e+=p.search),o(this.root,e)},change:function(t){e(window).bind("popstate.kendo",t)},stop:function(){e(window).unbind("popstate.kendo")},normalizeCurrent:function(e){var t,o=e.root,a=p.pathname,s=r(i(e.hashBang));o===a+"/"&&(t=o),o===a&&s&&(t=n(s.replace(v,""),o)),t&&f.pushState({},_.title,t)}}),y=w.extend({init:function(e){this._id=l.guid(),this.prefix=i(e),this.fix=e?s:a},navigate:function(e){p.hash=this.fix(e)},replace:function(e){this.replaceLocation(this.fix(e))},normalize:function(e){return e.indexOf(this.prefix)<0?e:e.split(this.prefix)[1]},change:function(t){h.hashChange?e(window).on("hashchange."+this._id,t):this._interval=setInterval(t,g)},stop:function(){e(window).off("hashchange."+this._id),clearInterval(this._interval)},current:function(){return r(this.prefix)},normalizeCurrent:function(e){var t=p.pathname,n=e.root;return e.pushState&&n!==t?(this.replaceLocation(n+this.prefix+o(n,t)),!0):!1}}),k=l.Observable.extend({start:function(t){if(t=t||{},this.bind([c,d,u],t),!this._started){this._started=!0,t.root=t.root||"/";var n,i=this.createAdapter(t);i.normalizeCurrent(t)||(n=i.current(),e.extend(this,{adapter:i,root:t.root,historyLength:i.length(),current:n,locations:[n]}),i.change(e.proxy(this,"_checkUrl")))}},createAdapter:function(e){return h.pushState&&e.pushState?new b(e.root):new y(e.hashBang)},stop:function(){this._started&&(this.adapter.stop(),this.unbind(c),this._started=!1)},change:function(e){this.bind(c,e)},replace:function(e,t){this._navigate(e,t,function(t){t.replace(e),this.locations[this.locations.length-1]=this.current})},navigate:function(e,n){return"#:back"===e?(this.backCalled=!0,this.adapter.back(),t):(this._navigate(e,n,function(t){t.navigate(e),this.locations.push(this.current)}),t)},_navigate:function(e,n,i){var r=this.adapter;return e=r.normalize(e),this.current===e||this.current===decodeURIComponent(e)?(this.trigger(u),t):((n||!this.trigger(c,{url:e}))&&(this.current=e,i.call(this,r),this.historyLength=r.length()),t)},_checkUrl:function(){var e=this.adapter,n=e.current(),i=e.length(),r=this.historyLength===i,o=n===this.locations[this.locations.length-2]&&r,a=this.backCalled,s=this.current;return null===n||this.current===n||this.current===decodeURIComponent(n)?!0:(this.historyLength=i,this.backCalled=!1,this.current=n,o&&this.trigger("back",{url:s,to:n})?(e.forward(),this.current=s,t):this.trigger(c,{url:n,backButtonPressed:!a})?(o?e.forward():(e.back(),this.historyLength--),this.current=s,t):(o?this.locations.pop():this.locations.push(n),t))}});l.History=k,l.History.HistoryAdapter=w,l.History.HashAdapter=y,l.History.PushStateAdapter=b,l.absoluteURL=n,l.history=new k}(window.kendo.jQuery),function(){function e(e,t){return t?e:"([^/]+)"}function t(t,n){return RegExp("^"+t.replace(f,"\\$&").replace(u,"(?:$1)?").replace(h,e).replace(p,"(.*?)")+"$",n?"i":"")}function n(e){return e.replace(/(\?.*)|(#.*)/g,"")}var i=window.kendo,r=i.history,o=i.Observable,a="init",s="routeMissing",l="change",c="back",d="same",u=/\((.*?)\)/g,h=/(\(\?)?:\w+/g,p=/\*\w+/g,f=/[\-{}\[\]+?.,\\\^$|#\s]/g,g=i.Class.extend({init:function(e,n,i){e instanceof RegExp||(e=t(e,i)),this.route=e,this._callback=n},callback:function(e){var t,r,o=0,a=i.parseQueryStringParams(e);for(e=n(e),t=this.route.exec(e).slice(1),r=t.length;r>o;o++)void 0!==t[o]&&(t[o]=decodeURIComponent(t[o]));t.push(a),this._callback.apply(null,t)},worksWith:function(e){return this.route.test(n(e))?(this.callback(e),!0):!1}}),m=o.extend({init:function(e){e||(e={}),o.fn.init.call(this),this.routes=[],this.pushState=e.pushState,this.hashBang=e.hashBang,this.root=e.root,this.ignoreCase=e.ignoreCase!==!1,this.bind([a,s,l,d],e)},destroy:function(){r.unbind(l,this._urlChangedProxy),r.unbind(d,this._sameProxy),r.unbind(c,this._backProxy),this.unbind()},start:function(){var e,t=this,n=function(){t._same()},i=function(e){t._back(e)},o=function(e){t._urlChanged(e)};r.start({same:n,change:o,back:i,pushState:t.pushState,hashBang:t.hashBang,root:t.root}),e={url:r.current||"/",preventDefault:$.noop},t.trigger(a,e)||t._urlChanged(e),this._urlChangedProxy=o,this._backProxy=i},route:function(e,t){this.routes.push(new g(e,t,this.ignoreCase))},navigate:function(e,t){i.history.navigate(e,t)},replace:function(e,t){i.history.replace(e,t)},_back:function(e){this.trigger(c,{url:e.url,to:e.to})&&e.preventDefault()},_same:function(){this.trigger(d)},_urlChanged:function(e){var t,n,r,o,a=e.url;if(a||(a="/"),this.trigger(l,{url:e.url,params:i.parseQueryStringParams(e.url),backButtonPressed:e.backButtonPressed}))return void e.preventDefault();for(t=0,n=this.routes,o=n.length;o>t;t++)if(r=n[t],r.worksWith(a))return;this.trigger(s,{url:a,params:i.parseQueryStringParams(a),backButtonPressed:e.backButtonPressed})&&e.preventDefault()}});i.Router=m}(),function(e,t){function n(i,o){var l,c,d,u,h,p,f,g,m=[],v=i.logic||"and",_=i.filters;for(l=0,c=_.length;c>l;l++)i=_[l],d=i.field,f=i.value,p=i.operator,i.filters?i=n(i,o):(g=i.ignoreCase,d=d.replace(/\./g,"/"),i=a[p],o&&(i=s[p]),i&&f!==t&&(u=e.type(f),"string"===u?(h="'{1}'",f=f.replace(/'/g,"''"),g===!0&&(d="tolower("+d+")")):h="date"===u?o?"{1:yyyy-MM-ddTHH:mm:ss+00:00}":"datetime'{1:yyyy-MM-ddTHH:mm:ss}'":"{1}",i.length>3?"substringof"!==i?h="{0}({2},"+h+")":(h="{0}("+h+",{2})","doesnotcontain"===p&&(o?(h="{0}({2},'{1}') eq -1",i="indexof"):h+=" eq false")):h="{2} {0} "+h,i=r.format(h,i,f,d))),m.push(i);return i=m.join(" "+v+" "),m.length>1&&(i="("+i+")"),i}function i(e){for(var t in e)0===t.indexOf("@odata")&&delete e[t]}var r=window.kendo,o=e.extend,a={eq:"eq",neq:"ne",gt:"gt",gte:"ge",lt:"lt",lte:"le",contains:"substringof",doesnotcontain:"substringof",endswith:"endswith",startswith:"startswith"},s=o({},a,{contains:"contains"}),l={pageSize:e.noop,page:e.noop,filter:function(e,t,i){t&&(t=n(t,i),t&&(e.$filter=t))},sort:function(t,n){var i=e.map(n,function(e){var t=e.field.replace(/\./g,"/");return"desc"===e.dir&&(t+=" desc"),t}).join(",");i&&(t.$orderby=i)},skip:function(e,t){t&&(e.$skip=t)},take:function(e,t){t&&(e.$top=t)}},c={read:{dataType:"jsonp"}};o(!0,r.data,{schemas:{odata:{type:"json",data:function(e){return e.d.results||[e.d]},total:"d.__count"}},transports:{odata:{read:{cache:!0,dataType:"jsonp",jsonp:"$callback"},update:{cache:!0,dataType:"json",contentType:"application/json",type:"PUT"},create:{cache:!0,dataType:"json",contentType:"application/json",type:"POST"},destroy:{cache:!0,dataType:"json",type:"DELETE"},parameterMap:function(e,t,n){var i,o,a,s;if(e=e||{},t=t||"read",s=(this.options||c)[t],s=s?s.dataType:"json","read"===t){i={$inlinecount:"allpages"},"json"!=s&&(i.$format="json");for(a in e)l[a]?l[a](i,e[a],n):i[a]=e[a]}else{if("json"!==s)throw Error("Only json dataType can be used for "+t+" operation.");if("destroy"!==t){for(a in e)o=e[a],"number"==typeof o&&(e[a]=o+"");i=r.stringify(e)}}return i}}}}),o(!0,r.data,{schemas:{"odata-v4":{type:"json",data:function(t){return t=e.extend({},t),i(t),t.value?t.value:[t]},total:function(e){return e["@odata.count"]}}},transports:{"odata-v4":{read:{cache:!0,dataType:"json"},update:{cache:!0,dataType:"json",contentType:"application/json;IEEE754Compatible=true",type:"PUT"},create:{cache:!0,dataType:"json",contentType:"application/json;IEEE754Compatible=true",type:"POST"},destroy:{cache:!0,dataType:"json",type:"DELETE"},parameterMap:function(e,t){var n=r.data.transports.odata.parameterMap(e,t,!0);return"read"==t&&(n.$count=!0,delete n.$inlinecount),n}}}})}(window.kendo.jQuery),function(e,t){var n=window.kendo,i=e.isArray,r=e.isPlainObject,o=e.map,a=e.each,s=e.extend,l=n.getter,c=n.Class,d=c.extend({init:function(t){var l,c,d,u,h=this,p=t.total,f=t.model,g=t.parse,m=t.errors,v=t.serialize,_=t.data;f&&(r(f)&&(l=t.modelBase||n.data.Model,f.fields&&a(f.fields,function(t,n){r(n)&&n.field?e.isFunction(n.field)||(n=s(n,{field:h.getter(n.field)})):n={field:h.getter(n)},f.fields[t]=n}),c=f.id,c&&(d={},d[h.xpathToMember(c,!0)]={field:h.getter(c)},f.fields=s(d,f.fields),f.id=h.xpathToMember(c)),f=l.define(f)),h.model=f),p&&("string"==typeof p?(p=h.getter(p),h.total=function(e){return parseInt(p(e),10)}):"function"==typeof p&&(h.total=p)),m&&("string"==typeof m?(m=h.getter(m),h.errors=function(e){return m(e)||null}):"function"==typeof m&&(h.errors=m)),_&&("string"==typeof _?(_=h.xpathToMember(_),h.data=function(e){var t,n=h.evaluate(e,_);return n=i(n)?n:[n],h.model&&f.fields?(t=new h.model,o(n,function(e){if(e){var n,i={};for(n in f.fields)i[n]=t._parse(n,f.fields[n].field(e));return i}})):n}):"function"==typeof _&&(h.data=_)),"function"==typeof g&&(u=h.parse,h.parse=function(e){var t=g.call(h,e);return u.call(h,t)}),"function"==typeof v&&(h.serialize=v)},total:function(e){return this.data(e).length},errors:function(e){return e?e.errors:null},serialize:function(e){return e},parseDOM:function(e){var n,r,o,a,s,l,c,d={},u=e.attributes,h=u.length;for(c=0;h>c;c++)l=u[c],d["@"+l.nodeName]=l.nodeValue;for(r=e.firstChild;r;r=r.nextSibling)o=r.nodeType,3===o||4===o?d["#text"]=r.nodeValue:1===o&&(n=this.parseDOM(r),a=r.nodeName,s=d[a],i(s)?s.push(n):s=s!==t?[s,n]:n,d[a]=s);return d},evaluate:function(e,t){for(var n,r,o,a,s,l=t.split(".");n=l.shift();)if(e=e[n],i(e)){for(r=[],t=l.join("."),s=0,o=e.length;o>s;s++)a=this.evaluate(e[s],t),a=i(a)?a:[a],r.push.apply(r,a);return r}return e},parse:function(t){var n,i,r={};return n=t.documentElement||e.parseXML(t).documentElement,i=this.parseDOM(n),r[n.nodeName]=i,r},xpathToMember:function(e,t){return e?(e=e.replace(/^\//,"").replace(/\//g,"."),e.indexOf("@")>=0?e.replace(/\.?(@.*)/,t?"$1":'["$1"]'):e.indexOf("text()")>=0?e.replace(/(\.?text\(\))/,t?"#text":'["#text"]'):e):""},getter:function(e){return l(this.xpathToMember(e),!0)}});e.extend(!0,n.data,{XmlDataReader:d,readers:{xml:d}})}(window.kendo.jQuery),function(e,t){function n(e,t,n,i){return function(r){var o,a={};for(o in r)a[o]=r[o];a.field=i?n+"."+r.field:n,t==wt&&e._notifyChange&&e._notifyChange(a),e.trigger(t,a)}}function i(t,n){if(t===n)return!0;var r,o=e.type(t),a=e.type(n);if(o!==a)return!1;if("date"===o)return t.getTime()===n.getTime();if("object"!==o&&"array"!==o)return!1;for(r in t)if(!i(t[r],n[r]))return!1;return!0}function r(e,t){var n,i;for(i in e){if(n=e[i],nt(n)&&n.field&&n.field===t)return n;if(n===t)return n}return null}function o(e){this.data=e||[]}function a(e,n){if(e){var i=typeof e===pt?{field:e,dir:n}:e,r=rt(i)?i:i!==t?[i]:[];return ot(r,function(e){return!!e.dir})}}function s(e){var t,n,i,r,o=e.filters;if(o)for(t=0,n=o.length;n>t;t++)i=o[t],r=i.operator,r&&typeof r===pt&&(i.operator=U[r.toLowerCase()]||r),s(i)}function l(e){return e&&!it(e)?((rt(e)||!e.filters)&&(e={logic:"and",filters:rt(e)?e:[e]}),s(e),e):t}function c(e){return rt(e)?e:[e]}function d(e,n){var i=typeof e===pt?{field:e,dir:n}:e,r=rt(i)?i:i!==t?[i]:[];return L(r,function(e){return{field:e.field,dir:e.dir||"asc",aggregates:e.aggregates}})}function u(e,t){return e&&e.getTime&&t&&t.getTime?e.getTime()===t.getTime():e===t}function h(e,t,n,i,r,o){var a,s,l,c,d;for(t=t||[],c=t.length,a=0;c>a;a++)s=t[a],l=s.aggregate,d=s.field,e[d]=e[d]||{},o[d]=o[d]||{},o[d][l]=o[d][l]||{},e[d][l]=W[l.toLowerCase()](e[d][l],n,ct.accessor(d),i,r,o[d][l])}function p(e){return"number"==typeof e&&!isNaN(e)}function f(e){return e&&e.getTime}function g(e){var t,n=e.length,i=Array(n);for(t=0;n>t;t++)i[t]=e[t].toJSON();return i}function m(e,t,n,i,r){var o,a,s,l,c;for(l=0,c=e.length;c>l;l++){o=e[l];for(a in t)s=r[a],s&&s!==a&&(o[s]=t[a](o),delete o[a])}}function v(e,t,n,i,r){var o,a,s,l,c;for(l=0,c=e.length;c>l;l++){o=e[l];for(a in t)o[a]=n._parse(a,t[a](o)),s=r[a],s&&s!==a&&delete o[s]}}function _(e,t,n,i,r){var o,a,s,l;for(a=0,l=e.length;l>a;a++)o=e[a],s=i[o.field],s&&s!=o.field&&(o.field=s),o.value=n._parse(o.field,o.value),o.hasSubgroups?_(o.items,t,n,i,r):v(o.items,t,n,i,r)}function w(e,t,n,i,r,o){return function(a){return a=e(a),a&&!it(i)&&("[object Array]"===Lt.call(a)||a instanceof Wt||(a=[a]),n(a,i,new t,r,o)),a||[]}}function b(e,t,n,i){for(var r,o,a,s=0;t.length&&i&&(r=t[s],o=r.items,a=o.length,e&&e.field===r.field&&e.value===r.value?(e.hasSubgroups&&e.items.length?b(e.items[e.items.length-1],r.items,n,i):(o=o.slice(n,n+i),e.items=e.items.concat(o)),t.splice(s--,1)):r.hasSubgroups&&o.length?(b(r,o,n,i),r.items.length||t.splice(s--,1)):(o=o.slice(n,n+i),r.items=o,r.items.length||t.splice(s--,1)),0===o.length?n-=a:(n=0,i-=o.length),!(++s>=t.length)););t.length>s&&t.splice(s,t.length-s)}function y(e){var t,n,i,r,o,a=[];for(t=0,n=e.length;n>t;t++)if(o=e.at(t),o.hasSubgroups)a=a.concat(y(o.items));else for(i=o.items,r=0;i.length>r;r++)a.push(i.at(r));return a}function k(e,t){var n,i,r;if(t)for(n=0,i=e.length;i>n;n++)r=e.at(n),r.hasSubgroups?k(r.items,t):r.items=new jt(r.items,t)}function x(e,t){for(var n=0,i=e.length;i>n;n++)if(e[n].hasSubgroups){if(x(e[n].items,t))return!0}else if(t(e[n].items,e[n]))return!0}function C(e,t,n,i){for(var r=0;e.length>r&&e[r].data!==t&&!S(e[r].data,n,i);r++);}function S(e,t,n){for(var i=0,r=e.length;r>i;i++){if(e[i]&&e[i].hasSubgroups)return S(e[i].items,t,n);if(e[i]===t||e[i]===n)return e[i]=n,!0}}function T(e,n,i,r,o){var a,s,l,c;for(a=0,s=e.length;s>a;a++)if(l=e[a],l&&!(l instanceof r))if(l.hasSubgroups===t||o){for(c=0;n.length>c;c++)if(n[c]===l){e[a]=n.at(c),C(i,n,l,e[a]);break}}else T(l.items,n,i,r,o)}function D(e,t){var n,i,r;for(n=0,i=e.length;i>n;n++)if(r=e.at(n),r.uid==t.uid)return e.splice(n,1),r}function A(e,t){return t?I(e,function(e){return e.uid?e.uid==t.uid:e[t.idField]===t.id}):-1}function E(e,t){return t?I(e,function(e){return e.uid==t.uid}):-1}function I(e,t){var n,i;for(n=0,i=e.length;i>n;n++)if(t(e[n]))return n;return-1}function P(e,t){var n,i;return e&&!it(e)?(n=e[t],i=nt(n)?n.from||n.field||t:e[t]||t,dt(i)?t:i):t}function M(e,t){var n,i,r,o={};for(r in e)"filters"!==r&&(o[r]=e[r]);if(e.filters)for(o.filters=[],n=0,i=e.filters.length;i>n;n++)o.filters[n]=M(e.filters[n],t);else o.field=P(t.fields,o.field);return o}function z(e,t){var n,i,r,o,a,s=[];for(n=0,i=e.length;i>n;n++){r={},o=e[n];for(a in o)r[a]=o[a];r.field=P(t.fields,r.field),r.aggregates&&rt(r.aggregates)&&(r.aggregates=z(r.aggregates,t)),s.push(r)}return s}function F(t,n){var i,r,o,a,s,l,c,d,u,h;for(t=e(t)[0],i=t.options,r=n[0],o=n[1],a=[],s=0,l=i.length;l>s;s++)u={},d=i[s],c=d.parentNode,c===t&&(c=null),d.disabled||c&&c.disabled||(c&&(u.optgroup=c.label),u[r.field]=d.text,h=d.attributes.value,h=h&&h.specified?d.value:d.text,u[o.field]=h,a.push(u));return a}function R(t,n){var i,r,o,a,s,l,c,d=e(t)[0].tBodies[0],u=d?d.rows:[],h=n.length,p=[];for(i=0,r=u.length;r>i;i++){for(s={},c=!0,a=u[i].cells,o=0;h>o;o++)l=a[o],"th"!==l.nodeName.toLowerCase()&&(c=!1,s[n[o].field]=l.innerHTML);c||p.push(s)}return p}function H(e){return function(){var t=this._data,n=Y.fn[e].apply(this,Ht.call(arguments));return this._data!=t&&this._attachBubbleHandlers(),n -}}function B(t,n){function i(e,t){return e.filter(t).add(e.find(t))}var r,o,a,s,l,c,d,u,h=e(t).children(),p=[],f=n[0].field,g=n[1]&&n[1].field,m=n[2]&&n[2].field,v=n[3]&&n[3].field;for(r=0,o=h.length;o>r;r++)a={_loaded:!0},s=h.eq(r),c=s[0].firstChild,u=s.children(),t=u.filter("ul"),u=u.filter(":not(ul)"),l=s.attr("data-id"),l&&(a.id=l),c&&(a[f]=3==c.nodeType?c.nodeValue:u.text()),g&&(a[g]=i(u,"a").attr("href")),v&&(a[v]=i(u,"img").attr("src")),m&&(d=i(u,".k-sprite").prop("className"),a[m]=d&&e.trim(d.replace("k-sprite",""))),t.length&&(a.items=B(t.eq(0),n)),"true"==s.attr("data-hasChildren")&&(a.hasChildren=!0),p.push(a);return p}var L,N,O,V,U,W,j,G,q,$,Y,Q,K,X,Z,J,et=e.extend,tt=e.proxy,nt=e.isPlainObject,it=e.isEmptyObject,rt=e.isArray,ot=e.grep,at=e.ajax,st=e.each,lt=e.noop,ct=window.kendo,dt=ct.isFunction,ut=ct.Observable,ht=ct.Class,pt="string",ft="function",gt="create",mt="read",vt="update",_t="destroy",wt="change",bt="sync",yt="get",kt="error",xt="requestStart",Ct="progress",St="requestEnd",Tt=[gt,mt,vt,_t],Dt=function(e){return e},At=ct.getter,Et=ct.stringify,It=Math,Pt=[].push,Mt=[].join,zt=[].pop,Ft=[].splice,Rt=[].shift,Ht=[].slice,Bt=[].unshift,Lt={}.toString,Nt=ct.support.stableSort,Ot=/^\/Date\((.*?)\)\/$/,Vt=/(\r+|\n+)/g,Ut=/(?=['\\])/g,Wt=ut.extend({init:function(e,t){var n=this;n.type=t||Gt,ut.fn.init.call(n),n.length=e.length,n.wrapAll(e,n)},at:function(e){return this[e]},toJSON:function(){var e,t,n=this.length,i=Array(n);for(e=0;n>e;e++)t=this[e],t instanceof Gt&&(t=t.toJSON()),i[e]=t;return i},parent:lt,wrapAll:function(e,t){var n,i,r=this,o=function(){return r};for(t=t||[],n=0,i=e.length;i>n;n++)t[n]=r.wrap(e[n],o);return t},wrap:function(e,t){var n,i=this;return null!==e&&"[object Object]"===Lt.call(e)&&(n=e instanceof i.type||e instanceof Yt,n||(e=e instanceof Gt?e.toJSON():e,e=new i.type(e)),e.parent=t,e.bind(wt,function(e){i.trigger(wt,{field:e.field,node:e.node,index:e.index,items:e.items||[this],action:e.node?e.action||"itemloaded":"itemchange"})})),e},push:function(){var e,t=this.length,n=this.wrapAll(arguments);return e=Pt.apply(this,n),this.trigger(wt,{action:"add",index:t,items:n}),e},slice:Ht,sort:[].sort,join:Mt,pop:function(){var e=this.length,t=zt.apply(this);return e&&this.trigger(wt,{action:"remove",index:e-1,items:[t]}),t},splice:function(e,t,n){var i,r,o,a=this.wrapAll(Ht.call(arguments,2));if(i=Ft.apply(this,[e,t].concat(a)),i.length)for(this.trigger(wt,{action:"remove",index:e,items:i}),r=0,o=i.length;o>r;r++)i[r]&&i[r].children&&i[r].unbind(wt);return n&&this.trigger(wt,{action:"add",index:e,items:a}),i},shift:function(){var e=this.length,t=Rt.apply(this);return e&&this.trigger(wt,{action:"remove",index:0,items:[t]}),t},unshift:function(){var e,t=this.wrapAll(arguments);return e=Bt.apply(this,t),this.trigger(wt,{action:"add",index:0,items:t}),e},indexOf:function(e){var t,n,i=this;for(t=0,n=i.length;n>t;t++)if(i[t]===e)return t;return-1},forEach:function(e){for(var t=0,n=this.length;n>t;t++)e(this[t],t,this)},map:function(e){for(var t=0,n=[],i=this.length;i>t;t++)n[t]=e(this[t],t,this);return n},reduce:function(e){var t,n=0,i=this.length;for(2==arguments.length?t=arguments[1]:i>n&&(t=this[n++]);i>n;n++)t=e(t,this[n],n,this);return t},reduceRight:function(e){var t,n=this.length-1;for(2==arguments.length?t=arguments[1]:n>0&&(t=this[n--]);n>=0;n--)t=e(t,this[n],n,this);return t},filter:function(e){for(var t,n=0,i=[],r=this.length;r>n;n++)t=this[n],e(t,n,this)&&(i[i.length]=t);return i},find:function(e){for(var t,n=0,i=this.length;i>n;n++)if(t=this[n],e(t,n,this))return t},every:function(e){for(var t,n=0,i=this.length;i>n;n++)if(t=this[n],!e(t,n,this))return!1;return!0},some:function(e){for(var t,n=0,i=this.length;i>n;n++)if(t=this[n],e(t,n,this))return!0;return!1},remove:function(e){var t=this.indexOf(e);-1!==t&&this.splice(t,1)},empty:function(){this.splice(0,this.length)}}),jt=Wt.extend({init:function(e,t){ut.fn.init.call(this),this.type=t||Gt;for(var n=0;e.length>n;n++)this[n]=e[n];this.length=n,this._parent=tt(function(){return this},this)},at:function(e){var t=this[e];return t instanceof this.type?t.parent=this._parent:t=this[e]=this.wrap(t,this._parent),t}}),Gt=ut.extend({init:function(e){var t,n,i=this,r=function(){return i};ut.fn.init.call(this);for(n in e)t=e[n],"object"==typeof t&&t&&!t.getTime&&"_"!=n.charAt(0)&&(t=i.wrap(t,n,r)),i[n]=t;i.uid=ct.guid()},shouldSerialize:function(e){return this.hasOwnProperty(e)&&"_events"!==e&&typeof this[e]!==ft&&"uid"!==e},forEach:function(e){for(var t in this)this.shouldSerialize(t)&&e(this[t],t)},toJSON:function(){var e,t,n={};for(t in this)this.shouldSerialize(t)&&(e=this[t],(e instanceof Gt||e instanceof Wt)&&(e=e.toJSON()),n[t]=e);return n},get:function(e){var t,n=this;return n.trigger(yt,{field:e}),t="this"===e?n:ct.getter(e,!0)(n)},_set:function(e,t){var n,i,r,o=this,a=e.indexOf(".")>=0;if(a)for(n=e.split("."),i="";n.length>1;){if(i+=n.shift(),r=ct.getter(i,!0)(o),r instanceof Gt)return r.set(n.join("."),t),a;i+="."}return ct.setter(e)(o,t),a},set:function(e,t){var n=this,i=e.indexOf(".")>=0,r=ct.getter(e,!0)(n);r!==t&&(n.trigger("set",{field:e,value:t})||(i||(t=n.wrap(t,e,function(){return n})),(!n._set(e,t)||e.indexOf("(")>=0||e.indexOf("[")>=0)&&n.trigger(wt,{field:e})))},parent:lt,wrap:function(e,t,i){var r,o,a=this,s=Lt.call(e);return null==e||"[object Object]"!==s&&"[object Array]"!==s||(r=e instanceof Wt,o=e instanceof Y,"[object Object]"!==s||o||r?("[object Array]"===s||r||o)&&(r||o||(e=new Wt(e)),e.parent()!=i()&&e.bind(wt,n(a,wt,t,!1))):(e instanceof Gt||(e=new Gt(e)),e.parent()!=i()&&(e.bind(yt,n(a,yt,t,!0)),e.bind(wt,n(a,wt,t,!0)))),e.parent=i),e}}),qt={number:function(e){return ct.parseFloat(e)},date:function(e){return ct.parseDate(e)},"boolean":function(e){return typeof e===pt?"true"===e.toLowerCase():null!=e?!!e:e},string:function(e){return null!=e?e+"":e},"default":function(e){return e}},$t={string:"",number:0,date:new Date,"boolean":!1,"default":""},Yt=Gt.extend({init:function(n){var i,r,o=this;if((!n||e.isEmptyObject(n))&&(n=e.extend({},o.defaults,n),o._initializers))for(i=0;o._initializers.length>i;i++)r=o._initializers[i],n[r]=o.defaults[r]();Gt.fn.init.call(o,n),o.dirty=!1,o.idField&&(o.id=o.get(o.idField),o.id===t&&(o.id=o._defaultId))},shouldSerialize:function(e){return Gt.fn.shouldSerialize.call(this,e)&&"uid"!==e&&!("id"!==this.idField&&"id"===e)&&"dirty"!==e&&"_accessors"!==e},_parse:function(e,t){var n,i=this,o=e,a=i.fields||{};return e=a[e],e||(e=r(a,o)),e&&(n=e.parse,!n&&e.type&&(n=qt[e.type.toLowerCase()])),n?n(t):t},_notifyChange:function(e){var t=e.action;("add"==t||"remove"==t)&&(this.dirty=!0)},editable:function(e){return e=(this.fields||{})[e],e?e.editable!==!1:!0},set:function(e,t,n){var r=this;r.editable(e)&&(t=r._parse(e,t),i(t,r.get(e))||(r.dirty=!0,Gt.fn.set.call(r,e,t,n)))},accept:function(e){var t,n,i=this,r=function(){return i};for(t in e)n=e[t],"_"!=t.charAt(0)&&(n=i.wrap(e[t],t,r)),i._set(t,n);i.idField&&(i.id=i.get(i.idField)),i.dirty=!1},isNew:function(){return this.id===this._defaultId}});Yt.define=function(e,n){n===t&&(n=e,e=Yt);var i,r,o,a,s,l,c,d,u=et({defaults:{}},n),h={},p=u.id,f=[];if(p&&(u.idField=p),u.id&&delete u.id,p&&(u.defaults[p]=u._defaultId=""),"[object Array]"===Lt.call(u.fields)){for(l=0,c=u.fields.length;c>l;l++)o=u.fields[l],typeof o===pt?h[o]={}:o.field&&(h[o.field]=o);u.fields=h}for(r in u.fields)o=u.fields[r],a=o.type||"default",s=null,d=r,r=typeof o.field===pt?o.field:r,o.nullable||(s=u.defaults[d!==r?d:r]=o.defaultValue!==t?o.defaultValue:$t[a.toLowerCase()],"function"==typeof s&&f.push(r)),n.id===r&&(u._defaultId=s),u.defaults[d!==r?d:r]=s,o.parse=o.parse||qt[a];return f.length>0&&(u._initializers=f),i=e.extend(u),i.define=function(e){return Yt.define(i,e)},u.fields&&(i.fields=u.fields,i.idField=u.idField),i},N={selector:function(e){return dt(e)?e:At(e)},compare:function(e){var t=this.selector(e);return function(e,n){return e=t(e),n=t(n),null==e&&null==n?0:null==e?-1:null==n?1:e.localeCompare?e.localeCompare(n):e>n?1:n>e?-1:0}},create:function(e){var t=e.compare||this.compare(e.field);return"desc"==e.dir?function(e,n){return t(n,e,!0)}:t},combine:function(e){return function(t,n){var i,r,o=e[0](t,n);for(i=1,r=e.length;r>i;i++)o=o||e[i](t,n);return o}}},O=et({},N,{asc:function(e){var t=this.selector(e);return function(e,n){var i=t(e),r=t(n);return i&&i.getTime&&r&&r.getTime&&(i=i.getTime(),r=r.getTime()),i===r?e.__position-n.__position:null==i?-1:null==r?1:i.localeCompare?i.localeCompare(r):i>r?1:-1}},desc:function(e){var t=this.selector(e);return function(e,n){var i=t(e),r=t(n);return i&&i.getTime&&r&&r.getTime&&(i=i.getTime(),r=r.getTime()),i===r?e.__position-n.__position:null==i?1:null==r?-1:r.localeCompare?r.localeCompare(i):r>i?1:-1}},create:function(e){return this[e.dir](e.field)}}),L=function(e,t){var n,i=e.length,r=Array(i);for(n=0;i>n;n++)r[n]=t(e[n],n,e);return r},V=function(){function e(e){return e.replace(Ut,"\\").replace(Vt,"")}function t(t,n,i,r){var o;return null!=i&&(typeof i===pt&&(i=e(i),o=Ot.exec(i),o?i=new Date(+o[1]):r?(i="'"+i.toLowerCase()+"'",n="("+n+" || '').toLowerCase()"):i="'"+i+"'"),i.getTime&&(n="("+n+"?"+n+".getTime():"+n+")",i=i.getTime())),n+" "+t+" "+i}return{quote:function(t){return t&&t.getTime?"new Date("+t.getTime()+")":"string"==typeof t?"'"+e(t)+"'":""+t},eq:function(e,n,i){return t("==",e,n,i)},neq:function(e,n,i){return t("!=",e,n,i)},gt:function(e,n,i){return t(">",e,n,i)},gte:function(e,n,i){return t(">=",e,n,i)},lt:function(e,n,i){return t("<",e,n,i)},lte:function(e,n,i){return t("<=",e,n,i)},startswith:function(t,n,i){return i&&(t="("+t+" || '').toLowerCase()",n&&(n=n.toLowerCase())),n&&(n=e(n)),t+".lastIndexOf('"+n+"', 0) == 0"},endswith:function(t,n,i){return i&&(t="("+t+" || '').toLowerCase()",n&&(n=n.toLowerCase())),n&&(n=e(n)),t+".indexOf('"+n+"', "+t+".length - "+(n||"").length+") >= 0"},contains:function(t,n,i){return i&&(t="("+t+" || '').toLowerCase()",n&&(n=n.toLowerCase())),n&&(n=e(n)),t+".indexOf('"+n+"') >= 0"},doesnotcontain:function(t,n,i){return i&&(t="("+t+" || '').toLowerCase()",n&&(n=n.toLowerCase())),n&&(n=e(n)),t+".indexOf('"+n+"') == -1"}}}(),o.filterExpr=function(e){var n,i,r,a,s,l,c=[],d={and:" && ",or:" || "},u=[],h=[],p=e.filters;for(n=0,i=p.length;i>n;n++)r=p[n],s=r.field,l=r.operator,r.filters?(a=o.filterExpr(r),r=a.expression.replace(/__o\[(\d+)\]/g,function(e,t){return t=+t,"__o["+(h.length+t)+"]"}).replace(/__f\[(\d+)\]/g,function(e,t){return t=+t,"__f["+(u.length+t)+"]"}),h.push.apply(h,a.operators),u.push.apply(u,a.fields)):(typeof s===ft?(a="__f["+u.length+"](d)",u.push(s)):a=ct.expr(s),typeof l===ft?(r="__o["+h.length+"]("+a+", "+V.quote(r.value)+")",h.push(l)):r=V[(l||"eq").toLowerCase()](a,r.value,r.ignoreCase!==t?r.ignoreCase:!0)),c.push(r);return{expression:"("+c.join(d[e.logic])+")",fields:u,operators:h}},U={"==":"eq",equals:"eq",isequalto:"eq",equalto:"eq",equal:"eq","!=":"neq",ne:"neq",notequals:"neq",isnotequalto:"neq",notequalto:"neq",notequal:"neq","<":"lt",islessthan:"lt",lessthan:"lt",less:"lt","<=":"lte",le:"lte",islessthanorequalto:"lte",lessthanequal:"lte",">":"gt",isgreaterthan:"gt",greaterthan:"gt",greater:"gt",">=":"gte",isgreaterthanorequalto:"gte",greaterthanequal:"gte",ge:"gte",notsubstringof:"doesnotcontain"},o.normalizeFilter=l,o.prototype={toArray:function(){return this.data},range:function(e,t){return new o(this.data.slice(e,e+t))},skip:function(e){return new o(this.data.slice(e))},take:function(e){return new o(this.data.slice(0,e))},select:function(e){return new o(L(this.data,e))},order:function(e,t){var n={dir:t};return e&&(e.compare?n.compare=e.compare:n.field=e),new o(this.data.slice(0).sort(N.create(n)))},orderBy:function(e){return this.order(e,"asc")},orderByDescending:function(e){return this.order(e,"desc")},sort:function(e,t,n){var i,r,o=a(e,t),s=[];if(n=n||N,o.length){for(i=0,r=o.length;r>i;i++)s.push(n.create(o[i]));return this.orderBy({compare:n.combine(s)})}return this},filter:function(e){var t,n,i,r,a,s,c,d,u=this.data,h=[];if(e=l(e),!e||0===e.filters.length)return this;for(r=o.filterExpr(e),s=r.fields,c=r.operators,a=d=Function("d, __f, __o","return "+r.expression),(s.length||c.length)&&(d=function(e){return a(e,s,c)}),t=0,i=u.length;i>t;t++)n=u[t],d(n)&&h.push(n);return new o(h)},group:function(e,t){e=d(e||[]),t=t||this.data;var n,i=this,r=new o(i.data);return e.length>0&&(n=e[0],r=r.groupBy(n).select(function(i){var r=new o(t).filter([{field:i.field,operator:"eq",value:i.value,ignoreCase:!1}]);return{field:i.field,value:i.value,items:e.length>1?new o(i.items).group(e.slice(1),r.toArray()).toArray():i.items,hasSubgroups:e.length>1,aggregates:r.aggregate(n.aggregates)}})),r},groupBy:function(e){if(it(e)||!this.data.length)return new o([]);var t,n,i,r,a=e.field,s=this._sortForGrouping(a,e.dir||"asc"),l=ct.accessor(a),c=l.get(s[0],a),d={field:a,value:c,items:[]},h=[d];for(i=0,r=s.length;r>i;i++)t=s[i],n=l.get(t,a),u(c,n)||(c=n,d={field:a,value:c,items:[]},h.push(d)),d.items.push(t);return new o(h)},_sortForGrouping:function(e,t){var n,i,r=this.data;if(!Nt){for(n=0,i=r.length;i>n;n++)r[n].__position=n;for(r=new o(r).sort(e,t,O).toArray(),n=0,i=r.length;i>n;n++)delete r[n].__position;return r}return this.sort(e,t).toArray()},aggregate:function(e){var t,n,i={},r={};if(e&&e.length)for(t=0,n=this.data.length;n>t;t++)h(i,e,this.data[t],t,n,r);return i}},W={sum:function(e,t,n){var i=n.get(t);return p(e)?p(i)&&(e+=i):e=i,e},count:function(e){return(e||0)+1},average:function(e,n,i,r,o,a){var s=i.get(n);return a.count===t&&(a.count=0),p(e)?p(s)&&(e+=s):e=s,p(s)&&a.count++,r==o-1&&p(e)&&(e/=a.count),e},max:function(e,t,n){var i=n.get(t);return p(e)||f(e)||(e=i),i>e&&(p(i)||f(i))&&(e=i),e},min:function(e,t,n){var i=n.get(t);return p(e)||f(e)||(e=i),e>i&&(p(i)||f(i))&&(e=i),e}},o.process=function(e,n){n=n||{};var i,r=new o(e),s=n.group,l=d(s||[]).concat(a(n.sort||[])),c=n.filterCallback,u=n.filter,h=n.skip,p=n.take;return u&&(r=r.filter(u),c&&(r=c(r)),i=r.toArray().length),l&&(r=r.sort(l),s&&(e=r.toArray())),h!==t&&p!==t&&(r=r.range(h,p)),s&&(r=r.group(s,e)),{total:i,data:r.toArray()}},j=ht.extend({init:function(e){this.data=e.data},read:function(e){e.success(this.data)},update:function(e){e.success(e.data)},create:function(e){e.success(e.data)},destroy:function(e){e.success(e.data)}}),G=ht.extend({init:function(e){var t,n=this;e=n.options=et({},n.options,e),st(Tt,function(t,n){typeof e[n]===pt&&(e[n]={url:e[n]})}),n.cache=e.cache?q.create(e.cache):{find:lt,add:lt},t=e.parameterMap,dt(e.push)&&(n.push=e.push),n.push||(n.push=Dt),n.parameterMap=dt(t)?t:function(e){var n={};return st(e,function(e,i){e in t&&(e=t[e],nt(e)&&(i=e.value(i),e=e.key)),n[e]=i}),n}},options:{parameterMap:Dt},create:function(e){return at(this.setup(e,gt))},read:function(n){var i,r,o,a=this,s=a.cache;n=a.setup(n,mt),i=n.success||lt,r=n.error||lt,o=s.find(n.data),o!==t?i(o):(n.success=function(e){s.add(n.data,e),i(e)},e.ajax(n))},update:function(e){return at(this.setup(e,vt))},destroy:function(e){return at(this.setup(e,_t))},setup:function(e,t){e=e||{};var n,i=this,r=i.options[t],o=dt(r.data)?r.data(e.data):r.data;return e=et(!0,{},r,e),n=et(!0,{},o,e.data),e.data=i.parameterMap(n,t),dt(e.url)&&(e.url=e.url(n)),e}}),q=ht.extend({init:function(){this._store={}},add:function(e,n){e!==t&&(this._store[Et(e)]=n)},find:function(e){return this._store[Et(e)]},clear:function(){this._store={}},remove:function(e){delete this._store[Et(e)]}}),q.create=function(e){var t={inmemory:function(){return new q}};return nt(e)&&dt(e.find)?e:e===!0?new q:t[e]()},$=ht.extend({init:function(e){var t,n,i,r,o,a,s,l,c,d,u,h,p,f=this;e=e||{};for(t in e)n=e[t],f[t]=typeof n===pt?At(n):n;r=e.modelBase||Yt,nt(f.model)&&(f.model=i=r.define(f.model)),o=tt(f.data,f),f._dataAccessFunction=o,f.model&&(a=tt(f.groups,f),s=tt(f.serialize,f),l={},c={},d={},u={},h=!1,i=f.model,i.fields&&(st(i.fields,function(e,t){var n;p=e,nt(t)&&t.field?p=t.field:typeof t===pt&&(p=t),nt(t)&&t.from&&(n=t.from),h=h||n&&n!==e||p!==e,c[e]=At(n||p),d[e]=At(e),l[n||p]=e,u[e]=n||p}),!e.serialize&&h&&(f.serialize=w(s,i,m,d,l,u))),f._dataAccessFunction=o,f.data=w(o,i,v,c,l,u),f.groups=w(a,i,_,c,l,u))},errors:function(e){return e?e.errors:null},parse:Dt,data:Dt,total:function(e){return e.length},groups:Dt,aggregates:function(){return{}},serialize:function(e){return e}}),Y=ut.extend({init:function(e){var n,i,r,o=this;e&&(i=e.data),e=o.options=et({},o.options,e),o._map={},o._prefetch={},o._data=[],o._pristineData=[],o._ranges=[],o._view=[],o._pristineTotal=0,o._destroyed=[],o._pageSize=e.pageSize,o._page=e.page||(e.pageSize?1:t),o._sort=a(e.sort),o._filter=l(e.filter),o._group=d(e.group),o._aggregate=e.aggregate,o._total=e.total,o._shouldDetachObservableParents=!0,ut.fn.init.call(o),o.transport=Q.create(e,i,o),dt(o.transport.push)&&o.transport.push({pushCreate:tt(o._pushCreate,o),pushUpdate:tt(o._pushUpdate,o),pushDestroy:tt(o._pushDestroy,o)}),null!=e.offlineStorage&&("string"==typeof e.offlineStorage?(r=e.offlineStorage,o._storage={getItem:function(){return JSON.parse(localStorage.getItem(r))},setItem:function(e){localStorage.setItem(r,Et(o.reader.serialize(e)))}}):o._storage=e.offlineStorage),o.reader=new ct.data.readers[e.schema.type||"json"](e.schema),n=o.reader.model||{},o._detachObservableParents(),o._data=o._observe(o._data),o._online=!0,o.bind(["push",kt,wt,xt,bt,St,Ct],e)},options:{data:null,schema:{modelBase:Yt},offlineStorage:null,serverSorting:!1,serverPaging:!1,serverFiltering:!1,serverGrouping:!1,serverAggregates:!1,batch:!1},online:function(n){return n!==t?this._online!=n&&(this._online=n,n)?this.sync():e.Deferred().resolve().promise():this._online},offlineData:function(e){return null==this.options.offlineStorage?null:e!==t?this._storage.setItem(e):this._storage.getItem()||{}},_isServerGrouped:function(){var e=this.group()||[];return this.options.serverGrouping&&e.length},_pushCreate:function(e){this._push(e,"pushCreate")},_pushUpdate:function(e){this._push(e,"pushUpdate")},_pushDestroy:function(e){this._push(e,"pushDestroy")},_push:function(e,t){var n=this._readData(e);n||(n=e),this[t](n)},_flatData:function(e,t){if(e){if(this._isServerGrouped())return y(e);if(!t)for(var n=0;e.length>n;n++)e.at(n)}return e},parent:lt,get:function(e){var t,n,i=this._flatData(this._data);for(t=0,n=i.length;n>t;t++)if(i[t].id==e)return i[t]},getByUid:function(e){var t,n,i=this._flatData(this._data);if(i)for(t=0,n=i.length;n>t;t++)if(i[t].uid==e)return i[t]},indexOf:function(e){return E(this._data,e)},at:function(e){return this._data.at(e)},data:function(e){var n,i=this;if(e===t){if(i._data)for(n=0;i._data.length>n;n++)i._data.at(n);return i._data}i._detachObservableParents(),i._data=this._observe(e),i._pristineData=e.slice(0),i._storeData(),i._ranges=[],i.trigger("reset"),i._addRange(i._data),i._total=i._data.length,i._pristineTotal=i._total,i._process(i._data)},view:function(e){return e===t?this._view:(this._view=this._observeView(e),t)},_observeView:function(e){var t,n=this;return T(e,n._data,n._ranges,n.reader.model||Gt,n._isServerGrouped()),t=new jt(e,n.reader.model),t.parent=function(){return n.parent()},t},flatView:function(){var e=this.group()||[];return e.length?y(this._view):this._view},add:function(e){return this.insert(this._data.length,e)},_createNewModel:function(e){return this.reader.model?new this.reader.model(e):e instanceof Gt?e:new Gt(e)},insert:function(e,t){return t||(t=e,e=0),t instanceof Yt||(t=this._createNewModel(t)),this._isServerGrouped()?this._data.splice(e,0,this._wrapInEmptyGroup(t)):this._data.splice(e,0,t),t},pushCreate:function(e){var t,n,i,r,o,a;rt(e)||(e=[e]),t=[],n=this.options.autoSync,this.options.autoSync=!1;try{for(i=0;e.length>i;i++)r=e[i],o=this.add(r),t.push(o),a=o.toJSON(),this._isServerGrouped()&&(a=this._wrapInEmptyGroup(a)),this._pristineData.push(a)}finally{this.options.autoSync=n}t.length&&this.trigger("push",{type:"create",items:t})},pushUpdate:function(e){var t,n,i,r,o;for(rt(e)||(e=[e]),t=[],n=0;e.length>n;n++)i=e[n],r=this._createNewModel(i),o=this.get(r.id),o?(t.push(o),o.accept(i),o.trigger(wt),this._updatePristineForModel(o,i)):this.pushCreate(i);t.length&&this.trigger("push",{type:"update",items:t})},pushDestroy:function(e){var t=this._removeItems(e);t.length&&this.trigger("push",{type:"destroy",items:t})},_removeItems:function(e){var t,n,i,r,o,a;rt(e)||(e=[e]),t=[],n=this.options.autoSync,this.options.autoSync=!1;try{for(i=0;e.length>i;i++)r=e[i],o=this._createNewModel(r),a=!1,this._eachItem(this._data,function(e){var n,i;for(n=0;e.length>n;n++)if(i=e.at(n),i.id===o.id){t.push(i),e.splice(n,1),a=!0;break}}),a&&(this._removePristineForModel(o),this._destroyed.pop())}finally{this.options.autoSync=n}return t},remove:function(e){var n,i=this,r=i._isServerGrouped();return this._eachItem(i._data,function(o){return n=D(o,e),n&&r?(n.isNew&&n.isNew()||i._destroyed.push(n),!0):t}),this._removeModelFromRanges(e),this._updateRangesLength(),e},destroyed:function(){return this._destroyed},created:function(){var e,t,n=[],i=this._flatData(this._data);for(e=0,t=i.length;t>e;e++)i[e].isNew&&i[e].isNew()&&n.push(i[e]);return n},updated:function(){var e,t,n=[],i=this._flatData(this._data);for(e=0,t=i.length;t>e;e++)i[e].isNew&&!i[e].isNew()&&i[e].dirty&&n.push(i[e]);return n},sync:function(){var t,n=this,i=[],r=[],o=n._destroyed,a=(n._flatData(n._data),e.Deferred().resolve().promise());if(n.online()){if(!n.reader.model)return a;i=n.created(),r=n.updated(),t=[],n.options.batch&&n.transport.submit?t=n._sendSubmit(i,r,o):(t.push.apply(t,n._send("create",i)),t.push.apply(t,n._send("update",r)),t.push.apply(t,n._send("destroy",o))),a=e.when.apply(null,t).then(function(){var e,t;for(e=0,t=arguments.length;t>e;e++)n._accept(arguments[e]);n._storeData(!0),n._change({action:"sync"}),n.trigger(bt)})}else n._storeData(!0),n._change({action:"sync"});return a},cancelChanges:function(e){var t=this;e instanceof ct.data.Model?t._cancelModel(e):(t._destroyed=[],t._detachObservableParents(),t._data=t._observe(t._pristineData),t.options.serverPaging&&(t._total=t._pristineTotal),t._ranges=[],t._addRange(t._data),t._change())},hasChanges:function(){var e,t,n=this._flatData(this._data);if(this._destroyed.length)return!0;for(e=0,t=n.length;t>e;e++)if(n[e].isNew&&n[e].isNew()||n[e].dirty)return!0;return!1},_accept:function(t){var n,i=this,r=t.models,o=t.response,a=0,s=i._isServerGrouped(),l=i._pristineData,c=t.type;if(i.trigger(St,{response:o,type:c}),o&&!it(o)){if(o=i.reader.parse(o),i._handleCustomErrors(o))return;o=i.reader.data(o),rt(o)||(o=[o])}else o=e.map(r,function(e){return e.toJSON()});for("destroy"===c&&(i._destroyed=[]),a=0,n=r.length;n>a;a++)"destroy"!==c?(r[a].accept(o[a]),"create"===c?l.push(s?i._wrapInEmptyGroup(r[a]):o[a]):"update"===c&&i._updatePristineForModel(r[a],o[a])):i._removePristineForModel(r[a])},_updatePristineForModel:function(e,t){this._executeOnPristineForModel(e,function(e,n){ct.deepExtend(n[e],t)})},_executeOnPristineForModel:function(e,n){this._eachPristineItem(function(i){var r=A(i,e);return r>-1?(n(r,i),!0):t})},_removePristineForModel:function(e){this._executeOnPristineForModel(e,function(e,t){t.splice(e,1)})},_readData:function(e){var t=this._isServerGrouped()?this.reader.groups:this.reader.data;return t.call(this.reader,e)},_eachPristineItem:function(e){this._eachItem(this._pristineData,e)},_eachItem:function(e,t){e&&e.length&&(this._isServerGrouped()?x(e,t):t(e))},_pristineForModel:function(e){var n,i,r=function(r){return i=A(r,e),i>-1?(n=r[i],!0):t};return this._eachPristineItem(r),n},_cancelModel:function(e){var t=this._pristineForModel(e);this._eachItem(this._data,function(n){var i=E(n,e);i>=0&&(!t||e.isNew()&&!t.__state__?n.splice(i,1):n[i].accept(t))})},_submit:function(t,n){var i=this;i.trigger(xt,{type:"submit"}),i.transport.submit(et({success:function(n,i){var r=e.grep(t,function(e){return e.type==i})[0];r&&r.resolve({response:n,models:r.models,type:i})},error:function(e,n,r){for(var o=0;t.length>o;o++)t[o].reject(e);i.error(e,n,r)}},n))},_sendSubmit:function(t,n,i){var r=this,o=[];return r.options.batch&&(t.length&&o.push(e.Deferred(function(e){e.type="create",e.models=t})),n.length&&o.push(e.Deferred(function(e){e.type="update",e.models=n})),i.length&&o.push(e.Deferred(function(e){e.type="destroy",e.models=i})),r._submit(o,{data:{created:r.reader.serialize(g(t)),updated:r.reader.serialize(g(n)),destroyed:r.reader.serialize(g(i))}})),o},_promise:function(t,n,i){var r=this;return e.Deferred(function(e){r.trigger(xt,{type:i}),r.transport[i].call(r.transport,et({success:function(t){e.resolve({response:t,models:n,type:i})},error:function(t,n,i){e.reject(t),r.error(t,n,i)}},t))}).promise()},_send:function(e,t){var n,i,r=this,o=[],a=r.reader.serialize(g(t));if(r.options.batch)t.length&&o.push(r._promise({data:{models:a}},t,e));else for(n=0,i=t.length;i>n;n++)o.push(r._promise({data:a[n]},[t[n]],e));return o},read:function(t){var n=this,i=n._params(t),r=e.Deferred();return n._queueRequest(i,function(){var e=n.trigger(xt,{type:"read"});e?(n._dequeueRequest(),r.resolve(e)):(n.trigger(Ct),n._ranges=[],n.trigger("reset"),n.online()?n.transport.read({data:i,success:function(e){n.success(e,i),r.resolve()},error:function(){var e=Ht.call(arguments);n.error.apply(n,e),r.reject.apply(r,e)}}):null!=n.options.offlineStorage&&(n.success(n.offlineData(),i),r.resolve()))}),r.promise()},_readAggregates:function(e){return this.reader.aggregates(e)},success:function(e){var n,i,r,o,a,s,l,c,d=this,u=d.options;if(d.trigger(St,{response:e,type:"read"}),d.online()){if(e=d.reader.parse(e),d._handleCustomErrors(e))return d._dequeueRequest(),t;d._total=d.reader.total(e),d._aggregate&&u.serverAggregates&&(d._aggregateResult=d._readAggregates(e)),e=d._readData(e)}else{for(e=d._readData(e),n=[],i={},r=d.reader.model,o=r?r.idField:"id",a=0;this._destroyed.length>a;a++)s=this._destroyed[a][o],i[s]=s;for(a=0;e.length>a;a++)l=e[a],c=l.__state__,"destroy"==c?i[l[o]]||this._destroyed.push(this._createNewModel(l)):n.push(l);e=n,d._total=e.length}d._pristineTotal=d._total,d._pristineData=e.slice(0),d._detachObservableParents(),d._data=d._observe(e),null!=d.options.offlineStorage&&d._eachItem(d._data,function(e){var t,n;for(t=0;e.length>t;t++)n=e.at(t),"update"==n.__state__&&(n.dirty=!0)}),d._storeData(),d._addRange(d._data),d._process(d._data),d._dequeueRequest()},_detachObservableParents:function(){if(this._data&&this._shouldDetachObservableParents)for(var e=0;this._data.length>e;e++)this._data[e].parent&&(this._data[e].parent=lt)},_storeData:function(e){function t(e){var n,i,r,s=[];for(n=0;e.length>n;n++)i=e.at(n),r=i.toJSON(),o&&i.items?r.items=t(i.items):(r.uid=i.uid,a&&(i.isNew()?r.__state__="create":i.dirty&&(r.__state__="update"))),s.push(r);return s}var n,i,r,o=this._isServerGrouped(),a=this.reader.model;if(null!=this.options.offlineStorage){for(n=t(this._data),i=0;this._destroyed.length>i;i++)r=this._destroyed[i].toJSON(),r.__state__="destroy",n.push(r);this.offlineData(n),e&&(this._pristineData=n)}},_addRange:function(e){var t=this,n=t._skip||0,i=n+t._flatData(e,!0).length;t._ranges.push({start:n,end:i,data:e,timestamp:(new Date).getTime()}),t._ranges.sort(function(e,t){return e.start-t.start})},error:function(e,t,n){this._dequeueRequest(),this.trigger(St,{}),this.trigger(kt,{xhr:e,status:t,errorThrown:n})},_params:function(e){var t=this,n=et({take:t.take(),skip:t.skip(),page:t.page(),pageSize:t.pageSize(),sort:t._sort,filter:t._filter,group:t._group,aggregate:t._aggregate},e);return t.options.serverPaging||(delete n.take,delete n.skip,delete n.page,delete n.pageSize),t.options.serverGrouping?t.reader.model&&n.group&&(n.group=z(n.group,t.reader.model)):delete n.group,t.options.serverFiltering?t.reader.model&&n.filter&&(n.filter=M(n.filter,t.reader.model)):delete n.filter,t.options.serverSorting?t.reader.model&&n.sort&&(n.sort=z(n.sort,t.reader.model)):delete n.sort,t.options.serverAggregates?t.reader.model&&n.aggregate&&(n.aggregate=z(n.aggregate,t.reader.model)):delete n.aggregate,n},_queueRequest:function(e,n){var i=this;i._requestInProgress?i._pending={callback:tt(n,i),options:e}:(i._requestInProgress=!0,i._pending=t,n())},_dequeueRequest:function(){var e=this;e._requestInProgress=!1,e._pending&&e._queueRequest(e._pending.options,e._pending.callback)},_handleCustomErrors:function(e){if(this.reader.errors){var t=this.reader.errors(e);if(t)return this.trigger(kt,{xhr:null,status:"customerror",errorThrown:"custom error",errors:t}),!0}return!1},_shouldWrap:function(e){var t=this.reader.model;return t&&e.length?!(e[0]instanceof t):!1},_observe:function(e){var t,n=this,i=n.reader.model;return n._shouldDetachObservableParents=!0,e instanceof Wt?(n._shouldDetachObservableParents=!1,n._shouldWrap(e)&&(e.type=n.reader.model,e.wrapAll(e,e))):(t=n.pageSize()&&!n.options.serverPaging?jt:Wt,e=new t(e,n.reader.model),e.parent=function(){return n.parent()}),n._isServerGrouped()&&k(e,i),n._changeHandler&&n._data&&n._data instanceof Wt?n._data.unbind(wt,n._changeHandler):n._changeHandler=tt(n._change,n),e.bind(wt,n._changeHandler)},_change:function(e){var t,n,i,r=this,o=e?e.action:"";if("remove"===o)for(t=0,n=e.items.length;n>t;t++)e.items[t].isNew&&e.items[t].isNew()||r._destroyed.push(e.items[t]);!r.options.autoSync||"add"!==o&&"remove"!==o&&"itemchange"!==o?(i=parseInt(r._total,10),p(r._total)||(i=parseInt(r._pristineTotal,10)),"add"===o?i+=e.items.length:"remove"===o?i-=e.items.length:"itemchange"===o||"sync"===o||r.options.serverPaging?"sync"===o&&(i=r._pristineTotal=parseInt(r._total,10)):i=r._pristineTotal,r._total=i,r._process(r._data,e)):r.sync()},_calculateAggregates:function(e,t){t=t||{};var n=new o(e),i=t.aggregate,r=t.filter;return r&&(n=n.filter(r)),n.aggregate(i)},_process:function(e,n){var i,r=this,o={};r.options.serverPaging!==!0&&(o.skip=r._skip,o.take=r._take||r._pageSize,o.skip===t&&r._page!==t&&r._pageSize!==t&&(o.skip=(r._page-1)*r._pageSize)),r.options.serverSorting!==!0&&(o.sort=r._sort),r.options.serverFiltering!==!0&&(o.filter=r._filter),r.options.serverGrouping!==!0&&(o.group=r._group),r.options.serverAggregates!==!0&&(o.aggregate=r._aggregate,r._aggregateResult=r._calculateAggregates(e,o)),i=r._queryProcess(e,o),r.view(i.data),i.total===t||r.options.serverFiltering||(r._total=i.total),n=n||{},n.items=n.items||r._view,r.trigger(wt,n)},_queryProcess:function(e,t){return o.process(e,t)},_mergeState:function(e){var n=this;return e!==t&&(n._pageSize=e.pageSize,n._page=e.page,n._sort=e.sort,n._filter=e.filter,n._group=e.group,n._aggregate=e.aggregate,n._skip=e.skip,n._take=e.take,n._skip===t&&(n._skip=n.skip(),e.skip=n.skip()),n._take===t&&n._pageSize!==t&&(n._take=n._pageSize,e.take=n._take),e.sort&&(n._sort=e.sort=a(e.sort)),e.filter&&(n._filter=e.filter=l(e.filter)),e.group&&(n._group=e.group=d(e.group)),e.aggregate&&(n._aggregate=e.aggregate=c(e.aggregate))),e},query:function(n){var i,r,o=this.options.serverSorting||this.options.serverPaging||this.options.serverFiltering||this.options.serverGrouping||this.options.serverAggregates;return o||(this._data===t||0===this._data.length)&&!this._destroyed.length?this.read(this._mergeState(n)):(r=this.trigger(xt,{type:"read"}),r||(this.trigger(Ct),i=this._queryProcess(this._data,this._mergeState(n)),this.options.serverFiltering||(this._total=i.total!==t?i.total:this._data.length),this._aggregateResult=this._calculateAggregates(this._data,n),this.view(i.data),this.trigger(St,{type:"read"}),this.trigger(wt,{items:i.data})),e.Deferred().resolve(r).promise())},fetch:function(e){var t=this,n=function(n){n!==!0&&dt(e)&&e.call(t)};return this._query().then(n)},_query:function(e){var t=this;return t.query(et({},{page:t.page(),pageSize:t.pageSize(),sort:t.sort(),filter:t.filter(),group:t.group(),aggregate:t.aggregate()},e))},next:function(e){var n=this,i=n.page(),r=n.total();return e=e||{},!i||r&&i+1>n.totalPages()?t:(n._skip=i*n.take(),i+=1,e.page=i,n._query(e),i)},prev:function(e){var n=this,i=n.page();return e=e||{},i&&1!==i?(n._skip=n._skip-n.take(),i-=1,e.page=i,n._query(e),i):t -},page:function(e){var n,i=this;return e!==t?(e=It.max(It.min(It.max(e,1),i.totalPages()),1),i._query({page:e}),t):(n=i.skip(),n!==t?It.round((n||0)/(i.take()||1))+1:t)},pageSize:function(e){var n=this;return e!==t?(n._query({pageSize:e,page:1}),t):n.take()},sort:function(e){var n=this;return e!==t?(n._query({sort:e}),t):n._sort},filter:function(e){var n=this;return e===t?n._filter:(n._query({filter:e,page:1}),n.trigger("reset"),t)},group:function(e){var n=this;return e!==t?(n._query({group:e}),t):n._group},total:function(){return parseInt(this._total||0,10)},aggregate:function(e){var n=this;return e!==t?(n._query({aggregate:e}),t):n._aggregate},aggregates:function(){var e=this._aggregateResult;return it(e)&&(e=this._emptyAggregates(this.aggregate())),e},_emptyAggregates:function(e){var t,n,i={};if(!it(e))for(t={},rt(e)||(e=[e]),n=0;e.length>n;n++)t[e[n].aggregate]=0,i[e[n].field]=t;return i},_wrapInEmptyGroup:function(e){var t,n,i,r,o=this.group();for(i=o.length-1,r=0;i>=r;i--)n=o[i],t={value:e.get(n.field),field:n.field,items:t?[t]:[e],hasSubgroups:!!t,aggregates:this._emptyAggregates(n.aggregates)};return t},totalPages:function(){var e=this,t=e.pageSize()||e.total();return It.ceil((e.total()||0)/t)},inRange:function(e,t){var n=this,i=It.min(e+t,n.total());return!n.options.serverPaging&&n._data.length>0?!0:n._findRange(e,i).length>0},lastRange:function(){var e=this._ranges;return e[e.length-1]||{start:0,end:0,data:[]}},firstItemUid:function(){var e=this._ranges;return e.length&&e[0].data.length&&e[0].data[0].uid},enableRequestsInProgress:function(){this._skipRequestsInProgress=!1},_timeStamp:function(){return(new Date).getTime()},range:function(e,n){var i,r,o,a,s,l,c,d;if(this._currentRequestTimeStamp=this._timeStamp(),this._skipRequestsInProgress=!0,e=It.min(e||0,this.total()),i=this,r=It.max(It.floor(e/n),0)*n,o=It.min(r+n,i.total()),a=i._findRange(e,It.min(e+n,i.total())),a.length){i._pending=t,i._skip=e>i.skip()?It.min(o,(i.totalPages()-1)*i.take()):r,i._take=n,s=i.options.serverPaging,l=i.options.serverSorting,c=i.options.serverFiltering,d=i.options.serverAggregates;try{i.options.serverPaging=!0,i._isServerGrouped()||i.group()&&i.group().length||(i.options.serverSorting=!0),i.options.serverFiltering=!0,i.options.serverPaging=!0,i.options.serverAggregates=!0,s&&(i._detachObservableParents(),i._data=a=i._observe(a)),i._process(a)}finally{i.options.serverPaging=s,i.options.serverSorting=l,i.options.serverFiltering=c,i.options.serverAggregates=d}}else n!==t&&(i._rangeExists(r,o)?e>r&&i.prefetch(o,n,function(){i.range(e,n)}):i.prefetch(r,n,function(){e>r&&or;r++)if(i=_[r],e>=i.start&&i.end>=e){for(f=0,o=r;g>o;o++)if(i=_[o],p=v._flatData(i.data,!0),p.length&&e+f>=i.start&&(c=i.data,u=i.end,y||(m=d(v.group()||[]).concat(a(v.sort()||[])),h=v._queryProcess(i.data,{sort:m,filter:v.filter()}),p=c=h.data,h.total!==t&&(u=h.total)),s=0,e+f>i.start&&(s=e+f-i.start),l=p.length,u>n&&(l-=u-n),f+=l-s,w=v._mergeGroups(w,c,s,l),i.end>=n&&f==n-e))return w;break}return[]},_mergeGroups:function(e,t,n,i){if(this._isServerGrouped()){var r,o=t.toJSON();return e.length&&(r=e[e.length-1]),b(r,o,n,i),e.concat(o)}return e.concat(t.slice(n,i))},skip:function(){var e=this;return e._skip===t?e._page!==t?(e._page-1)*(e.take()||1):t:e._skip},take:function(){return this._take||this._pageSize},_prefetchSuccessHandler:function(e,t,n,i){var r=this,o=r._timeStamp();return function(a){var s,l,c,d=!1,u={start:e,end:t,data:[],timestamp:r._timeStamp()};if(r._dequeueRequest(),r.trigger(St,{response:a,type:"read"}),a=r.reader.parse(a),c=r._readData(a),c.length){for(s=0,l=r._ranges.length;l>s;s++)if(r._ranges[s].start===e){d=!0,u=r._ranges[s];break}d||r._ranges.push(u)}u.data=r._observe(c),u.end=u.start+r._flatData(u.data,!0).length,r._ranges.sort(function(e,t){return e.start-t.start}),r._total=r.reader.total(a),(i||o>=r._currentRequestTimeStamp||!r._skipRequestsInProgress)&&(n&&c.length?n():r.trigger(wt,{}))}},prefetch:function(e,t,n){var i=this,r=It.min(e+t,i.total()),o={take:t,skip:e,page:e/t+1,pageSize:t,sort:i._sort,filter:i._filter,group:i._group,aggregate:i._aggregate};i._rangeExists(e,r)?n&&n():(clearTimeout(i._timeout),i._timeout=setTimeout(function(){i._queueRequest(o,function(){i.trigger(xt,{type:"read"})?i._dequeueRequest():i.transport.read({data:i._params(o),success:i._prefetchSuccessHandler(e,r,n),error:function(){var e=Ht.call(arguments);i.error.apply(i,e)}})})},100))},_multiplePrefetch:function(e,t,n){var i=this,r=It.min(e+t,i.total()),o={take:t,skip:e,page:e/t+1,pageSize:t,sort:i._sort,filter:i._filter,group:i._group,aggregate:i._aggregate};i._rangeExists(e,r)?n&&n():i.trigger(xt,{type:"read"})||i.transport.read({data:i._params(o),success:i._prefetchSuccessHandler(e,r,n,!0)})},_rangeExists:function(e,t){var n,i,r=this,o=r._ranges;for(n=0,i=o.length;i>n;n++)if(e>=o[n].start&&o[n].end>=t)return!0;return!1},_removeModelFromRanges:function(e){var t,n,i,r,o;for(r=0,o=this._ranges.length;o>r&&(i=this._ranges[r],this._eachItem(i.data,function(i){t=D(i,e),t&&(n=!0)}),!n);r++);},_updateRangesLength:function(){var e,t,n,i,r=0;for(n=0,i=this._ranges.length;i>n;n++)e=this._ranges[n],e.start=e.start-r,t=this._flatData(e.data,!0).length,r=e.end-t,e.end=e.start+t}}),Q={},Q.create=function(e,t,n){var i,r=e.transport;return r?(r.read=typeof r.read===pt?{url:r.read}:r.read,n&&(r.dataSource=n),e.type&&(ct.data.transports=ct.data.transports||{},ct.data.schemas=ct.data.schemas||{},ct.data.transports[e.type]&&!nt(ct.data.transports[e.type])?i=new ct.data.transports[e.type](et(r,{data:t})):r=et(!0,{},ct.data.transports[e.type],r),e.schema=et(!0,{},ct.data.schemas[e.type],e.schema)),i||(i=dt(r.read)?r:new G(r))):i=new j({data:e.data||[]}),i},Y.create=function(e){(rt(e)||e instanceof Wt)&&(e={data:e});var n,i,r,o=e||{},a=o.data,s=o.fields,l=o.table,c=o.select,d={};if(a||!s||o.transport||(l?a=R(l,s):c&&(a=F(c,s),o.group===t&&a[0]&&a[0].optgroup!==t&&(o.group="optgroup"))),ct.data.Model&&s&&(!o.schema||!o.schema.model)){for(n=0,i=s.length;i>n;n++)r=s[n],r.type&&(d[r.field]=r);it(d)||(o.schema=et(!0,o.schema,{model:{fields:d}}))}return o.data=a,c=null,o.select=null,l=null,o.table=null,o instanceof Y?o:new Y(o)},K=Yt.define({idField:"id",init:function(e){var t=this,n=t.hasChildren||e&&e.hasChildren,i="items",r={};ct.data.Model.fn.init.call(t,e),typeof t.children===pt&&(i=t.children),r={schema:{data:i,model:{hasChildren:n,id:t.idField,fields:t.fields}}},typeof t.children!==pt&&et(r,t.children),r.data=e,n||(n=r.schema.data),typeof n===pt&&(n=ct.getter(n)),dt(n)&&(t.hasChildren=!!n.call(t,t)),t._childrenOptions=r,t.hasChildren&&t._initChildren(),t._loaded=!(!e||!e[i]&&!e._loaded)},_initChildren:function(){var e,t,n,i=this;i.children instanceof X||(e=i.children=new X(i._childrenOptions),t=e.transport,n=t.parameterMap,t.parameterMap=function(e,t){return e[i.idField||"id"]=i.id,n&&(e=n(e,t)),e},e.parent=function(){return i},e.bind(wt,function(e){e.node=e.node||i,i.trigger(wt,e)}),e.bind(kt,function(e){var t=i.parent();t&&(e.node=e.node||i,t.trigger(kt,e))}),i._updateChildrenField())},append:function(e){this._initChildren(),this.loaded(!0),this.children.add(e)},hasChildren:!1,level:function(){for(var e=this.parentNode(),t=0;e&&e.parentNode;)t++,e=e.parentNode?e.parentNode():null;return t},_updateChildrenField:function(){var e=this._childrenOptions.schema.data;this[e||"items"]=this.children.data()},_childrenLoaded:function(){this._loaded=!0,this._updateChildrenField()},load:function(){var n,i,r={},o="_query";return this.hasChildren?(this._initChildren(),n=this.children,r[this.idField||"id"]=this.id,this._loaded||(n._data=t,o="read"),n.one(wt,tt(this._childrenLoaded,this)),i=n[o](r)):this.loaded(!0),i||e.Deferred().resolve().promise()},parentNode:function(){var e=this.parent();return e.parent()},loaded:function(e){return e===t?this._loaded:(this._loaded=e,t)},shouldSerialize:function(e){return Yt.fn.shouldSerialize.call(this,e)&&"children"!==e&&"_loaded"!==e&&"hasChildren"!==e&&"_childrenOptions"!==e}}),X=Y.extend({init:function(e){var t=K.define({children:e});Y.fn.init.call(this,et(!0,{},{schema:{modelBase:t,model:t}},e)),this._attachBubbleHandlers()},_attachBubbleHandlers:function(){var e=this;e._data.bind(kt,function(t){e.trigger(kt,t)})},remove:function(e){var t,n=e.parentNode(),i=this;return n&&n._initChildren&&(i=n.children),t=Y.fn.remove.call(i,e),n&&!i.data().length&&(n.hasChildren=!1),t},success:H("success"),data:H("data"),insert:function(e,t){var n=this.parent();return n&&n._initChildren&&(n.hasChildren=!0,n._initChildren()),Y.fn.insert.call(this,e,t)},_find:function(e,t){var n,i,r,o,a;if(r=Y.fn[e].call(this,t))return r;if(o=this._flatData(this._data))for(n=0,i=o.length;i>n;n++)if(a=o[n].children,a instanceof X&&(r=a[e](t)))return r},get:function(e){return this._find("get",e)},getByUid:function(e){return this._find("getByUid",e)}}),X.create=function(e){e=e&&e.push?{data:e}:e;var t=e||{},n=t.data,i=t.fields,r=t.list;return n&&n._dataSource?n._dataSource:(n||!i||t.transport||r&&(n=B(r,i)),t.data=n,t instanceof X?t:new X(t))},Z=ct.Observable.extend({init:function(e,t,n){ct.Observable.fn.init.call(this),this._prefetching=!1,this.dataSource=e,this.prefetch=!n;var i=this;e.bind("change",function(){i._change()}),e.bind("reset",function(){i._reset()}),this._syncWithDataSource(),this.setViewSize(t)},setViewSize:function(e){this.viewSize=e,this._recalculate()},at:function(e){var n=this.pageSize,i=!0;return e>=this.total()?(this.trigger("endreached",{index:e}),null):this.useRanges?this.useRanges?((this.dataOffset>e||e>=this.skip+n)&&(i=this.range(Math.floor(e/n)*n)),e===this.prefetchThreshold&&this._prefetch(),e===this.midPageThreshold?this.range(this.nextMidRange,!0):e===this.nextPageThreshold?this.range(this.nextFullRange):e===this.pullBackThreshold&&this.range(this.offset===this.skip?this.previousMidRange:this.previousFullRange),i?this.dataSource.at(e-this.dataOffset):(this.trigger("endreached",{index:e}),null)):t:this.dataSource.view()[e]},indexOf:function(e){return this.dataSource.data().indexOf(e)+this.dataOffset},total:function(){return parseInt(this.dataSource.total(),10)},next:function(){var e=this,t=e.pageSize,n=e.skip-e.viewSize+t,i=It.max(It.floor(n/t),0)*t;this.offset=n,this.dataSource.prefetch(i,t,function(){e._goToRange(n,!0)})},range:function(e,t){if(this.offset===e)return!0;var n=this,i=this.pageSize,r=It.max(It.floor(e/i),0)*i,o=this.dataSource;return t&&(r+=i),o.inRange(e,i)?(this.offset=e,this._recalculate(),this._goToRange(e),!0):this.prefetch?(o.prefetch(r,i,function(){n.offset=e,n._recalculate(),n._goToRange(e,!0)}),!1):!0},syncDataSource:function(){var e=this.offset;this.offset=null,this.range(e)},destroy:function(){this.unbind()},_prefetch:function(){var e=this,t=this.pageSize,n=this.skip+t,i=this.dataSource;i.inRange(n,t)||this._prefetching||!this.prefetch||(this._prefetching=!0,this.trigger("prefetching",{skip:n,take:t}),i.prefetch(n,t,function(){e._prefetching=!1,e.trigger("prefetched",{skip:n,take:t})}))},_goToRange:function(e,t){this.offset===e&&(this.dataOffset=e,this._expanding=t,this.dataSource.range(e,this.pageSize),this.dataSource.enableRequestsInProgress())},_reset:function(){this._syncPending=!0},_change:function(){var e=this.dataSource;this.length=this.useRanges?e.lastRange().end:e.view().length,this._syncPending&&(this._syncWithDataSource(),this._recalculate(),this._syncPending=!1,this.trigger("reset",{offset:this.offset})),this.trigger("resize"),this._expanding&&this.trigger("expand"),delete this._expanding},_syncWithDataSource:function(){var e=this.dataSource;this._firstItemUid=e.firstItemUid(),this.dataOffset=this.offset=e.skip()||0,this.pageSize=e.pageSize(),this.useRanges=e.options.serverPaging},_recalculate:function(){var e=this.pageSize,t=this.offset,n=this.viewSize,i=Math.ceil(t/e)*e;this.skip=i,this.midPageThreshold=i+e-1,this.nextPageThreshold=i+n-1,this.prefetchThreshold=i+Math.floor(e/3*2),this.pullBackThreshold=this.offset-1,this.nextMidRange=i+e-n,this.nextFullRange=i,this.previousMidRange=t-n,this.previousFullRange=i-e}}),J=ct.Observable.extend({init:function(e,t){var n=this;ct.Observable.fn.init.call(n),this.dataSource=e,this.batchSize=t,this._total=0,this.buffer=new Z(e,3*t),this.buffer.bind({endreached:function(e){n.trigger("endreached",{index:e.index})},prefetching:function(e){n.trigger("prefetching",{skip:e.skip,take:e.take})},prefetched:function(e){n.trigger("prefetched",{skip:e.skip,take:e.take})},reset:function(){n._total=0,n.trigger("reset")},resize:function(){n._total=Math.ceil(this.length/n.batchSize),n.trigger("resize",{total:n.total(),offset:this.offset})}})},syncDataSource:function(){this.buffer.syncDataSource()},at:function(e){var t,n,i=this.buffer,r=e*this.batchSize,o=this.batchSize,a=[];for(i.offset>r&&i.at(i.offset-1),n=0;o>n&&(t=i.at(r+n),null!==t);n++)a.push(t);return a},total:function(){return this._total},destroy:function(){this.buffer.destroy(),this.unbind()}}),et(!0,ct.data,{readers:{json:$},Query:o,DataSource:Y,HierarchicalDataSource:X,Node:K,ObservableObject:Gt,ObservableArray:Wt,LazyObservableArray:jt,LocalTransport:j,RemoteTransport:G,Cache:q,DataReader:$,Model:Yt,Buffer:Z,BatchBuffer:J})}(window.kendo.jQuery),function(e,t){function n(t,n,i){return v.extend({init:function(e,t,n){var i=this;v.fn.init.call(i,e.element[0],t,n),i.widget=e,i._dataBinding=P(i.dataBinding,i),i._dataBound=P(i.dataBound,i),i._itemChange=P(i.itemChange,i)},itemChange:function(e){a(e.item[0],e.data,this._ns(e.ns),[e.data].concat(this.bindings[t]._parents()))},dataBinding:function(e){var t,n,i=this.widget,r=e.removedItems||i.items();for(t=0,n=r.length;n>t;t++)c(r[t])},_ns:function(t){t=t||C.ui;var n=[C.ui,C.dataviz.ui,C.mobile.ui];return n.splice(e.inArray(t,n),1),n.unshift(t),C.rolesFromNamespaces(n)},dataBound:function(e){var i,r,o,s,l=this.widget,c=e.addedItems||l.items(),d=l[n],u=(d.group()||[],C.data.HierarchicalDataSource);if(!(u&&d instanceof u)&&c.length)for(o=e.addedDataItems||d.flatView(),s=this.bindings[t]._parents(),i=0,r=o.length;r>i;i++)a(c[i],o[i],this._ns(e.ns),[o[i]].concat(s))},refresh:function(e){var r,o=this,a=o.widget;e=e||{},e.action||(o.destroy(),a.bind("dataBinding",o._dataBinding),a.bind("dataBound",o._dataBound),a.bind("itemChange",o._itemChange),r=o.bindings[t].get(),a[n]instanceof C.data.DataSource&&a[n]!=r&&(r instanceof C.data.DataSource?a[i](r):r&&r._dataSource?a[i](r._dataSource):(a[n].data(r),o.bindings.value&&(a instanceof C.ui.Select||a instanceof C.ui.MultiSelect)&&a.value(p(o.bindings.value.get(),a.options.dataValueField)))))},destroy:function(){var e=this.widget;e.unbind("dataBinding",this._dataBinding),e.unbind("dataBound",this._dataBound),e.unbind("itemChange",this._itemChange)}})}function i(e,n){var i=C.initWidget(e,{},n);return i?new y(i):t}function r(e){var t,n,i,o,a,s,l,c={};for(l=e.match(k),t=0,n=l.length;n>t;t++)i=l[t],o=i.indexOf(":"),a=i.substring(0,o),s=i.substring(o+1),"{"==s.charAt(0)&&(s=r(s)),c[a]=s;return c}function o(e,t,n){var i,r={};for(i in e)r[i]=new n(t,e[i]);return r}function a(e,t,n,s){var c,d,u,h=e.getAttribute("data-"+C.ns+"role"),p=e.getAttribute("data-"+C.ns+"bind"),v=e.children,_=[],w=!0,y={};if(s=s||[t],(h||p)&&l(e),h&&(u=i(e,n)),p&&(p=r(p.replace(x,"")),u||(y=C.parseOptions(e,{textField:"",valueField:"",template:"",valueUpdate:L,valuePrimitive:!1,autoBind:!0}),y.roles=n,u=new b(e,y)),u.source=t,d=o(p,s,f),y.template&&(d.template=new m(s,"",y.template)),d.click&&(p.events=p.events||{},p.events.click=p.click,d.click.destroy(),delete d.click),d.source&&(w=!1),p.attr&&(d.attr=o(p.attr,s,f)),p.style&&(d.style=o(p.style,s,f)),p.events&&(d.events=o(p.events,s,g)),p.css&&(d.css=o(p.css,s,f)),u.bind(d)),u&&(e.kendoBindingTarget=u),w&&v){for(c=0;v.length>c;c++)_[c]=v[c];for(c=0;_.length>c;c++)a(_[c],t,n,s)}}function s(t,n){var i,r,o,s=C.rolesFromNamespaces([].slice.call(arguments,2));for(n=C.observable(n),t=e(t),i=0,r=t.length;r>i;i++)o=t[i],1===o.nodeType&&a(o,n,s)}function l(e){var t=e.kendoBindingTarget;t&&(t.destroy(),B?delete e.kendoBindingTarget:e.removeAttribute?e.removeAttribute("kendoBindingTarget"):e.kendoBindingTarget=null)}function c(e){l(e),d(e)}function d(e){var t,n,i=e.children;if(i)for(t=0,n=i.length;n>t;t++)c(i[t])}function u(t){var n,i;for(t=e(t),n=0,i=t.length;i>n;n++)c(t[n])}function h(e,t){var n=e.element,i=n[0].kendoBindingTarget;i&&s(n,i.source,t)}function p(e,t){var n,i,r=[],o=0;if(!t)return e;if(e instanceof D){for(n=e.length;n>o;o++)i=e[o],r[o]=i.get?i.get(t):i[t];e=r}else e instanceof T&&(e=e.get(t));return e}var f,g,m,v,_,w,b,y,k,x,C=window.kendo,S=C.Observable,T=C.data.ObservableObject,D=C.data.ObservableArray,A={}.toString,E={},I=C.Class,P=e.proxy,M="value",z="source",F="events",R="checked",H="css",B=!0,L="change";!function(){var e=document.createElement("a");try{delete e.test}catch(t){B=!1}}(),f=S.extend({init:function(e,t){var n=this;S.fn.init.call(n),n.source=e[0],n.parents=e,n.path=t,n.dependencies={},n.dependencies[t]=!0,n.observable=n.source instanceof S,n._access=function(e){n.dependencies[e.field]=!0},n.observable&&(n._change=function(e){n.change(e)},n.source.bind(L,n._change))},_parents:function(){var t,n=this.parents,i=this.get();return i&&"function"==typeof i.parent&&(t=i.parent(),e.inArray(t,n)<0&&(n=[t].concat(n))),n},change:function(e){var t,n,i=e.field,r=this;if("this"===r.path)r.trigger(L,e);else for(t in r.dependencies)if(0===t.indexOf(i)&&(n=t.charAt(i.length),!n||"."===n||"["===n)){r.trigger(L,e);break}},start:function(e){e.bind("get",this._access)},stop:function(e){e.unbind("get",this._access)},get:function(){var e=this,n=e.source,i=0,r=e.path,o=n;if(!e.observable)return o;for(e.start(e.source),o=n.get(r);o===t&&n;)n=e.parents[++i],n instanceof T&&(o=n.get(r));if(o===t)for(n=e.source;o===t&&n;)n=n.parent(),n instanceof T&&(o=n.get(r));return"function"==typeof o&&(i=r.lastIndexOf("."),i>0&&(n=n.get(r.substring(0,i))),e.start(n),o=n!==e.source?o.call(n,e.source):o.call(n),e.stop(n)),n&&n!==e.source&&(e.currentSource=n,n.unbind(L,e._change).bind(L,e._change)),e.stop(e.source),o},set:function(e){var t=this.currentSource||this.source,n=C.getter(this.path)(t);"function"==typeof n?t!==this.source?n.call(t,this.source,e):n.call(t,e):t.set(this.path,e)},destroy:function(){this.observable&&(this.source.unbind(L,this._change),this.currentSource&&this.currentSource.unbind(L,this._change)),this.unbind()}}),g=f.extend({get:function(){var e,t=this.source,n=this.path,i=0;for(e=t.get(n);!e&&t;)t=this.parents[++i],t instanceof T&&(e=t.get(n));return P(e,t)}}),m=f.extend({init:function(e,t,n){var i=this;f.fn.init.call(i,e,t),i.template=n},render:function(e){var t;return this.start(this.source),t=C.render(this.template,e),this.stop(this.source),t}}),v=I.extend({init:function(e,t,n){this.element=e,this.bindings=t,this.options=n},bind:function(e,t){var n=this;e=t?e[t]:e,e.bind(L,function(e){n.refresh(t||e)}),n.refresh(t)},destroy:function(){}}),_=v.extend({dataType:function(){var e=this.element.getAttribute("data-type")||this.element.type||"text";return e.toLowerCase()},parsedValue:function(){return this._parseValue(this.element.value,this.dataType())},_parseValue:function(e,t){return"date"==t?e=C.parseDate(e,"yyyy-MM-dd"):"datetime-local"==t?e=C.parseDate(e,["yyyy-MM-ddTHH:mm:ss","yyyy-MM-ddTHH:mm"]):"number"==t?e=C.parseFloat(e):"boolean"==t&&(e=e.toLowerCase(),e=null!==C.parseFloat(e)?!!C.parseFloat(e):"true"===e.toLowerCase()),e}}),E.attr=v.extend({refresh:function(e){this.element.setAttribute(e,this.bindings.attr[e].get())}}),E.css=v.extend({init:function(e,t,n){v.fn.init.call(this,e,t,n),this.classes={}},refresh:function(t){var n=e(this.element),i=this.bindings.css[t],r=this.classes[t]=i.get();r?n.addClass(t):n.removeClass(t)}}),E.style=v.extend({refresh:function(e){this.element.style[e]=this.bindings.style[e].get()||""}}),E.enabled=v.extend({refresh:function(){this.bindings.enabled.get()?this.element.removeAttribute("disabled"):this.element.setAttribute("disabled","disabled")}}),E.readonly=v.extend({refresh:function(){this.bindings.readonly.get()?this.element.setAttribute("readonly","readonly"):this.element.removeAttribute("readonly")}}),E.disabled=v.extend({refresh:function(){this.bindings.disabled.get()?this.element.setAttribute("disabled","disabled"):this.element.removeAttribute("disabled")}}),E.events=v.extend({init:function(e,t,n){v.fn.init.call(this,e,t,n),this.handlers={}},refresh:function(t){var n=e(this.element),i=this.bindings.events[t],r=this.handlers[t];r&&n.off(t,r),r=this.handlers[t]=i.get(),n.on(t,i.source,r)},destroy:function(){var t,n=e(this.element);for(t in this.handlers)n.off(t,this.handlers[t])}}),E.text=v.extend({refresh:function(){var t=this.bindings.text.get(),n=this.element.getAttribute("data-format")||"";null==t&&(t=""),e(this.element).text(C.toString(t,n))}}),E.visible=v.extend({refresh:function(){this.element.style.display=this.bindings.visible.get()?"":"none"}}),E.invisible=v.extend({refresh:function(){this.element.style.display=this.bindings.invisible.get()?"none":""}}),E.html=v.extend({refresh:function(){this.element.innerHTML=this.bindings.html.get()}}),E.value=_.extend({init:function(t,n,i){_.fn.init.call(this,t,n,i),this._change=P(this.change,this),this.eventName=i.valueUpdate||L,e(this.element).on(this.eventName,this._change),this._initChange=!1},change:function(){this._initChange=this.eventName!=L,this.bindings[M].set(this.parsedValue()),this._initChange=!1},refresh:function(){var e,t;this._initChange||(e=this.bindings[M].get(),null==e&&(e=""),t=this.dataType(),"date"==t?e=C.toString(e,"yyyy-MM-dd"):"datetime-local"==t&&(e=C.toString(e,"yyyy-MM-ddTHH:mm:ss")),this.element.value=e),this._initChange=!1},destroy:function(){e(this.element).off(this.eventName,this._change)}}),E.source=v.extend({init:function(e,t,n){v.fn.init.call(this,e,t,n);var i=this.bindings.source.get();i instanceof C.data.DataSource&&n.autoBind!==!1&&i.fetch()},refresh:function(e){var t=this,n=t.bindings.source.get();n instanceof D||n instanceof C.data.DataSource?(e=e||{},"add"==e.action?t.add(e.index,e.items):"remove"==e.action?t.remove(e.index,e.items):"itemchange"!=e.action&&t.render()):t.render()},container:function(){var e=this.element;return"table"==e.nodeName.toLowerCase()&&(e.tBodies[0]||e.appendChild(document.createElement("tbody")),e=e.tBodies[0]),e},template:function(){var e=this.options,t=e.template,n=this.container().nodeName.toLowerCase();return t||(t="select"==n?e.valueField||e.textField?C.format('',e.valueField||e.textField,e.textField||e.valueField):"":"tbody"==n?"#:data#":"ul"==n||"ol"==n?"
  • #:data#
  • ":"#:data#",t=C.template(t)),t},add:function(t,n){var i,r,o,s,l=this.container(),c=l.cloneNode(!1),d=l.children[t];if(e(c).html(C.render(this.template(),n)),c.children.length)for(i=this.bindings.source._parents(),r=0,o=n.length;o>r;r++)s=c.children[0],l.insertBefore(s,d||null),a(s,n[r],this.options.roles,[n[r]].concat(i))},remove:function(e,t){var n,i,r=this.container();for(n=0;t.length>n;n++)i=r.children[e],c(i),r.removeChild(i)},render:function(){var t,n,i,r=this.bindings.source.get(),o=this.container(),s=this.template();if(r instanceof C.data.DataSource&&(r=r.view()),r instanceof D||"[object Array]"===A.call(r)||(r=[r]),this.bindings.template){if(d(o),e(o).html(this.bindings.template.render(r)),o.children.length)for(t=this.bindings.source._parents(),n=0,i=r.length;i>n;n++)a(o.children[n],r[n],this.options.roles,[r[n]].concat(t))}else e(o).html(C.render(s,r))}}),E.input={checked:_.extend({init:function(t,n,i){_.fn.init.call(this,t,n,i),this._change=P(this.change,this),e(this.element).change(this._change)},change:function(){var e,t,n,i=this.element,r=this.value();if("radio"==i.type)r=this.parsedValue(),this.bindings[R].set(r);else if("checkbox"==i.type)if(e=this.bindings[R].get(),e instanceof D){if(r=this.parsedValue(),r instanceof Date){for(n=0;e.length>n;n++)if(e[n]instanceof Date&&+e[n]===+r){t=n;break}}else t=e.indexOf(r);t>-1?e.splice(t,1):e.push(r)}else this.bindings[R].set(r)},refresh:function(){var e,t,n=this.bindings[R].get(),i=n,r=this.dataType(),o=this.element;if("checkbox"==o.type)if(i instanceof D){if(e=-1,n=this.parsedValue(),n instanceof Date){for(t=0;i.length>t;t++)if(i[t]instanceof Date&&+i[t]===+n){e=t;break}}else e=i.indexOf(n);o.checked=e>=0}else o.checked=i;else"radio"==o.type&&null!=n&&("date"==r?n=C.toString(n,"yyyy-MM-dd"):"datetime-local"==r&&(n=C.toString(n,"yyyy-MM-ddTHH:mm:ss")),o.value===""+n&&(o.checked=!0))},value:function(){var e=this.element,t=e.value;return"checkbox"==e.type&&(t=e.checked),t},destroy:function(){e(this.element).off(L,this._change)}})},E.select={source:E.source.extend({refresh:function(n){var i=this,r=i.bindings.source.get();r instanceof D||r instanceof C.data.DataSource?(n=n||{},"add"==n.action?i.add(n.index,n.items):"remove"==n.action?i.remove(n.index,n.items):("itemchange"==n.action||n.action===t)&&(i.render(),i.bindings.value&&i.bindings.value&&(i.element.value=p(i.bindings.value.get(),e(i.element).data("valueField"))))):i.render()}}),value:_.extend({init:function(t,n,i){_.fn.init.call(this,t,n,i),this._change=P(this.change,this),e(this.element).change(this._change)},parsedValue:function(){var e,t,n,i,r=this.dataType(),o=[];for(n=0,i=this.element.options.length;i>n;n++)t=this.element.options[n],t.selected&&(e=t.attributes.value,e=e&&e.specified?t.value:t.text,o.push(this._parseValue(e,r)));return o},change:function(){var e,n,i,r,o,a,s=[],l=this.options.valueField||this.options.textField,c=this.options.valuePrimitive;if(s=this.parsedValue(),l)for(e=this.bindings.source.get(),e instanceof C.data.DataSource&&(e=e.view()),n=0;s.length>n;n++)for(r=0,o=e.length;o>r;r++)if(a=c?this._parseValue(s[n],this.dataType())===e[r].get(l):""+this._parseValue(e[r].get(l),this.dataType())===s[n]){s[n]=e[r];break}i=this.bindings[M].get(),i instanceof D?i.splice.apply(i,[0,i.length].concat(s)):this.bindings[M].set(c||!(i instanceof T||null===i||i===t)&&l?s[0].get(l):s[0])},refresh:function(){var e,t,n,i=this.element,r=i.options,o=this.bindings[M].get(),a=o,s=this.options.valueField||this.options.textField,l=!1,c=this.dataType();for(a instanceof D||(a=new D([o])),i.selectedIndex=-1,n=0;a.length>n;n++)for(o=a[n],s&&o instanceof T&&(o=o.get(s)),"date"==c?o=C.toString(a[n],"yyyy-MM-dd"):"datetime-local"==c&&(o=C.toString(a[n],"yyyy-MM-ddTHH:mm:ss")),e=0;r.length>e;e++)t=r[e].value,""===t&&""!==o&&(t=r[e].text),null!=o&&t==""+o&&(r[e].selected=!0,l=!0)},destroy:function(){e(this.element).off(L,this._change)}})},E.widget={events:v.extend({init:function(e,t,n){v.fn.init.call(this,e.element[0],t,n),this.widget=e,this.handlers={}},refresh:function(e){var t=this.bindings.events[e],n=this.handlers[e];n&&this.widget.unbind(e,n),n=t.get(),this.handlers[e]=function(e){e.data=t.source,n(e),e.data===t.source&&delete e.data},this.widget.bind(e,this.handlers[e])},destroy:function(){var e;for(e in this.handlers)this.widget.unbind(e,this.handlers[e])}}),checked:v.extend({init:function(e,t,n){v.fn.init.call(this,e.element[0],t,n),this.widget=e,this._change=P(this.change,this),this.widget.bind(L,this._change)},change:function(){this.bindings[R].set(this.value())},refresh:function(){this.widget.check(this.bindings[R].get()===!0)},value:function(){var e=this.element,t=e.value;return("on"==t||"off"==t)&&(t=e.checked),t},destroy:function(){this.widget.unbind(L,this._change)}}),visible:v.extend({init:function(e,t,n){v.fn.init.call(this,e.element[0],t,n),this.widget=e},refresh:function(){var e=this.bindings.visible.get();this.widget.wrapper[0].style.display=e?"":"none"}}),invisible:v.extend({init:function(e,t,n){v.fn.init.call(this,e.element[0],t,n),this.widget=e},refresh:function(){var e=this.bindings.invisible.get();this.widget.wrapper[0].style.display=e?"none":""}}),enabled:v.extend({init:function(e,t,n){v.fn.init.call(this,e.element[0],t,n),this.widget=e},refresh:function(){this.widget.enable&&this.widget.enable(this.bindings.enabled.get())}}),disabled:v.extend({init:function(e,t,n){v.fn.init.call(this,e.element[0],t,n),this.widget=e},refresh:function(){this.widget.enable&&this.widget.enable(!this.bindings.disabled.get())}}),source:n("source","dataSource","setDataSource"),value:v.extend({init:function(t,n,i){v.fn.init.call(this,t.element[0],n,i),this.widget=t,this._change=e.proxy(this.change,this),this.widget.first(L,this._change);var r=this.bindings.value.get();this._valueIsObservableObject=!i.valuePrimitive&&(null==r||r instanceof T),this._valueIsObservableArray=r instanceof D,this._initChange=!1},change:function(){var e,t,n,i,r,o,a,s=this.widget.value(),l=this.options.dataValueField||this.options.dataTextField,c="[object Array]"===A.call(s),d=this._valueIsObservableObject,u=[];if(this._initChange=!0,l)if(this.bindings.source&&(a=this.bindings.source.get()),""===s&&(d||this.options.valuePrimitive))s=null;else{for((!a||a instanceof C.data.DataSource)&&(a=this.widget.dataSource.view()),c&&(t=s.length,u=s.slice(0)),r=0,o=a.length;o>r;r++)if(n=a[r],i=n.get(l),c){for(e=0;t>e;e++)if(i==u[e]){u[e]=n;break}}else if(i==s){s=d?n:i;break}u[0]&&(s=this._valueIsObservableArray?u:d||!l?u[0]:u[0].get(l))}this.bindings.value.set(s),this._initChange=!1},refresh:function(){var e,n,i,r,o,a,s,l,c;if(!this._initChange){if(e=this.widget,n=e.options,i=n.dataTextField,r=n.dataValueField||i,o=this.bindings.value.get(),a=n.text||"",s=0,c=[],o===t&&(o=null),r)if(o instanceof D){for(l=o.length;l>s;s++)c[s]=o[s].get(r);o=c}else o instanceof T&&(a=o.get(i),o=o.get(r));n.autoBind!==!1||n.cascadeFrom||!e.listView||e.listView.isBound()?e.value(o):(i!==r||a||(a=o),!a&&o&&n.valuePrimitive?e.value(o):e._preselect(o,a))}this._initChange=!1},destroy:function(){this.widget.unbind(L,this._change)}}),gantt:{dependencies:n("dependencies","dependencies","setDependenciesDataSource")},multiselect:{value:v.extend({init:function(t,n,i){v.fn.init.call(this,t.element[0],n,i),this.widget=t,this._change=e.proxy(this.change,this),this.widget.first(L,this._change),this._initChange=!1},change:function(){var e,n,i,r,o,a,s,l,c,d=this,u=d.bindings[M].get(),h=d.options.valuePrimitive,p=h?d.widget.value():d.widget.dataItems(),f=this.options.dataValueField||this.options.dataTextField;if(p=p.slice(0),d._initChange=!0,u instanceof D){for(e=[],n=p.length,i=0,r=0,o=u[i],a=!1;o!==t;){for(c=!1,r=0;n>r;r++)if(h?a=p[r]==o:(l=p[r],l=l.get?l.get(f):l,a=l==(o.get?o.get(f):o)),a){p.splice(r,1),n-=1,c=!0;break}c?i+=1:(e.push(o),w(u,i,1),s=i),o=u[i]}w(u,u.length,0,p),e.length&&u.trigger("change",{action:"remove",items:e,index:s}),p.length&&u.trigger("change",{action:"add",items:p,index:u.length-1})}else d.bindings[M].set(p);d._initChange=!1},refresh:function(){if(!this._initChange){var e,n,i=this.options,r=this.widget,o=i.dataValueField||i.dataTextField,a=this.bindings.value.get(),s=a,l=0,c=[];if(a===t&&(a=null),o)if(a instanceof D){for(e=a.length;e>l;l++)n=a[l],c[l]=n.get?n.get(o):n;a=c}else a instanceof T&&(a=a.get(o));i.autoBind!==!1||i.valuePrimitive===!0||r.listView.isBound()?r.value(a):r._preselect(s,a)}},destroy:function(){this.widget.unbind(L,this._change)}})},scheduler:{source:n("source","dataSource","setDataSource").extend({dataBound:function(e){var t,n,i,r,o=this.widget,s=e.addedItems||o.items();if(s.length)for(i=e.addedDataItems||o.dataItems(),r=this.bindings.source._parents(),t=0,n=i.length;n>t;t++)a(s[t],i[t],this._ns(e.ns),[i[t]].concat(r))}})}},w=function(e,t,n,i){var r,o,a,s,l;if(i=i||[],n=n||0,r=i.length,o=e.length,a=[].slice.call(e,t+n),s=a.length,r){for(r=t+r,l=0;r>t;t++)e[t]=i[l],l++;e.length=r}else if(n)for(e.length=t,n+=t;n>t;)delete e[--n];if(s){for(s=t+s,l=0;s>t;t++)e[t]=a[l],l++;e.length=s}for(t=e.length;o>t;)delete e[t],t++},b=I.extend({init:function(e,t){this.target=e,this.options=t,this.toDestroy=[] -},bind:function(e){var t,n,i,r,o,a,s=this instanceof y,l=this.binders();for(t in e)t==M?n=!0:t==z?i=!0:t!=F||s?t==R?o=!0:t==H?a=!0:this.applyBinding(t,e,l):r=!0;i&&this.applyBinding(z,e,l),n&&this.applyBinding(M,e,l),o&&this.applyBinding(R,e,l),r&&!s&&this.applyBinding(F,e,l),a&&!s&&this.applyBinding(H,e,l)},binders:function(){return E[this.target.nodeName.toLowerCase()]||{}},applyBinding:function(e,t,n){var i,r=n[e]||E[e],o=this.toDestroy,a=t[e];if(r)if(r=new r(this.target,t,this.options),o.push(r),a instanceof f)r.bind(a),o.push(a);else for(i in a)r.bind(a,i),o.push(a[i]);else if("template"!==e)throw Error("The "+e+" binding is not supported by the "+this.target.nodeName.toLowerCase()+" element")},destroy:function(){var e,t,n=this.toDestroy;for(e=0,t=n.length;t>e;e++)n[e].destroy()}}),y=b.extend({binders:function(){return E.widget[this.target.options.name.toLowerCase()]||{}},applyBinding:function(e,t,n){var i,r=n[e]||E.widget[e],o=this.toDestroy,a=t[e];if(!r)throw Error("The "+e+" binding is not supported by the "+this.target.options.name+" widget");if(r=new r(this.target,t,this.target.options),o.push(r),a instanceof f)r.bind(a),o.push(a);else for(i in a)r.bind(a,i),o.push(a[i])}}),k=/[A-Za-z0-9_\-]+:(\{([^}]*)\}|[^,}]+)/g,x=/\s/g,C.unbind=u,C.bind=s,C.data.binders=E,C.data.Binder=v,C.notify=h,C.observable=function(e){return e instanceof T||(e=new T(e)),e},C.observableHierarchy=function(e){function t(e){var n,i;for(n=0;e.length>n;n++)e[n]._initChildren(),i=e[n].children,i.fetch(),e[n].items=i.data(),t(e[n].items)}var n=C.data.HierarchicalDataSource.create(e);return n.fetch(),t(n.data()),n._data._dataSource=n,n._data}}(window.kendo.jQuery),function(e,t){function n(e){return parseInt(e,10)}function i(e,t){return n(e.css(t))}function r(e){var t,n=[];for(t in e)n.push(t);return n}function o(e){for(var t in e)-1!=U.indexOf(t)&&-1==W.indexOf(t)&&delete e[t];return e}function a(e,t){var n,i,r,o,a=[],s={};for(i in t)n=i.toLowerCase(),o=P&&-1!=U.indexOf(n),!E.hasHW3D&&o&&-1==W.indexOf(n)?delete t[i]:(r=t[i],o?a.push(i+"("+r+")"):s[i]=r);return a.length&&(s[st]=a.join(" ")),s}function s(e,t){var i,r,o;return P?(i=e.css(st),i==Q?"scale"==t?1:0:(r=i.match(RegExp(t+"\\s*\\(([\\d\\w\\.]+)")),o=0,r?o=n(r[1]):(r=i.match(H)||[0,0,0,0,0],t=t.toLowerCase(),L.test(t)?o=parseFloat(r[3]/r[2]):"translatey"==t?o=parseFloat(r[4]/r[2]):"scale"==t?o=parseFloat(r[2]):"rotate"==t&&(o=parseFloat(Math.atan2(r[2],r[1])))),o)):parseFloat(e.css(t))}function l(e){return e.charAt(0).toUpperCase()+e.substring(1)}function c(e,t){var n=f.extend(t),i=n.prototype.directions;S[l(e)]=n,S.Element.prototype[e]=function(e,t,i,r){return new n(this.element,e,t,i,r)},T(i,function(t,i){S.Element.prototype[e+l(i)]=function(e,t,r){return new n(this.element,i,e,t,r)}})}function d(e,n,i,r){c(e,{directions:m,startValue:function(e){return this._startValue=e,this},endValue:function(e){return this._endValue=e,this},shouldHide:function(){return this._shouldHide},prepare:function(e,o){var a,s,l=this,c="out"===this._direction,d=l.element.data(n),u=!(isNaN(d)||d==i);a=u?d:t!==this._startValue?this._startValue:c?i:r,s=t!==this._endValue?this._endValue:c?r:i,this._reverse?(e[n]=s,o[n]=a):(e[n]=a,o[n]=s),l._shouldHide=o[n]===r}})}function u(e,t){var n=C.directions[t].vertical,i=e[n?Z:X]()/2+"px";return _[t].replace("$size",i)}var h,p,f,g,m,v,_,w,b,y,k,x,C=window.kendo,S=C.effects,T=e.each,D=e.extend,A=e.proxy,E=C.support,I=E.browser,P=E.transforms,M=E.transitions,z={scale:0,scalex:0,scaley:0,scale3d:0},F={translate:0,translatex:0,translatey:0,translate3d:0},R=t!==document.documentElement.style.zoom&&!P,H=/matrix3?d?\s*\(.*,\s*([\d\.\-]+)\w*?,\s*([\d\.\-]+)\w*?,\s*([\d\.\-]+)\w*?,\s*([\d\.\-]+)\w*?/i,B=/^(-?[\d\.\-]+)?[\w\s]*,?\s*(-?[\d\.\-]+)?[\w\s]*/i,L=/translatex?$/i,N=/(zoom|fade|expand)(\w+)/,O=/(zoom|fade|expand)/,V=/[xy]$/i,U=["perspective","rotate","rotatex","rotatey","rotatez","rotate3d","scale","scalex","scaley","scalez","scale3d","skew","skewx","skewy","translate","translatex","translatey","translatez","translate3d","matrix","matrix3d"],W=["rotate","scale","scalex","scaley","skew","skewx","skewy","translate","translatex","translatey","matrix"],j={rotate:"deg",scale:"",skew:"px",translate:"px"},G=P.css,q=Math.round,$="",Y="px",Q="none",K="auto",X="width",Z="height",J="hidden",et="origin",tt="abortId",nt="overflow",it="translate",rt="position",ot="completeCallback",at=G+"transition",st=G+"transform",lt=G+"backface-visibility",ct=G+"perspective",dt="1500px",ut="perspective("+dt+")",ht={left:{reverse:"right",property:"left",transition:"translatex",vertical:!1,modifier:-1},right:{reverse:"left",property:"left",transition:"translatex",vertical:!1,modifier:1},down:{reverse:"up",property:"top",transition:"translatey",vertical:!0,modifier:1},up:{reverse:"down",property:"top",transition:"translatey",vertical:!0,modifier:-1},top:{reverse:"bottom"},bottom:{reverse:"top"},"in":{reverse:"out",modifier:-1},out:{reverse:"in",modifier:1},vertical:{reverse:"vertical"},horizontal:{reverse:"horizontal"}};C.directions=ht,D(e.fn,{kendoStop:function(e,t){return M?S.stopQueue(this,e||!1,t||!1):this.stop(e,t)}}),P&&!M&&(T(W,function(n,i){e.fn[i]=function(n){if(t===n)return s(this,i);var r=e(this)[0],o=i+"("+n+j[i.replace(V,"")]+")";return-1==r.style.cssText.indexOf(st)?e(this).css(st,o):r.style.cssText=r.style.cssText.replace(RegExp(i+"\\(.*?\\)","i"),o),this},e.fx.step[i]=function(t){e(t.elem)[i](t.now)}}),h=e.fx.prototype.cur,e.fx.prototype.cur=function(){return-1!=W.indexOf(this.prop)?parseFloat(e(this.elem)[this.prop]()):h.apply(this,arguments)}),C.toggleClass=function(e,t,n,i){return t&&(t=t.split(" "),M&&(n=D({exclusive:"all",duration:400,ease:"ease-out"},n),e.css(at,n.exclusive+" "+n.duration+"ms "+n.ease),setTimeout(function(){e.css(at,"").css(Z)},n.duration)),T(t,function(t,n){e.toggleClass(n,i)})),e},C.parseEffects=function(e,t){var n={};return"string"==typeof e?T(e.split(" "),function(e,i){var r=!O.test(i),o=i.replace(N,function(e,t,n){return t+":"+n.toLowerCase()}),a=o.split(":"),s=a[1],l={};a.length>1&&(l.direction=t&&r?ht[s].reverse:s),n[a[0]]=l}):T(e,function(e){var i=this.direction;i&&t&&!O.test(e)&&(this.direction=ht[i].reverse),n[e]=this}),n},M&&D(S,{transition:function(t,n,i){var o,s,l,c,d=0,u=t.data("keys")||[];i=D({duration:200,ease:"ease-out",complete:null,exclusive:"all"},i),l=!1,c=function(){l||(l=!0,s&&(clearTimeout(s),s=null),t.removeData(tt).dequeue().css(at,"").css(at),i.complete.call(t))},i.duration=e.fx?e.fx.speeds[i.duration]||i.duration:i.duration,o=a(t,n),e.merge(u,r(o)),t.data("keys",e.unique(u)).height(),t.css(at,i.exclusive+" "+i.duration+"ms "+i.ease).css(at),t.css(o).css(st),M.event&&(t.one(M.event,c),0!==i.duration&&(d=500)),s=setTimeout(c,i.duration+d),t.data(tt,s),t.data(ot,c)},stopQueue:function(e,t,n){var i,r=e.data("keys"),o=!n&&r,a=e.data(ot);return o&&(i=C.getComputedStyles(e[0],r)),a&&a(),o&&e.css(i),e.removeData("keys").stop(t)}}),p=C.Class.extend({init:function(e,t){var n=this;n.element=e,n.effects=[],n.options=t,n.restore=[]},run:function(t){var n,i,r,s,l,c,d,u=this,h=t.length,p=u.element,f=u.options,g=e.Deferred(),m={},v={};for(u.effects=t,g.then(e.proxy(u,"complete")),p.data("animating",!0),i=0;h>i;i++)for(n=t[i],n.setReverse(f.reverse),n.setOptions(f),u.addRestoreProperties(n.restore),n.prepare(m,v),l=n.children(),r=0,c=l.length;c>r;r++)l[r].duration(f.duration).run();for(d in f.effects)D(v,f.effects[d].properties);for(p.is(":visible")||D(m,{display:p.data("olddisplay")||"block"}),P&&!f.reset&&(s=p.data("targetTransform"),s&&(m=D(s,m))),m=a(p,m),P&&!M&&(m=o(m)),p.css(m).css(st),i=0;h>i;i++)t[i].setup();return f.init&&f.init(),p.data("targetTransform",v),S.animate(p,v,D({},f,{complete:g.resolve})),g.promise()},stop:function(){e(this.element).kendoStop(!0,!0)},addRestoreProperties:function(e){for(var t,n=this.element,i=0,r=e.length;r>i;i++)t=e[i],this.restore.push(t),n.data(t)||n.data(t,n.css(t))},restoreCallback:function(){var e,t,n,i=this.element;for(e=0,t=this.restore.length;t>e;e++)n=this.restore[e],i.css(n,i.data(n))},complete:function(){var t=this,n=0,i=t.element,r=t.options,o=t.effects,a=o.length;for(i.removeData("animating").dequeue(),r.hide&&i.data("olddisplay",i.css("display")).hide(),this.restoreCallback(),R&&!P&&setTimeout(e.proxy(this,"restoreCallback"),0);a>n;n++)o[n].teardown();r.completeCallback&&r.completeCallback(i)}}),S.promise=function(e,t){var n,i,r,o=[],a=new p(e,t),s=C.parseEffects(t.effects);t.effects=s;for(r in s)n=S[l(r)],n&&(i=new n(e,s[r].direction),o.push(i));o[0]?a.run(o):(e.is(":visible")||e.css({display:e.data("olddisplay")||"block"}).css("display"),t.init&&t.init(),e.dequeue(),a.complete())},D(S,{animate:function(n,r,a){var s=a.transition!==!1;delete a.transition,M&&"transition"in S&&s?S.transition(n,r,a):P?n.animate(o(r),{queue:!1,show:!1,hide:!1,duration:a.duration,complete:a.complete}):n.each(function(){var n=e(this),o={};T(U,function(e,a){var s,l,c,d,u,h,p,f=r?r[a]+" ":null;f&&(l=r,a in z&&r[a]!==t?(s=f.match(B),P&&D(l,{scale:+s[0]})):a in F&&r[a]!==t&&(c=n.css(rt),d="absolute"==c||"fixed"==c,n.data(it)||(d?n.data(it,{top:i(n,"top")||0,left:i(n,"left")||0,bottom:i(n,"bottom"),right:i(n,"right")}):n.data(it,{top:i(n,"marginTop")||0,left:i(n,"marginLeft")||0})),u=n.data(it),s=f.match(B),s&&(h=a==it+"y"?0:+s[1],p=a==it+"y"?+s[1]:+s[2],d?(isNaN(u.right)?isNaN(h)||D(l,{left:u.left+h}):isNaN(h)||D(l,{right:u.right-h}),isNaN(u.bottom)?isNaN(p)||D(l,{top:u.top+p}):isNaN(p)||D(l,{bottom:u.bottom-p})):(isNaN(h)||D(l,{marginLeft:u.left+h}),isNaN(p)||D(l,{marginTop:u.top+p})))),!P&&"scale"!=a&&a in l&&delete l[a],l&&D(o,l))}),I.msie&&delete o.scale,n.animate(o,{queue:!1,show:!1,hide:!1,duration:a.duration,complete:a.complete})})}}),S.animatedPromise=S.promise,f=C.Class.extend({init:function(e,t){var n=this;n.element=e,n._direction=t,n.options={},n._additionalEffects=[],n.restore||(n.restore=[])},reverse:function(){return this._reverse=!0,this.run()},play:function(){return this._reverse=!1,this.run()},add:function(e){return this._additionalEffects.push(e),this},direction:function(e){return this._direction=e,this},duration:function(e){return this._duration=e,this},compositeRun:function(){var e=this,t=new p(e.element,{reverse:e._reverse,duration:e._duration}),n=e._additionalEffects.concat([e]);return t.run(n)},run:function(){if(this._additionalEffects&&this._additionalEffects[0])return this.compositeRun();var t,n,i=this,r=i.element,s=0,l=i.restore,c=l.length,d=e.Deferred(),u={},h={},p=i.children(),f=p.length;for(d.then(e.proxy(i,"_complete")),r.data("animating",!0),s=0;c>s;s++)t=l[s],r.data(t)||r.data(t,r.css(t));for(s=0;f>s;s++)p[s].duration(i._duration).run();return i.prepare(u,h),r.is(":visible")||D(u,{display:r.data("olddisplay")||"block"}),P&&(n=r.data("targetTransform"),n&&(u=D(n,u))),u=a(r,u),P&&!M&&(u=o(u)),r.css(u).css(st),i.setup(),r.data("targetTransform",h),S.animate(r,h,{duration:i._duration,complete:d.resolve}),d.promise()},stop:function(){var t=0,n=this.children(),i=n.length;for(t=0;i>t;t++)n[t].stop();return e(this.element).kendoStop(!0,!0),this},restoreCallback:function(){var e,t,n,i=this.element;for(e=0,t=this.restore.length;t>e;e++)n=this.restore[e],i.css(n,i.data(n))},_complete:function(){var t=this,n=t.element;n.removeData("animating").dequeue(),t.restoreCallback(),t.shouldHide()&&n.data("olddisplay",n.css("display")).hide(),R&&!P&&setTimeout(e.proxy(t,"restoreCallback"),0),t.teardown()},setOptions:function(e){D(!0,this.options,e)},children:function(){return[]},shouldHide:e.noop,setup:e.noop,prepare:e.noop,teardown:e.noop,directions:[],setReverse:function(e){return this._reverse=e,this}}),g=["left","right","up","down"],m=["in","out"],c("slideIn",{directions:g,divisor:function(e){return this.options.divisor=e,this},prepare:function(e,t){var n,i=this,r=i.element,o=ht[i._direction],a=-o.modifier*(o.vertical?r.outerHeight():r.outerWidth()),s=a/(i.options&&i.options.divisor||1)+Y,l="0px";i._reverse&&(n=e,e=t,t=n),P?(e[o.transition]=s,t[o.transition]=l):(e[o.property]=s,t[o.property]=l)}}),c("tile",{directions:g,init:function(e,t,n){f.prototype.init.call(this,e,t),this.options={previous:n}},previousDivisor:function(e){return this.options.previousDivisor=e,this},children:function(){var e=this,t=e._reverse,n=e.options.previous,i=e.options.previousDivisor||1,r=e._direction,o=[C.fx(e.element).slideIn(r).setReverse(t)];return n&&o.push(C.fx(n).slideIn(ht[r].reverse).divisor(i).setReverse(!t)),o}}),d("fade","opacity",1,0),d("zoom","scale",1,.01),c("slideMargin",{prepare:function(e,t){var n,i=this,r=i.element,o=i.options,a=r.data(et),s=o.offset,l=i._reverse;l||null!==a||r.data(et,parseFloat(r.css("margin-"+o.axis))),n=r.data(et)||0,t["margin-"+o.axis]=l?n:n+s}}),c("slideTo",{prepare:function(e,t){var n=this,i=n.element,r=n.options,o=r.offset.split(","),a=n._reverse;P?(t.translatex=a?0:o[0],t.translatey=a?0:o[1]):(t.left=a?0:o[0],t.top=a?0:o[1]),i.css("left")}}),c("expand",{directions:["horizontal","vertical"],restore:[nt],prepare:function(e,n){var i=this,r=i.element,o=i.options,a=i._reverse,s="vertical"===i._direction?Z:X,l=r[0].style[s],c=r.data(s),d=parseFloat(c||l),u=q(r.css(s,K)[s]());e.overflow=J,d=o&&o.reset?u||d:d||u,n[s]=(a?0:d)+Y,e[s]=(a?d:0)+Y,c===t&&r.data(s,l)},shouldHide:function(){return this._reverse},teardown:function(){var e=this,t=e.element,n="vertical"===e._direction?Z:X,i=t.data(n);(i==K||i===$)&&setTimeout(function(){t.css(n,K).css(n)},0)}}),v={position:"absolute",marginLeft:0,marginTop:0,scale:1},c("transfer",{init:function(e,t){this.element=e,this.options={target:t},this.restore=[]},setup:function(){this.element.appendTo(document.body)},prepare:function(e,t){var n=this,i=n.element,r=S.box(i),o=S.box(n.options.target),a=s(i,"scale"),l=S.fillScale(o,r),c=S.transformOrigin(o,r);D(e,v),t.scale=1,i.css(st,"scale(1)").css(st),i.css(st,"scale("+a+")"),e.top=r.top,e.left=r.left,e.transformOrigin=c.x+Y+" "+c.y+Y,n._reverse?e.scale=l:t.scale=l}}),_={top:"rect(auto auto $size auto)",bottom:"rect($size auto auto auto)",left:"rect(auto $size auto auto)",right:"rect(auto auto auto $size)"},w={top:{start:"rotatex(0deg)",end:"rotatex(180deg)"},bottom:{start:"rotatex(-180deg)",end:"rotatex(0deg)"},left:{start:"rotatey(0deg)",end:"rotatey(-180deg)"},right:{start:"rotatey(180deg)",end:"rotatey(0deg)"}},c("turningPage",{directions:g,init:function(e,t,n){f.prototype.init.call(this,e,t),this._container=n},prepare:function(e,t){var n=this,i=n._reverse,r=i?ht[n._direction].reverse:n._direction,o=w[r];e.zIndex=1,n._clipInHalf&&(e.clip=u(n._container,C.directions[r].reverse)),e[lt]=J,t[st]=ut+(i?o.start:o.end),e[st]=ut+(i?o.end:o.start)},setup:function(){this._container.append(this.element)},face:function(e){return this._face=e,this},shouldHide:function(){var e=this,t=e._reverse,n=e._face;return t&&!n||!t&&n},clipInHalf:function(e){return this._clipInHalf=e,this},temporary:function(){return this.element.addClass("temp-page"),this}}),c("staticPage",{directions:g,init:function(e,t,n){f.prototype.init.call(this,e,t),this._container=n},restore:["clip"],prepare:function(e,t){var n=this,i=n._reverse?ht[n._direction].reverse:n._direction;e.clip=u(n._container,i),e.opacity=.999,t.opacity=1},shouldHide:function(){var e=this,t=e._reverse,n=e._face;return t&&!n||!t&&n},face:function(e){return this._face=e,this}}),c("pageturn",{directions:["horizontal","vertical"],init:function(e,t,n,i){f.prototype.init.call(this,e,t),this.options={},this.options.face=n,this.options.back=i},children:function(){var e,t=this,n=t.options,i="horizontal"===t._direction?"left":"top",r=C.directions[i].reverse,o=t._reverse,a=n.face.clone(!0).removeAttr("id"),s=n.back.clone(!0).removeAttr("id"),l=t.element;return o&&(e=i,i=r,r=e),[C.fx(n.face).staticPage(i,l).face(!0).setReverse(o),C.fx(n.back).staticPage(r,l).setReverse(o),C.fx(a).turningPage(i,l).face(!0).clipInHalf(!0).temporary().setReverse(o),C.fx(s).turningPage(r,l).clipInHalf(!0).temporary().setReverse(o)]},prepare:function(e,t){e[ct]=dt,e.transformStyle="preserve-3d",e.opacity=.999,t.opacity=1},teardown:function(){this.element.find(".temp-page").remove()}}),c("flip",{directions:["horizontal","vertical"],init:function(e,t,n,i){f.prototype.init.call(this,e,t),this.options={},this.options.face=n,this.options.back=i},children:function(){var e,t=this,n=t.options,i="horizontal"===t._direction?"left":"top",r=C.directions[i].reverse,o=t._reverse,a=t.element;return o&&(e=i,i=r,r=e),[C.fx(n.face).turningPage(i,a).face(!0).setReverse(o),C.fx(n.back).turningPage(r,a).setReverse(o)]},prepare:function(e){e[ct]=dt,e.transformStyle="preserve-3d"}}),b=!E.mobileOS.android,y=".km-touch-scrollbar, .km-actionsheet-wrapper",c("replace",{_before:e.noop,_after:e.noop,init:function(t,n,i){f.prototype.init.call(this,t),this._previous=e(n),this._transitionClass=i},duration:function(){throw Error("The replace effect does not support duration setting; the effect duration may be customized through the transition class rule")},beforeTransition:function(e){return this._before=e,this},afterTransition:function(e){return this._after=e,this},_both:function(){return e().add(this._element).add(this._previous)},_containerClass:function(){var e=this._direction,t="k-fx k-fx-start k-fx-"+this._transitionClass;return e&&(t+=" k-fx-"+e),this._reverse&&(t+=" k-fx-reverse"),t},complete:function(t){if(!(!this.deferred||t&&e(t.target).is(y))){var n=this.container;n.removeClass("k-fx-end").removeClass(this._containerClass()).off(M.event,this.completeProxy),this._previous.hide().removeClass("k-fx-current"),this.element.removeClass("k-fx-next"),b&&n.css(nt,""),this.isAbsolute||this._both().css(rt,""),this.deferred.resolve(),delete this.deferred}},run:function(){if(this._additionalEffects&&this._additionalEffects[0])return this.compositeRun();var t,n=this,i=n.element,r=n._previous,o=i.parents().filter(r.parents()).first(),a=n._both(),s=e.Deferred(),l=i.css(rt);return o.length||(o=i.parent()),this.container=o,this.deferred=s,this.isAbsolute="absolute"==l,this.isAbsolute||a.css(rt,"absolute"),b&&(t=o.css(nt),o.css(nt,"hidden")),M?(i.addClass("k-fx-hidden"),o.addClass(this._containerClass()),this.completeProxy=e.proxy(this,"complete"),o.on(M.event,this.completeProxy),C.animationFrame(function(){i.removeClass("k-fx-hidden").addClass("k-fx-next"),r.css("display","").addClass("k-fx-current"),n._before(r,i),C.animationFrame(function(){o.removeClass("k-fx-start").addClass("k-fx-end"),n._after(r,i)})})):this.complete(),s.promise()},stop:function(){this.complete()}}),k=C.Class.extend({init:function(){var e=this;e._tickProxy=A(e._tick,e),e._started=!1},tick:e.noop,done:e.noop,onEnd:e.noop,onCancel:e.noop,start:function(){this.enabled()&&(this.done()?this.onEnd():(this._started=!0,C.animationFrame(this._tickProxy)))},enabled:function(){return!0},cancel:function(){this._started=!1,this.onCancel()},_tick:function(){var e=this;e._started&&(e.tick(),e.done()?(e._started=!1,e.onEnd()):C.animationFrame(e._tickProxy))}}),x=k.extend({init:function(e){var t=this;D(t,e),k.fn.init.call(t)},done:function(){return this.timePassed()>=this.duration},timePassed:function(){return Math.min(this.duration,new Date-this.startDate)},moveTo:function(e){var t=this,n=t.movable;t.initial=n[t.axis],t.delta=e.location-t.initial,t.duration="number"==typeof e.duration?e.duration:300,t.tick=t._easeProxy(e.ease),t.startDate=new Date,t.start()},_easeProxy:function(e){var t=this;return function(){t.movable.moveAxis(t.axis,e(t.timePassed(),t.initial,t.delta,t.duration))}}}),D(x,{easeOutExpo:function(e,t,n,i){return e==i?t+n:n*(-Math.pow(2,-10*e/i)+1)+t},easeOutBack:function(e,t,n,i,r){return r=1.70158,n*((e=e/i-1)*e*((r+1)*e+r)+1)+t}}),S.Animation=k,S.Transition=x,S.createEffect=c,S.box=function(t){t=e(t);var n=t.offset();return n.width=t.outerWidth(),n.height=t.outerHeight(),n},S.transformOrigin=function(e,t){var n=(e.left-t.left)*t.width/(t.width-e.width),i=(e.top-t.top)*t.height/(t.height-e.height);return{x:isNaN(n)?0:n,y:isNaN(i)?0:i}},S.fillScale=function(e,t){return Math.min(e.width/t.width,e.height/t.height)},S.fitScale=function(e,t){return Math.max(e.width/t.width,e.height/t.height)}}(window.kendo.jQuery),function(e){function t(e){if(!e)return{};var t=e.match(v)||[];return{type:t[1],direction:t[3],reverse:"reverse"===t[5]}}var n=window.kendo,i=n.Observable,r="SCRIPT",o="init",a="show",s="hide",l="transitionStart",c="transitionEnd",d="attach",u="detach",h=/unrecognized expression/,p=i.extend({init:function(e,t){var r=this;t=t||{},i.fn.init.call(r),r.content=e,r.id=n.guid(),r.tagName=t.tagName||"div",r.model=t.model,r._wrap=t.wrap!==!1,this._evalTemplate=t.evalTemplate||!1,r._fragments={},r.bind([o,a,s,l,c],t)},render:function(t){var i=this,r=!i.element;return r&&(i.element=i._createElement()),t&&e(t).append(i.element),r&&(n.bind(i.element,i.model),i.trigger(o)),t&&(i._eachFragment(d),i.trigger(a)),i.element},clone:function(){return new f(this)},triggerBeforeShow:function(){return!0},triggerBeforeHide:function(){return!0},showStart:function(){this.element.css("display","")},showEnd:function(){},hideEnd:function(){this.hide()},beforeTransition:function(e){this.trigger(l,{type:e})},afterTransition:function(e){this.trigger(c,{type:e})},hide:function(){this._eachFragment(u),this.element.detach(),this.trigger(s)},destroy:function(){var e=this.element;e&&(n.unbind(e),n.destroy(e),e.remove())},fragments:function(t){e.extend(this._fragments,t)},_eachFragment:function(e){for(var t in this._fragments)this._fragments[t][e](this,t)},_createElement:function(){var t,i,o,a=this,s="<"+a.tagName+" />";try{i=e(document.getElementById(a.content)||a.content),i[0].tagName===r&&(i=i.html())}catch(l){h.test(l.message)&&(i=a.content)}return"string"==typeof i?(i=i.replace(/^\s+|\s+$/g,""),a._evalTemplate&&(i=n.template(i)(a.model||{})),t=e(s).append(i),a._wrap||(t=t.contents())):(t=i,a._evalTemplate&&(o=e(n.template(e("
    ").append(t.clone(!0)).html())(a.model||{})),e.contains(document,t[0])&&t.replaceWith(o),t=o),a._wrap&&(t=t.wrapAll(s).parent())),t}}),f=n.Class.extend({init:function(t){e.extend(this,{element:t.element.clone(!0),transition:t.transition,id:t.id}),t.element.parent().append(this.element)},hideEnd:function(){this.element.remove()},beforeTransition:e.noop,afterTransition:e.noop}),g=p.extend({init:function(e,t){p.fn.init.call(this,e,t),this.containers={}},container:function(e){var t=this.containers[e];return t||(t=this._createContainer(e),this.containers[e]=t),t},showIn:function(e,t,n){this.container(e).show(t,n)},_createContainer:function(e){var t,n=this.render(),i=n.find(e);if(!i.length&&n.is(e)){if(!n.is(e))throw Error("can't find a container with the specified "+e+" selector");i=n}return t=new _(i),t.bind("accepted",function(e){e.view.render(i)}),t}}),m=p.extend({attach:function(e,t){e.element.find(t).replaceWith(this.render())},detach:function(){}}),v=/^(\w+)(:(\w+))?( (\w+))?$/,_=i.extend({init:function(e){i.fn.init.call(this),this.container=e,this.history=[],this.view=null,this.running=!1},after:function(){this.running=!1,this.trigger("complete",{view:this.view}),this.trigger("after")},end:function(){this.view.showEnd(),this.previous.hideEnd(),this.after()},show:function(e,i,r){if(!e.triggerBeforeShow()||this.view&&!this.view.triggerBeforeHide())return this.trigger("after"),!1;r=r||e.id;var o=this,a=e===o.view?e.clone():o.view,s=o.history,l=s[s.length-2]||{},c=l.id===r,d=i||(c?s[s.length-1].transition:e.transition),u=t(d);return o.running&&o.effect.stop(),"none"===d&&(d=null),o.trigger("accepted",{view:e}),o.view=e,o.previous=a,o.running=!0,c?s.pop():s.push({id:r,transition:d}),a?(d&&n.effects.enabled?(e.element.addClass("k-fx-hidden"),e.showStart(),c&&!i&&(u.reverse=!u.reverse),o.effect=n.fx(e.element).replace(a.element,u.type).beforeTransition(function(){e.beforeTransition("show"),a.beforeTransition("hide")}).afterTransition(function(){e.afterTransition("show"),a.afterTransition("hide")}).direction(u.direction).setReverse(u.reverse),o.effect.run().then(function(){o.end()})):(e.showStart(),o.end()),!0):(e.showStart(),e.showEnd(),o.after(),!0)}});n.ViewContainer=_,n.Fragment=m,n.Layout=g,n.View=p,n.ViewClone=f}(window.kendo.jQuery),function(e){function t(){this.node=null}function n(){}function i(e,t,n){this.nodeName=e,this.attr=t||{},this.children=n||[]}function r(e){this.nodeValue=e}function o(e){this.html=e}function a(e){return new o(e)}function s(e,t,n){return new i(e,t,n)}function l(e){return new r(e)}function c(e){this.root=e,this.children=[]}t.prototype={remove:function(){this.node.parentNode.removeChild(this.node)},attr:{}},n.prototype={nodeName:"#null",attr:{style:{}},children:[],remove:function(){}};var d=new n;i.prototype=new t,i.prototype.appendTo=function(e){var t,n=document.createElement(this.nodeName),i=this.children;for(t=0;i.length>t;t++)i[t].render(n,d);return e.appendChild(n),n},i.prototype.render=function(e,t){var n,i,r,o,a,s;if(t.nodeName!==this.nodeName)t.remove(),n=this.appendTo(e);else{if(n=t.node,r=this.children,o=r.length,a=t.children,s=a.length,Math.abs(s-o)>2)return void this.render({appendChild:function(n){e.replaceChild(n,t.node)}},d);for(i=0;o>i;i++)r[i].render(n,a[i]||d);for(i=o;s>i;i++)a[i].remove()}this.node=n,this.syncAttributes(t.attr),this.removeAttributes(t.attr)},i.prototype.syncAttributes=function(e){var t,n,i,r=this.attr;for(t in r)n=r[t],i=e[t],"style"===t?this.setStyle(n,i):n!==i&&this.setAttribute(t,n,i)},i.prototype.setStyle=function(e,t){var n,i=this.node;if(t)for(n in e)e[n]!==t[n]&&(i.style[n]=e[n]);else for(n in e)i.style[n]=e[n]},i.prototype.removeStyle=function(e){var t,n=this.attr.style||{},i=this.node;for(t in e)void 0===n[t]&&(i.style[t]="")},i.prototype.removeAttributes=function(e){var t,n=this.attr;for(t in e)"style"===t?this.removeStyle(e.style):void 0===n[t]&&this.removeAttribute(t)},i.prototype.removeAttribute=function(e){var t=this.node;"style"===e?t.style.cssText="":"className"===e?t.className="":t.removeAttribute(e)},i.prototype.setAttribute=function(e,t){var n=this.node;void 0!==n[e]?n[e]=t:n.setAttribute(e,t)},r.prototype=new t,r.prototype.nodeName="#text",r.prototype.render=function(e,t){var n;t.nodeName!==this.nodeName?(t.remove(),n=document.createTextNode(this.nodeValue),e.appendChild(n)):(n=t.node,this.nodeValue!==t.nodeValue&&(n.nodeValue=this.nodeValue)),this.node=n},o.prototype={nodeName:"#html",attr:{},remove:function(){for(var e=0;this.nodes.length>e;e++)this.nodes[e].parentNode.removeChild(this.nodes[e])},render:function(e,t){var n,i;if(t.nodeName!==this.nodeName||t.html!==this.html)for(t.remove(),n=e.lastChild,e.insertAdjacentHTML("beforeend",this.html),this.nodes=[],i=n?n.nextSibling:e.firstChild;i;i=i.nextSibling)this.nodes.push(i);else this.nodes=t.nodes.slice(0)}},c.prototype={html:a,element:s,text:l,render:function(e){var t,n,i=this.children;for(t=0,n=e.length;n>t;t++)e[t].render(this.root,i[t]||d);for(t=n;i.length>t;t++)i[t].remove();this.children=e}},e.dom={html:a,text:l,element:s,Tree:c}}(window.kendo),function(e,t){function n(e){var t=Math.floor(e/26)-1;return(t>=0?n(t):"")+String.fromCharCode(65+e%26)}function i(e,t){return n(t)+(e+1)}function r(e,t){return n(t)+"$"+(e+1)}function o(e){return((e.freezePane||{}).rowSplit||1)-1}function a(e){return 6>e.length&&(e=e.replace(/(\w)/g,function(e,t){return t+t})),e=e.substring(1).toUpperCase(),8>e.length&&(e="FF"+e),e}var s='\r\n',l=t.template('\r\n${creator}${lastModifiedBy}${created}${modified}'),c=t.template('\r\nMicrosoft Excel0falseWorksheets${sheets.length}# for (var idx = 0; idx < sheets.length; idx++) { ## if (sheets[idx].options.title) { #${sheets[idx].options.title}# } else { #Sheet${idx+1}# } ## } #falsefalsefalse14.0300'),d=t.template('\r\n# for (var idx = 1; idx <= count; idx++) { ## } #'),u=t.template('\r\n# for (var idx = 0; idx < sheets.length; idx++) { ## if (sheets[idx].options.title) { ## } else { ## } ## } ## if (definedNames.length) { # # for (var di = 0; di < definedNames.length; di++) { # # } ## } #'),h=t.template('\r\n# if (freezePane) { ## } ## if (columns) { ## for (var ci = 0; ci < columns.length; ci++) { ## var column = columns[ci]; ## if (column.width) { ## } ## } ## } ## for (var ri = 0; ri < data.length; ri++) { ## var row = data[ri]; ## for (var ci = 0; ci < row.data.length; ci++) { ## var cell = row.data[ci];## if (cell.value != null) { #${cell.value}# } ## } ## } ## if (filter) { ## } ## if (mergeCells.length) { ## for (var ci = 0; ci < mergeCells.length; ci++) { ## } ## } #'),p=t.template('\r\n# for (var idx = 1; idx <= count; idx++) { ## } #'),f=t.template('\r\n# for (var index in indexes) { #${index.substring(1)}# } #'),g=t.template('# for (var fi = 0; fi < formats.length; fi++) { ## var format = formats[fi]; ## } ## for (var fi = 0; fi < fonts.length; fi++) { ## var font = fonts[fi]; ## if (font.bold) { ## } ## if (font.italic) { ## } ## if (font.underline) { ## } ## if (font.color) { ## } else { ## } ## if (font.fontSize) { ## } else { ## } ## if (font.fontName) { ## } else { ## } ## } ## for (var fi = 0; fi < fills.length; fi++) { ## var fill = fills[fi]; ## if (fill.background) { ## } ## } ## for (var si = 0; si < styles.length; si++) { ## var style = styles[si]; ## if (style.hAlign || style.vAlign || style.wrap) { ## } ## } #'),m=t.timezone.remove(new Date(1900,0,0),"Etc/UTC"),v=t.Class.extend({init:function(e,t,n){this.options=e,this._strings=t,this._styles=n,this._mergeCells=[] -},toXML:function(e){var t,n,r=this.options.rows||[],a=this.options.filter,s={};for(this._maxCellIndex=0,t=[],n=0;r.length>n;n++)t.push(this._row(r,s,r[n],n));return h({freezePane:this.options.freezePane,columns:this.options.columns,data:t,index:e,mergeCells:this._mergeCells,filter:a?{from:i(o(this.options),a.from),to:i(o(this.options),a.to)}:null})},_row:function(e,t,n,r){var o,a,s,l,c,d;for(this._cellIndex&&this._cellIndex>this._maxCellIndex&&(this._maxCellIndex=this._cellIndex),this._cellIndex=0,a=[],s=n.cells,l=0,c=s.length;c>l;l++)o=this._cell(s[l],t,r),o&&a.push.apply(a,o);for(;this._maxCellIndex>this._cellIndex;)d=t[this._cellIndex],d&&(d.rowSpan-=1),a.push({ref:i(r,this._cellIndex)}),this._cellIndex++;return{data:a}},_lookupString:function(e){var t="$"+e,n=this._strings.indexes[t];return void 0!==n?e=n:(e=this._strings.indexes[t]=this._strings.uniqueCount,this._strings.uniqueCount++),this._strings.count++,e},_lookupStyle:function(n){var i,r=t.stringify(n);return"{}"==r?0:(i=e.inArray(r,this._styles),0>i&&(i=this._styles.push(r)-1),i+1)},_cell:function(e,n,r){var o,a,s,l,c,d,u,h,p,f,g,v;if(!e)return void this._cellIndex++;for(o=e.value,a={bold:e.bold,color:e.color,background:e.background,italic:e.italic,underline:e.underline,fontName:e.fontName,fontSize:e.fontSize,format:e.format,hAlign:e.hAlign,vAlign:e.vAlign,wrap:e.wrap},s=this.options.columns||[],l=s[this._cellIndex],l&&l.autoWidth&&(l.width=Math.max(l.width||0,(""+o).length)),c=typeof o,"string"===c?(o=this._lookupString(o),c="s"):"number"===c?c="n":"boolean"===c?(c="b",o=+o):o&&o.getTime?(c=null,o=(t.timezone.remove(o,"Etc/UTC")-m)/t.date.MS_PER_DAY+1,a.format||(a.format="mm-dd-yy")):(c=null,o=""),a=this._lookupStyle(a),d=[],p=n[this._cellIndex]||{};p.rowSpan>1;){for(p.rowSpan-=1,u=p.colSpan;u>0;)d.push({ref:i(r,this._cellIndex)}),u--,this._cellIndex++;p=n[this._cellIndex]||{}}if(h=i(r,this._cellIndex),d.push({value:o,type:c,style:a,ref:h}),f=e.colSpan||1,g=e.rowSpan||1,f>1||g>1){for(g>1&&(n[this._cellIndex]={colSpan:f,rowSpan:g}),v=1;f>v;v++)this._cellIndex++,d.push({ref:i(r,this._cellIndex)});this._mergeCells.push(h+":"+i(r+g-1,this._cellIndex))}return this._cellIndex++,d}}),_={General:0,0:1,"0.00":2,"#,##0":3,"#,##0.00":4,"0%":9,"0.00%":10,"0.00E+00":11,"# ?/?":12,"# ??/??":13,"mm-dd-yy":14,"d-mmm-yy":15,"d-mmm":16,"mmm-yy":17,"h:mm AM/PM":18,"h:mm:ss AM/PM":19,"h:mm":20,"h:mm:ss":21,"m/d/yy h:mm":22,"#,##0 ;(#,##0)":37,"#,##0 ;[Red](#,##0)":38,"#,##0.00;(#,##0.00)":39,"#,##0.00;[Red](#,##0.00)":40,"mm:ss":45,"[h]:mm:ss":46,"mmss.0":47,"##0.0E+0":48,"@":49,"[$-404]e/m/d":27,"m/d/yy":30,t0:59,"t0.00":60,"t#,##0":61,"t#,##0.00":62,"t0%":67,"t0.00%":68,"t# ?/?":69,"t# ??/??":70},w=t.Class.extend({init:function(t){this.options=t||{},this._strings={indexes:{},count:0,uniqueCount:0},this._styles=[],this._sheets=e.map(this.options.sheets||[],e.proxy(function(e){return new v(e,this._strings,this._styles)},this))},toDataURL:function(){var n,i,h,m,v,w,b,y,k,x,C,S,T,D;if("undefined"==typeof JSZip)throw Error("JSZip not found. Check http://docs.telerik.com/kendo-ui/framework/excel/introduction#requirements for more details.");for(n=new JSZip,i=n.folder("docProps"),i.file("core.xml",l({creator:this.options.creator||"Kendo UI",lastModifiedBy:this.options.creator||"Kendo UI",created:this.options.date||(new Date).toJSON(),modified:this.options.date||(new Date).toJSON()})),h=this._sheets.length,i.file("app.xml",c({sheets:this._sheets})),m=n.folder("_rels"),m.file(".rels",s),v=n.folder("xl"),w=v.folder("_rels"),w.file("workbook.xml.rels",p({count:h})),v.file("workbook.xml",u({sheets:this._sheets,definedNames:e.map(this._sheets,function(e,t){var n=e.options,i=n.filter;return i?{localSheetId:t,name:n.title||"Sheet"+(t+1),from:r(o(n),i.from),to:r(o(n),i.to)}:void 0})})),b=v.folder("worksheets"),y=new Date,k=0;h>k;k++)b.file(t.format("sheet{0}.xml",k+1),this._sheets[k].toXML(k));return x=e.map(this._styles,e.parseJSON),C=function(e){return e.underline||e.bold||e.italic||e.color||e.fontName||e.fontSize},S=e.map(x,function(e){return e.color&&(e.color=a(e.color)),C(e)?e:void 0}),T=e.map(x,function(e){return e.format&&void 0===_[e.format]?e:void 0}),D=e.map(x,function(e){return e.background?(e.background=a(e.background),e):void 0}),v.file("styles.xml",g({fonts:S,fills:D,formats:T,styles:e.map(x,function(t){var n={};return C(t)&&(n.fontId=e.inArray(t,S)+1),t.background&&(n.fillId=e.inArray(t,D)+2),n.hAlign=t.hAlign,n.vAlign=t.vAlign,n.wrap=t.wrap,t.format&&(n.numFmtId=void 0!==_[t.format]?_[t.format]:165+e.inArray(t,T)),n})})),v.file("sharedStrings.xml",f(this._strings)),n.file("[Content_Types].xml",d({count:h})),"data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,"+n.generate({compression:"DEFLATE"})}});t.ooxml={Workbook:w,Worksheet:v}}(kendo.jQuery,kendo),function(e,t){t.ExcelExporter=t.Class.extend({init:function(n){var i,r;n.columns=this._trimColumns(n.columns||[]),this.allColumns=e.map(this._leafColumns(n.columns||[]),this._prepareColumn),this.columns=e.grep(this.allColumns,function(e){return!e.hidden}),this.options=n,i=n.dataSource,i instanceof t.data.DataSource?(this.dataSource=new i.constructor(e.extend({},i.options,{page:n.allPages?0:i.page(),filter:i.filter(),pageSize:n.allPages?i.total():i.pageSize(),sort:i.sort(),group:i.group(),aggregate:i.aggregate()})),r=i.data(),r.length>0&&(this.dataSource._data=r)):this.dataSource=t.data.DataSource.create(i)},_trimColumns:function(t){var n=this;return e.grep(t,function(e){var t=!!e.field;return!t&&e.columns&&(t=n._trimColumns(e.columns).length>0),t})},_leafColumns:function(e){var t,n=[];for(t=0;e.length>t;t++)e[t].columns?n=n.concat(this._leafColumns(e[t].columns)):n.push(e[t]);return n},workbook:function(){return e.Deferred(e.proxy(function(t){this.dataSource.fetch().then(e.proxy(function(){var e={sheets:[{columns:this._columns(),rows:this._rows(),freezePane:this._freezePane(),filter:this._filter()}]};t.resolve(e,this.dataSource.view())},this))},this)).promise()},_prepareColumn:function(n){var i,r;if(n.field)return i=function(e){return e.get(n.field)},r=null,n.values&&(r={},e.each(n.values,function(){r[this.value]=this.text}),i=function(e){return r[e.get(n.field)]}),e.extend({},n,{value:i,values:r,groupHeaderTemplate:t.template(n.groupHeaderTemplate||"${title}: ${value}"),groupFooterTemplate:n.groupFooterTemplate?t.template(n.groupFooterTemplate):null,footerTemplate:n.footerTemplate?t.template(n.footerTemplate):null})},_filter:function(){if(!this.options.filterable)return null;var e=this._depth();return{from:e,to:e+this.columns.length-1}},_dataRow:function(t,n,i){var r,o,a,s,l,c,d,u,h,p;for(this._hierarchical()&&(n=this.dataSource.level(t)+1),r=[],o=0;n>o;o++)r[o]={background:"#dfdfdf",color:"#333"};if(i&&t.items)return a=e.grep(this.allColumns,function(e){return e.field==t.field})[0],s=a&&a.title?a.title:t.field,l=a?a.groupHeaderTemplate:null,c=s+": "+t.value,d=e.extend({title:s,field:t.field,value:a&&a.values?a.values[t.value]:t.value,aggregates:t.aggregates},t.aggregates[t.field]),l&&(c=l(d)),r.push({value:c,background:"#dfdfdf",color:"#333",colSpan:this.columns.length+i-n}),u=this._dataRows(t.items,n+1),u.unshift({type:"group-header",cells:r}),u.concat(this._footer(t));for(h=[],p=0;this.columns.length>p;p++)h[p]=this._cell(t,this.columns[p]);return this._hierarchical()&&(h[0].colSpan=i-n+1),[{type:"data",cells:r.concat(h)}]},_dataRows:function(e,t){var n,i=this._depth(),r=[];for(n=0;e.length>n;n++)r.push.apply(r,this._dataRow(e[n],t,i));return r},_footer:function(t){var n=[],i=!1,r=e.map(this.columns,e.proxy(function(n){return n.groupFooterTemplate?(i=!0,{background:"#dfdfdf",color:"#333",value:n.groupFooterTemplate(e.extend({},this.dataSource.aggregates(),t.aggregates,t.aggregates[n.field]))}):{background:"#dfdfdf",color:"#333"}},this));return i&&n.push({type:"group-footer",cells:e.map(Array(this.dataSource.group().length),function(){return{background:"#dfdfdf",color:"#333"}}).concat(r)}),n},_isColumnVisible:function(e){return this._visibleColumns([e]).length>0&&(e.field||e.columns)},_visibleColumns:function(t){var n=this;return e.grep(t,function(e){var t=!e.hidden;return t&&e.columns&&(t=n._visibleColumns(e.columns).length>0),t})},_headerRow:function(t,n){var i=e.map(t.cells,function(e){return{background:"#7a7a7a",color:"#fff",value:e.title,colSpan:e.colSpan>1?e.colSpan:1,rowSpan:t.rowSpan>1&&!e.colSpan?t.rowSpan:1}});return this._hierarchical()&&(i[0].colSpan=this._depth()+1),{type:"header",cells:e.map(Array(n.length),function(){return{background:"#7a7a7a",color:"#fff"}}).concat(i)}},_prependHeaderRows:function(e){var t,n=this.dataSource.group(),i=[{rowSpan:1,cells:[],index:0}];for(this._prepareHeaderRows(i,this.options.columns),t=i.length-1;t>=0;t--)e.unshift(this._headerRow(i[t],n))},_prepareHeaderRows:function(e,t,n,i){var r,o,a,s=i||e[e.length-1],l=e[s.index+1],c=0;for(a=0;t.length>a;a++)r=t[a],this._isColumnVisible(r)&&(o={title:r.title||r.field,colSpan:0},s.cells.push(o),r.columns&&r.columns.length&&(l||(l={rowSpan:0,cells:[],index:e.length},e.push(l)),o.colSpan=this._trimColumns(this._visibleColumns(r.columns)).length,this._prepareHeaderRows(e,r.columns,o,l),c+=o.colSpan-1,s.rowSpan=e.length-s.index));n&&(n.colSpan+=c)},_rows:function(){var t,n,i=this.dataSource.group(),r=this._dataRows(this.dataSource.view(),0);return this.columns.length&&(this._prependHeaderRows(r),t=!1,n=e.map(this.columns,e.proxy(function(n){if(n.footerTemplate){t=!0;var i=this.dataSource.aggregates();return{background:"#dfdfdf",color:"#333",value:n.footerTemplate(e.extend({},i,i[n.field]))}}return{background:"#dfdfdf",color:"#333"}},this)),t&&r.push({type:"footer",cells:e.map(Array(i.length),function(){return{background:"#dfdfdf",color:"#333"}}).concat(n)})),r},_headerDepth:function(e){var t,n,i=1,r=0;for(t=0;e.length>t;t++)e[t].columns&&(n=this._headerDepth(e[t].columns),n>r&&(r=n));return i+r},_freezePane:function(){var t=this._visibleColumns(this.options.columns||[]),n=this._trimColumns(this._leafColumns(e.grep(t,function(e){return e.locked}))).length;return{rowSplit:this._headerDepth(t),colSplit:n?n+this.dataSource.group().length:0}},_cell:function(e,t){return{value:t.value(e)}},_hierarchical:function(){return this.options.hierarchy&&this.dataSource.level},_depth:function(){var e,t,n,i=this.dataSource,r=0;if(this._hierarchical()){for(e=i.view(),t=0;e.length>t;t++)n=i.level(e[t]),n>r&&(r=n);r++}else r=i.group().length;return r},_columns:function(){var t=this._depth(),n=e.map(Array(t),function(){return{width:20}});return n.concat(e.map(this.columns,function(e){return{width:parseInt(e.width,10),autoWidth:e.width?!1:!0}}))}}),t.ExcelMixin={extend:function(t){t.events.push("excelExport"),t.options.excel=e.extend(t.options.excel,this.options),t.saveAsExcel=this.saveAsExcel},options:{proxyURL:"",allPages:!1,filterable:!1,fileName:"Export.xlsx"},saveAsExcel:function(){var n=this.options.excel||{},i=new t.ExcelExporter({columns:this.columns,dataSource:this.dataSource,allPages:n.allPages,filterable:n.filterable,hierarchy:n.hierarchy});i.workbook().then(e.proxy(function(e,i){if(!this.trigger("excelExport",{workbook:e,data:i})){var r=new t.ooxml.Workbook(e);t.saveAs({dataURI:r.toDataURL(),fileName:e.fileName||n.fileName,proxyURL:n.proxyURL,forceProxy:n.forceProxy})}},this))}}}(kendo.jQuery,kendo),function(e){var t=kendo.data.RemoteTransport.extend({init:function(e){var t,n=e&&e.signalr?e.signalr:{},i=n.promise;if(!i)throw Error('The "promise" option must be set.');if("function"!=typeof i.done||"function"!=typeof i.fail)throw Error('The "promise" option must be a Promise.');if(this.promise=i,t=n.hub,!t)throw Error('The "hub" option must be set.');if("function"!=typeof t.on||"function"!=typeof t.invoke)throw Error('The "hub" option is not a valid SignalR hub proxy.');this.hub=t,kendo.data.RemoteTransport.fn.init.call(this,e)},push:function(e){var t=this.options.signalr.client||{};t.create&&this.hub.on(t.create,e.pushCreate),t.update&&this.hub.on(t.update,e.pushUpdate),t.destroy&&this.hub.on(t.destroy,e.pushDestroy)},_crud:function(t,n){var i,r,o=this.hub,a=this.options.signalr.server;if(!a||!a[n])throw Error(kendo.format('The "server.{0}" option must be set.',n));i=[a[n]],r=this.parameterMap(t.data,n),e.isEmptyObject(r)||i.push(r),this.promise.done(function(){o.invoke.apply(o,i).done(t.success).fail(t.error)})},read:function(e){this._crud(e,"read")},create:function(e){this._crud(e,"create")},update:function(e){this._crud(e,"update")},destroy:function(e){this._crud(e,"destroy")}});e.extend(!0,kendo.data,{transports:{signalr:t}})}(window.kendo.jQuery),function(e,t,n){function i(e,r){var a,d;if(null==e||"none"==e)return null;if(e instanceof s)return e;if(e=e.toLowerCase(),a=o.exec(e))return e="transparent"==a[1]?new l(1,1,1,0):i(u.namedColors[a[1]],r),e.match=[a[1]],e;if((a=/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\b/i.exec(e))?d=new c(n(a[1],16),n(a[2],16),n(a[3],16),1):(a=/^#?([0-9a-f])([0-9a-f])([0-9a-f])\b/i.exec(e))?d=new c(n(a[1]+a[1],16),n(a[2]+a[2],16),n(a[3]+a[3],16),1):(a=/^rgb\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/.exec(e))?d=new c(n(a[1],10),n(a[2],10),n(a[3],10),1):(a=/^rgba\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9.]+)\s*\)/.exec(e))?d=new c(n(a[1],10),n(a[2],10),n(a[3],10),t(a[4])):(a=/^rgb\(\s*([0-9]*\.?[0-9]+)%\s*,\s*([0-9]*\.?[0-9]+)%\s*,\s*([0-9]*\.?[0-9]+)%\s*\)/.exec(e))?d=new l(t(a[1])/100,t(a[2])/100,t(a[3])/100,1):(a=/^rgba\(\s*([0-9]*\.?[0-9]+)%\s*,\s*([0-9]*\.?[0-9]+)%\s*,\s*([0-9]*\.?[0-9]+)%\s*,\s*([0-9.]+)\s*\)/.exec(e))&&(d=new l(t(a[1])/100,t(a[2])/100,t(a[3])/100,t(a[4]))),d)d.match=a;else if(!r)throw Error("Cannot parse color: "+e);return d}function r(e,t,n){for(n||(n="0"),e=e.toString(16);t>e.length;)e="0"+e;return e}var o,a,s,l,c,d,u=function(e){var t,n,i,r,o,a=this,s=u.formats;if(1===arguments.length)for(e=a.resolveColor(e),r=0;s.length>r;r++)t=s[r].re,n=s[r].process,i=t.exec(e),i&&(o=n(i),a.r=o[0],a.g=o[1],a.b=o[2]);else a.r=arguments[0],a.g=arguments[1],a.b=arguments[2];a.r=a.normalizeByte(a.r),a.g=a.normalizeByte(a.g),a.b=a.normalizeByte(a.b)};u.prototype={toHex:function(){var e=this,t=e.padDigit,n=e.r.toString(16),i=e.g.toString(16),r=e.b.toString(16);return"#"+t(n)+t(i)+t(r)},resolveColor:function(e){return e=e||"black","#"==e.charAt(0)&&(e=e.substr(1,6)),e=e.replace(/ /g,""),e=e.toLowerCase(),e=u.namedColors[e]||e},normalizeByte:function(e){return 0>e||isNaN(e)?0:e>255?255:e},padDigit:function(e){return 1===e.length?"0"+e:e},brightness:function(e){var t=this,n=Math.round;return t.r=n(t.normalizeByte(t.r*e)),t.g=n(t.normalizeByte(t.g*e)),t.b=n(t.normalizeByte(t.b*e)),t},percBrightness:function(){var e=this;return Math.sqrt(.241*e.r*e.r+.691*e.g*e.g+.068*e.b*e.b)}},u.formats=[{re:/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,process:function(e){return[n(e[1],10),n(e[2],10),n(e[3],10)]}},{re:/^(\w{2})(\w{2})(\w{2})$/,process:function(e){return[n(e[1],16),n(e[2],16),n(e[3],16)]}},{re:/^(\w{1})(\w{1})(\w{1})$/,process:function(e){return[n(e[1]+e[1],16),n(e[2]+e[2],16),n(e[3]+e[3],16)]}}],u.namedColors={aqua:"00ffff",azure:"f0ffff",beige:"f5f5dc",black:"000000",blue:"0000ff",brown:"a52a2a",coral:"ff7f50",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgray:"a9a9a9",darkgreen:"006400",darkorange:"ff8c00",darkred:"8b0000",dimgray:"696969",fuchsia:"ff00ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lightblue:"add8e6",lightgrey:"d3d3d3",lightgreen:"90ee90",lightpink:"ffb6c1",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumblue:"0000cd",navy:"000080",olive:"808000",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",pink:"ffc0cb",plum:"dda0dd",purple:"800080",red:"ff0000",royalblue:"4169e1",salmon:"fa8072",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",snow:"fffafa",steelblue:"4682b4",tan:"d2b48c",teal:"008080",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32"},o=["transparent"];for(a in u.namedColors)u.namedColors.hasOwnProperty(a)&&o.push(a);o=RegExp("^("+o.join("|")+")(\\W|$)","i"),s=kendo.Class.extend({toHSV:function(){return this},toRGB:function(){return this},toHex:function(){return this.toBytes().toHex()},toBytes:function(){return this},toCss:function(){return"#"+this.toHex()},toCssRgba:function(){var e=this.toBytes();return"rgba("+e.r+", "+e.g+", "+e.b+", "+t((+this.a).toFixed(3))+")"},toDisplay:function(){return kendo.support.browser.msie&&9>kendo.support.browser.version?this.toCss():this.toCssRgba()},equals:function(e){return e===this||null!==e&&this.toCssRgba()==i(e).toCssRgba()},diff:function(e){if(null==e)return 0/0;var t=this.toBytes();return e=e.toBytes(),Math.sqrt(Math.pow(.3*(t.r-e.r),2)+Math.pow(.59*(t.g-e.g),2)+Math.pow(.11*(t.b-e.b),2))},clone:function(){var e=this.toBytes();return e===this&&(e=new c(e.r,e.g,e.b,e.a)),e}}),l=s.extend({init:function(e,t,n,i){this.r=e,this.g=t,this.b=n,this.a=i},toHSV:function(){var e,t,n=this.r,i=this.g,r=this.b,o=Math.min(n,i,r),a=Math.max(n,i,r),s=a,l=a-o;return 0===l?new d(0,0,s,this.a):(0!==a?(t=l/a,e=n==a?(i-r)/l:i==a?2+(r-n)/l:4+(n-i)/l,e*=60,0>e&&(e+=360)):(t=0,e=-1),new d(e,t,s,this.a))},toBytes:function(){return new c(255*this.r,255*this.g,255*this.b,this.a)}}),c=l.extend({init:function(e,t,n,i){this.r=Math.round(e),this.g=Math.round(t),this.b=Math.round(n),this.a=i},toRGB:function(){return new l(this.r/255,this.g/255,this.b/255,this.a)},toHSV:function(){return this.toRGB().toHSV()},toHex:function(){return r(this.r,2)+r(this.g,2)+r(this.b,2)},toBytes:function(){return this}}),d=s.extend({init:function(e,t,n,i){this.h=e,this.s=t,this.v=n,this.a=i},toRGB:function(){var e,t,n,i,r,o,a,s,c=this.h,d=this.s,u=this.v;if(0===d)t=n=i=u;else switch(c/=60,e=Math.floor(c),r=c-e,o=u*(1-d),a=u*(1-d*r),s=u*(1-d*(1-r)),e){case 0:t=u,n=s,i=o;break;case 1:t=a,n=u,i=o;break;case 2:t=o,n=u,i=s;break;case 3:t=o,n=a,i=u;break;case 4:t=s,n=o,i=u;break;default:t=u,n=o,i=a}return new l(t,n,i,this.a)},toBytes:function(){return this.toRGB().toBytes()}}),u.fromBytes=function(e,t,n,i){return new c(e,t,n,null!=i?i:1)},u.fromRGB=function(e,t,n,i){return new l(e,t,n,null!=i?i:1)},u.fromHSV=function(e,t,n,i){return new d(e,t,n,null!=i?i:1)},kendo.Color=u,kendo.parseColor=i}(window.kendo.jQuery,parseFloat,parseInt),function(e){function t(e){return typeof e!==F}function n(e,t){var n=i(t);return A.round(e*n)/n}function i(e){return e?A.pow(10,e):1}function r(e,t,n){return A.max(A.min(e,n),t)}function o(e){return e*P}function a(e){return e/P}function s(e){return"number"==typeof e&&!isNaN(e)}function l(e,n){return t(e)?e:n}function c(e){return e*e}function d(e){var t,n=[];for(t in e)n.push(t+e[t]);return n.sort().join("")}function u(e){var t,n=2166136261;for(t=0;e.length>t;++t)n+=(n<<1)+(n<<4)+(n<<7)+(n<<8)+(n<<24),n^=e.charCodeAt(t);return n>>>0}function h(e){return u(d(e))}function p(e){var t,n=e.length,i=M,r=z;for(t=0;n>t;t++)r=A.max(r,e[t]),i=A.min(i,e[t]);return{min:i,max:r}}function f(e){return p(e).min}function g(e){return p(e).max}function m(e){return _(e).min}function v(e){return _(e).max}function _(e){var t,n,i,r=M,o=z;for(t=0,n=e.length;n>t;t++)i=e[t],null!==i&&isFinite(i)&&(r=A.min(r,i),o=A.max(o,i));return{min:r===M?void 0:r,max:o===z?void 0:o}}function w(e){return e?e[e.length-1]:void 0}function b(e,t){return e.push.apply(e,t),e}function y(e){return E.template(e,{useWithBlock:!1,paramName:"d"})}function k(e,n){return t(n)&&null!==n?" "+e+"='"+n+"' ":""}function x(e){var t,n="";for(t=0;e.length>t;t++)n+=k(e[t][0],e[t][1]);return n}function C(e){var n,i,r="";for(n=0;e.length>n;n++)i=e[n][1],t(i)&&(r+=e[n][0]+":"+i+";");return""!==r?r:void 0}function S(e){return"string"!=typeof e&&(e+="px"),e}function T(e){var t,n,i=[];if(e)for(t=E.toHyphens(e).split("-"),n=0;t.length>n;n++)i.push("k-pos-"+t[n]);return i.join(" ")}function D(e){return""===e||null===e||"none"===e||"transparent"===e||!t(e)}var A=Math,E=window.kendo,I=E.deepExtend,P=A.PI/180,M=Number.MAX_VALUE,z=-Number.MAX_VALUE,F="undefined",R=Date.now;R||(R=function(){return(new Date).getTime()}),I(E,{util:{MAX_NUM:M,MIN_NUM:z,append:b,arrayLimits:p,arrayMin:f,arrayMax:g,defined:t,deg:a,hashKey:u,hashObject:h,isNumber:s,isTransparent:D,last:w,limitValue:r,now:R,objectKey:d,round:n,rad:o,renderAttr:k,renderAllAttr:x,renderPos:T,renderSize:S,renderStyle:C,renderTemplate:y,sparseArrayLimits:_,sparseArrayMin:m,sparseArrayMax:v,sqr:c,valueOrDefault:l}}),E.dataviz.util=E.util}(window.kendo.jQuery),function(){function e(e){var n,i,r,a,s,l,c,d="",u=0;for(e=t(e);e.length>u;)n=e.charCodeAt(u++),i=e.charCodeAt(u++),r=e.charCodeAt(u++),a=n>>2,s=(3&n)<<4|i>>4,l=(15&i)<<2|r>>6,c=63&r,isNaN(i)?l=c=64:isNaN(r)&&(c=64),d=d+o.charAt(a)+o.charAt(s)+o.charAt(l)+o.charAt(c);return d}function t(e){var t,n,i="";for(t=0;e.length>t;t++)n=e.charCodeAt(t),128>n?i+=r(n):2048>n?(i+=r(192|n>>>6),i+=r(128|63&n)):65536>n&&(i+=r(224|n>>>12),i+=r(128|n>>>6&63),i+=r(128|63&n));return i}var n=window.kendo,i=n.deepExtend,r=String.fromCharCode,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i(n.util,{encodeBase64:e,encodeUTF8:t})}(window.kendo.jQuery),function(e){var t=Math,n=window.kendo,i=n.deepExtend,r=e.inArray,o={observers:function(){return this._observers=this._observers||[]},addObserver:function(e){return this._observers?this._observers.push(e):this._observers=[e],this},removeObserver:function(e){var t=this.observers(),n=r(e,t);return-1!=n&&t.splice(n,1),this},trigger:function(e,t){var n,i,r=this._observers;if(r&&!this._suspended)for(i=0;r.length>i;i++)n=r[i],n[e]&&n[e](t);return this},optionsChange:function(e){this.trigger("optionsChange",e)},geometryChange:function(e){this.trigger("geometryChange",e)},suspend:function(){return this._suspended=(this._suspended||0)+1,this},resume:function(){return this._suspended=t.max((this._suspended||0)-1,0),this},_observerField:function(e,t){this[e]&&this[e].removeObserver(this),this[e]=t,t.addObserver(this)}};i(n,{mixins:{ObserversMixin:o}})}(window.kendo.jQuery),function(e){function t(e){return null===e?null:e instanceof m?e:new m(e)}function n(e){return e&&w.isFunction(e.matrix)?e.matrix():e}function i(e,t,n,i){var r=0,o=0;return i&&(r=v.atan2(i.c*n,i.a*t),0!==i.b&&(o=v.atan2(i.d*n,i.b*t))),{x:r,y:o}}function r(e,t){for(;t>e;)e+=90;return e}function o(e,t){var n,i,r;for(n=0;t.length>n;n++)i=t[n],r=i.charAt(0).toUpperCase()+i.substring(1,i.length),e["set"+r]=a(i),e["get"+r]=s(i)}function a(e){return function(t){return this[e]!==t&&(this[e]=t,this.geometryChange()),this}}function s(e){return function(){return this[e]}}function l(e,t,n){e>t&&(t+=360);var i=v.abs(t-e);return n||(i=360-i),i}function c(e,t,n,i,r,o){var a=D((r-e)/n,3),s=D((o-t)/i,3);return D(T(v.atan2(s,a)))}function d(e,t,n,i,r,o,a,s){var d,u,h,p,f,g,m,w,b,y,k,x,C,S,T,D,A,E;if(t!==i)b=n-e,y=i-t,k=_(r,2),x=_(o,2),C=(x*b*(e+n)+k*y*(t+i))/(2*k*y),S=C-i,T=-(b*x)/(k*y),f=1/k+_(T,2)/x,g=2*(T*S/x-n/k),m=_(n,2)/k+_(S,2)/x-1,w=v.sqrt(_(g,2)-4*f*m),d=(-g-w)/(2*f),u=C+T*d,h=(-g+w)/(2*f),p=C+T*h;else{if(e===n)return!1;g=-2*i,m=_((n-e)*o/(2*r),2)+_(i,2)-_(o,2),w=v.sqrt(_(g,2)-4*m),d=h=(e+n)/2,u=(-g-w)/2,p=(-g+w)/2}return D=c(d,u,r,o,e,t),A=c(d,u,r,o,n,i),E=l(D,A,s),(a&&180>=E||!a&&E>180)&&(d=h,u=p,D=c(d,u,r,o,e,t),A=c(d,u,r,o,n,i)),{center:new P(d,u),startAngle:D,endAngle:A}}var u,h,p,f,g,m,v=Math,_=v.pow,w=window.kendo,b=w.Class,y=w.deepExtend,k=w.mixins.ObserversMixin,x=w.util,C=x.defined,S=x.rad,T=x.deg,D=x.round,A=v.PI/2,E=x.MIN_NUM,I=x.MAX_NUM,P=b.extend({init:function(e,t){this.x=e||0,this.y=t||0},equals:function(e){return e&&e.x===this.x&&e.y===this.y},clone:function(){return new P(this.x,this.y)},rotate:function(e,n){return this.transform(t().rotate(e,n))},translate:function(e,t){return this.x+=e,this.y+=t,this.geometryChange(),this},translateWith:function(e){return this.translate(e.x,e.y)},move:function(e,t){return this.x=this.y=0,this.translate(e,t)},scale:function(e,t){return C(t)||(t=e),this.x*=e,this.y*=t,this.geometryChange(),this},scaleCopy:function(e,t){return this.clone().scale(e,t)},transform:function(e){var t=n(e),i=this.x,r=this.y;return this.x=t.a*i+t.c*r+t.e,this.y=t.b*i+t.d*r+t.f,this.geometryChange(),this},transformCopy:function(e){var t=this.clone();return e&&t.transform(e),t},distanceTo:function(e){var t=this.x-e.x,n=this.y-e.y;return v.sqrt(t*t+n*n)},round:function(e){return this.x=D(this.x,e),this.y=D(this.y,e),this.geometryChange(),this},toArray:function(e){var t=C(e),n=t?D(this.x,e):this.x,i=t?D(this.y,e):this.y;return[n,i]}});o(P.fn,["x","y"]),y(P.fn,k),P.fn.toString=function(e,t){var n=this.x,i=this.y;return C(e)&&(n=D(n,e),i=D(i,e)),t=t||" ",n+t+i},P.create=function(e,t){return C(e)?e instanceof P?e:1===arguments.length&&2===e.length?new P(e[0],e[1]):new P(e,t):void 0},P.min=function(){var e,t,n=x.MAX_NUM,i=x.MAX_NUM;for(e=0;arguments.length>e;e++)t=arguments[e],n=v.min(t.x,n),i=v.min(t.y,i);return new P(n,i)},P.max=function(){var e,t,n=x.MIN_NUM,i=x.MIN_NUM;for(e=0;arguments.length>e;e++)t=arguments[e],n=v.max(t.x,n),i=v.max(t.y,i);return new P(n,i)},P.minPoint=function(){return new P(E,E)},P.maxPoint=function(){return new P(I,I)},P.ZERO=new P(0,0),u=b.extend({init:function(e,t){this.width=e||0,this.height=t||0},equals:function(e){return e&&e.width===this.width&&e.height===this.height},clone:function(){return new u(this.width,this.height)},toArray:function(e){var t=C(e),n=t?D(this.width,e):this.width,i=t?D(this.height,e):this.height;return[n,i]}}),o(u.fn,["width","height"]),y(u.fn,k),u.create=function(e,t){return C(e)?e instanceof u?e:1===arguments.length&&2===e.length?new u(e[0],e[1]):new u(e,t):void 0},u.ZERO=new u(0,0),h=b.extend({init:function(e,t){this.setOrigin(e||new P),this.setSize(t||new u)},clone:function(){return new h(this.origin.clone(),this.size.clone())},equals:function(e){return e&&e.origin.equals(this.origin)&&e.size.equals(this.size)},setOrigin:function(e){return this._observerField("origin",P.create(e)),this.geometryChange(),this},getOrigin:function(){return this.origin},setSize:function(e){return this._observerField("size",u.create(e)),this.geometryChange(),this},getSize:function(){return this.size},width:function(){return this.size.width},height:function(){return this.size.height},topLeft:function(){return this.origin.clone()},bottomRight:function(){return this.origin.clone().translate(this.width(),this.height())},topRight:function(){return this.origin.clone().translate(this.width(),0)},bottomLeft:function(){return this.origin.clone().translate(0,this.height())},center:function(){return this.origin.clone().translate(this.width()/2,this.height()/2)},bbox:function(e){var t=this.topLeft().transformCopy(e),n=this.topRight().transformCopy(e),i=this.bottomRight().transformCopy(e),r=this.bottomLeft().transformCopy(e);return h.fromPoints(t,n,i,r)},transformCopy:function(e){return h.fromPoints(this.topLeft().transform(e),this.bottomRight().transform(e))}}),y(h.fn,k),h.fromPoints=function(){var e=P.min.apply(this,arguments),t=P.max.apply(this,arguments),n=new u(t.x-e.x,t.y-e.y);return new h(e,n)},h.union=function(e,t){return h.fromPoints(P.min(e.topLeft(),t.topLeft()),P.max(e.bottomRight(),t.bottomRight()))},h.intersect=function(e,t){return e={left:e.topLeft().x,top:e.topLeft().y,right:e.bottomRight().x,bottom:e.bottomRight().y},t={left:t.topLeft().x,top:t.topLeft().y,right:t.bottomRight().x,bottom:t.bottomRight().y},t.right>=e.left&&e.right>=t.left&&t.bottom>=e.top&&e.bottom>=t.top?h.fromPoints(new P(v.max(e.left,t.left),v.max(e.top,t.top)),new P(v.min(e.right,t.right),v.min(e.bottom,t.bottom))):void 0},p=b.extend({init:function(e,t){this.setCenter(e||new P),this.setRadius(t||0)},setCenter:function(e){return this._observerField("center",P.create(e)),this.geometryChange(),this},getCenter:function(){return this.center},equals:function(e){return e&&e.center.equals(this.center)&&e.radius===this.radius},clone:function(){return new p(this.center.clone(),this.radius)},pointAt:function(e){return this._pointAt(S(e))},bbox:function(e){var t,n,r,o,a=P.maxPoint(),s=P.minPoint(),l=i(this.center,this.radius,this.radius,e);for(t=0;4>t;t++)n=this._pointAt(l.x+t*A).transformCopy(e),r=this._pointAt(l.y+t*A).transformCopy(e),o=new P(n.x,r.y),a=P.min(a,o),s=P.max(s,o);return h.fromPoints(a,s)},_pointAt:function(e){var t=this.center,n=this.radius;return new P(t.x-n*v.cos(e),t.y-n*v.sin(e))}}),o(p.fn,["radius"]),y(p.fn,k),f=b.extend({init:function(e,t){this.setCenter(e||new P),t=t||{},this.radiusX=t.radiusX,this.radiusY=t.radiusY||t.radiusX,this.startAngle=t.startAngle,this.endAngle=t.endAngle,this.anticlockwise=t.anticlockwise||!1},clone:function(){return new f(this.center,{radiusX:this.radiusX,radiusY:this.radiusY,startAngle:this.startAngle,endAngle:this.endAngle,anticlockwise:this.anticlockwise})},setCenter:function(e){return this._observerField("center",P.create(e)),this.geometryChange(),this},getCenter:function(){return this.center},MAX_INTERVAL:45,pointAt:function(e){var t=this.center,n=S(e);return new P(t.x+this.radiusX*v.cos(n),t.y+this.radiusY*v.sin(n))},curvePoints:function(){var e,t,n,i=this.startAngle,r=this.anticlockwise?-1:1,o=[this.pointAt(i)],a=i,s=this._arcInterval(),l=s.endAngle-s.startAngle,c=v.ceil(l/this.MAX_INTERVAL),d=l/c;for(e=1;c>=e;e++)t=a+r*d,n=this._intervalCurvePoints(a,t),o.push(n.cp1,n.cp2,n.p2),a=t;return o},bbox:function(e){for(var t,n,o=this,a=o._arcInterval(),s=a.startAngle,l=a.endAngle,c=i(this.center,this.radiusX,this.radiusY,e),d=T(c.x),u=T(c.y),p=o.pointAt(s).transformCopy(e),f=o.pointAt(l).transformCopy(e),g=P.min(p,f),m=P.max(p,f),v=r(d,s),_=r(u,s);l>v||l>_;)l>v&&(t=o.pointAt(v).transformCopy(e),v+=90),l>_&&(n=o.pointAt(_).transformCopy(e),_+=90),p=new P(t.x,n.y),g=P.min(g,p),m=P.max(m,p);return h.fromPoints(g,m)},_arcInterval:function(){var e,t=this.startAngle,n=this.endAngle,i=this.anticlockwise;return i&&(e=t,t=n,n=e),(t>n||i&&t===n)&&(n+=360),{startAngle:t,endAngle:n}},_intervalCurvePoints:function(e,t){var n=this,i=n.pointAt(e),r=n.pointAt(t),o=n._derivativeAt(e),a=n._derivativeAt(t),s=(S(t)-S(e))/3,l=new P(i.x+s*o.x,i.y+s*o.y),c=new P(r.x-s*a.x,r.y-s*a.y);return{p1:i,cp1:l,cp2:c,p2:r}},_derivativeAt:function(e){var t=this,n=S(e);return new P(-t.radiusX*v.sin(n),t.radiusY*v.cos(n))}}),o(f.fn,["radiusX","radiusY","startAngle","endAngle","anticlockwise"]),y(f.fn,k),f.fromPoints=function(e,t,n,i,r,o){var a=d(e.x,e.y,t.x,t.y,n,i,r,o);return new f(a.center,{startAngle:a.startAngle,endAngle:a.endAngle,radiusX:n,radiusY:i,anticlockwise:0===o})},g=b.extend({init:function(e,t,n,i,r,o){this.a=e||0,this.b=t||0,this.c=n||0,this.d=i||0,this.e=r||0,this.f=o||0},multiplyCopy:function(e){return new g(this.a*e.a+this.c*e.b,this.b*e.a+this.d*e.b,this.a*e.c+this.c*e.d,this.b*e.c+this.d*e.d,this.a*e.e+this.c*e.f+this.e,this.b*e.e+this.d*e.f+this.f)},invert:function(){var e=this.a,t=this.b,n=this.c,i=this.d,r=this.e,o=this.f,a=e*i-t*n;return 0===a?null:new g(i/a,-t/a,-n/a,e/a,(n*o-i*r)/a,(t*r-e*o)/a)},clone:function(){return new g(this.a,this.b,this.c,this.d,this.e,this.f)},equals:function(e){return e?this.a===e.a&&this.b===e.b&&this.c===e.c&&this.d===e.d&&this.e===e.e&&this.f===e.f:!1},round:function(e){return this.a=D(this.a,e),this.b=D(this.b,e),this.c=D(this.c,e),this.d=D(this.d,e),this.e=D(this.e,e),this.f=D(this.f,e),this},toArray:function(e){var t,n=[this.a,this.b,this.c,this.d,this.e,this.f];if(C(e))for(t=0;n.length>t;t++)n[t]=D(n[t],e);return n}}),g.fn.toString=function(e,t){return this.toArray(e).join(t||",")},g.translate=function(e,t){return new g(1,0,0,1,e,t)},g.unit=function(){return new g(1,0,0,1,0,0)},g.rotate=function(e,t,n){var i=new g;return i.a=v.cos(S(e)),i.b=v.sin(S(e)),i.c=-i.b,i.d=i.a,i.e=t-t*i.a+n*i.b||0,i.f=n-n*i.a-t*i.b||0,i},g.scale=function(e,t){return new g(e,0,0,t,0,0)},g.IDENTITY=g.unit(),m=b.extend({init:function(e){this._matrix=e||g.unit()},clone:function(){return new m(this._matrix.clone())},equals:function(e){return e&&e._matrix.equals(this._matrix) -},_optionsChange:function(){this.optionsChange({field:"transform",value:this})},translate:function(e,t){return this._matrix=this._matrix.multiplyCopy(g.translate(e,t)),this._optionsChange(),this},scale:function(e,t,n){return C(t)||(t=e),n&&(n=P.create(n),this._matrix=this._matrix.multiplyCopy(g.translate(n.x,n.y))),this._matrix=this._matrix.multiplyCopy(g.scale(e,t)),n&&(this._matrix=this._matrix.multiplyCopy(g.translate(-n.x,-n.y))),this._optionsChange(),this},rotate:function(e,t){return t=P.create(t)||P.ZERO,this._matrix=this._matrix.multiplyCopy(g.rotate(e,t.x,t.y)),this._optionsChange(),this},multiply:function(e){var t=n(e);return this._matrix=this._matrix.multiplyCopy(t),this._optionsChange(),this},matrix:function(){return this._matrix}}),y(m.fn,k),y(w,{geometry:{Arc:f,Circle:p,Matrix:g,Point:P,Rect:h,Size:u,Transformation:m,transform:t,toMatrix:n}}),w.dataviz.geometry=w.geometry}(window.kendo.jQuery),function(e){var t,n,i,r=e.noop,o=Object.prototype.toString,a=window.kendo,s=a.Class,l=a.ui.Widget,c=a.deepExtend,d=a.util,u=d.defined,h=l.extend({init:function(e,t){this.options=c({},this.options,t),l.fn.init.call(this,e,this.options),this._click=this._handler("click"),this._mouseenter=this._handler("mouseenter"),this._mouseleave=this._handler("mouseleave"),this._visual=new a.drawing.Group,this.options.width&&this.element.css("width",this.options.width),this.options.height&&this.element.css("height",this.options.height)},options:{name:"Surface"},events:["click","mouseenter","mouseleave","resize"],draw:function(e){this._visual.children.push(e)},clear:function(){this._visual.children=[]},destroy:function(){this._visual=null,l.fn.destroy.call(this)},exportVisual:function(){return this._visual},getSize:function(){return{width:this.element.width(),height:this.element.height()}},setSize:function(e){this.element.css({width:e.width,height:e.height}),this._size=e,this._resize()},eventTarget:function(t){for(var n,i=e(t.touch?t.touch.initialTouch:t.target);!n&&i.length>0&&(n=i[0]._kendoNode,!i.is(this.element)&&0!==i.length);)i=i.parent();return n?n.srcElement:void 0},_resize:r,_handler:function(e){var t=this;return function(n){var i=t.eventTarget(n);i&&t.trigger(e,{element:i,originalEvent:n})}}});a.ui.plugin(h),h.create=function(e,t){return i.current.create(e,t)},t=s.extend({init:function(e){this.childNodes=[],this.parent=null,e&&(this.srcElement=e,this.observe())},destroy:function(){var e,t;for(this.srcElement&&this.srcElement.removeObserver(this),e=this.childNodes,t=0;e.length>t;t++)this.childNodes[t].destroy();this.parent=null},load:r,observe:function(){this.srcElement&&this.srcElement.addObserver(this)},append:function(e){this.childNodes.push(e),e.parent=this},insertAt:function(e,t){this.childNodes.splice(t,0,e),e.parent=this},remove:function(e,t){var n,i=e+t;for(n=e;i>n;n++)this.childNodes[n].removeSelf();this.childNodes.splice(e,t)},removeSelf:function(){this.clear(),this.destroy()},clear:function(){this.remove(0,this.childNodes.length)},invalidate:function(){this.parent&&this.parent.invalidate()},geometryChange:function(){this.invalidate()},optionsChange:function(){this.invalidate()},childrenChange:function(e){"add"===e.action?this.load(e.items,e.index):"remove"===e.action&&this.remove(e.index,e.items.length),this.invalidate()}}),n=s.extend({init:function(e,t){var n,i;this.prefix=t||"";for(n in e)i=e[n],i=this._wrap(i,n),this[n]=i},get:function(e){return a.getter(e,!0)(this)},set:function(e,t){var n,i=a.getter(e,!0)(this);i!==t&&(n=this._set(e,this._wrap(t,e)),n||this.optionsChange({field:this.prefix+e,value:t}))},_set:function(e,t){var i,r,o,s=e.indexOf(".")>=0;if(s)for(i=e.split("."),r="";i.length>1;){if(r+=i.shift(),o=a.getter(r,!0)(this),o||(o=new n({},r+"."),o.addObserver(this),this[r]=o),o instanceof n)return o.set(i.join("."),t),s;r+="."}return this._clear(e),a.setter(e)(this,t),s},_clear:function(e){var t=a.getter(e,!0)(this);t&&t.removeObserver&&t.removeObserver(this)},_wrap:function(e,t){var i=o.call(e);return null!==e&&u(e)&&"[object Object]"===i&&(e instanceof n||e instanceof s||(e=new n(e,this.prefix+t+".")),e.addObserver(this)),e}}),c(n.fn,a.mixins.ObserversMixin),i=function(){this._items=[]},i.prototype={register:function(e,t,n){var i=this._items,r=i[0],o={name:e,type:t,order:n};!r||r.order>n?i.unshift(o):i.push(o)},create:function(e,t){var n,i,r=this._items,o=r[0];if(t&&t.type)for(n=t.type.toLowerCase(),i=0;r.length>i;i++)if(r[i].name===n){o=r[i];break}return o?new o.type(e,t):void a.logToConsole("Warning: Unable to create Kendo UI Drawing Surface. Possible causes:\n- The browser does not support SVG, VML and Canvas. User agent: "+navigator.userAgent+"\n- The Kendo UI scripts are not fully loaded")}},i.current=new i,c(a,{drawing:{DASH_ARRAYS:{dot:[1.5,3.5],dash:[4,3.5],longdash:[8,3.5],dashdot:[3.5,3.5,1.5,3.5],longdashdot:[8,3.5,1.5,3.5],longdashdotdot:[8,3.5,1.5,3.5,1.5,3.5]},Color:a.Color,BaseNode:t,OptionsStore:n,Surface:h,SurfaceFactory:i}}),a.dataviz.drawing=a.drawing}(window.kendo.jQuery),function(){var e=window.kendo,t=e.deepExtend,n=e.util.defined,i="gradient",r={extend:function(e){e.fill=this.fill,e.stroke=this.stroke},fill:function(e,t){var r,o=this.options;return n(e)?(e&&e.nodeType!=i?(r={color:e},n(t)&&(r.opacity=t),o.set("fill",r)):o.set("fill",e),this):o.get("fill")},stroke:function(e,t,i){return n(e)?(this.options.set("stroke.color",e),n(t)&&this.options.set("stroke.width",t),n(i)&&this.options.set("stroke.opacity",i),this):this.options.get("stroke")}},o={extend:function(e,t){e.traverse=function(e){var n,i,r=this[t];for(n=0;r.length>n;n++)i=r[n],i.traverse?i.traverse(e):e(i);return this}}};t(e.drawing,{mixins:{Paintable:r,Traversable:o}})}(window.kendo.jQuery),function(e){function t(e,t){return d.current.measure(e,t)}var n=document,i=window.kendo,r=i.Class,o=i.deepExtend,a=i.util,s=a.defined,l=1,c=r.extend({init:function(e){this._size=e,this._length=0,this._map={}},put:function(e,t){var n=this,i=n._map,r={key:e,value:t};i[e]=r,n._head?(n._tail.newer=r,r.older=n._tail,n._tail=r):n._head=n._tail=r,n._length>=n._size?(i[n._head.key]=null,n._head=n._head.newer,n._head.older=null):n._length++},get:function(e){var t=this,n=t._map[e];return n?(n===t._head&&n!==t._tail&&(t._head=n.newer,t._head.older=null),n!==t._tail&&(n.older&&(n.older.newer=n.newer,n.newer.older=n.older),n.older=t._tail,n.newer=null,t._tail.newer=n,t._tail=n),n.value):void 0}}),d=r.extend({init:function(){this._cache=new c(1e3)},measure:function(t,i){var r,o,c,d,u,h=a.objectKey(i),p=a.hashKey(t+h),f=this._cache.get(p);if(f)return f;r={width:0,height:0,baseline:0},o=this._measureBox,c=this._baselineMarker.cloneNode(!1);for(d in i)u=i[d],s(u)&&(o.style[d]=u);return e(o).text(t),o.appendChild(c),n.body.appendChild(o),(t+"").length&&(r.width=o.offsetWidth-l,r.height=o.offsetHeight,r.baseline=c.offsetTop+l),this._cache.put(p,r),o.parentNode.removeChild(o),r}});d.fn._baselineMarker=e("
    ")[0],d.fn._measureBox=e("
    ")[0],d.current=new d,o(i.drawing,{util:{TextMetrics:d,LRUCache:c,measureText:t}})}(window.kendo.jQuery),function(e){function t(e,t,n){var i,r,o,a;for(r=0;e.length>r;r++)o=e[r],o.visible()&&(a=t?o.bbox(n):o.rawBBox(),a&&(i=i?$.union(i,a):a));return i}function n(e,t){var n,i,r,o;for(i=0;e.length>i;i++)r=e[i],r.visible()&&(o=r.clippedBBox(t),o&&(n=n?$.union(n,o):o));return n}function i(e,t){e.origin.x-=t,e.origin.y-=t,e.size.width+=2*t,e.size.height+=2*t}function r(e,t){for(var n=0;t.length>n;n++)e[t[n]]=o(t[n])}function o(e){var t="_"+e;return function(e){return rt(e)?(this._observerField(t,e),this.geometryChange(),this):this[t]}}function a(e,t){for(var n=0;t.length>n;n++)e[t[n]]=s(t[n])}function s(e){var t="_"+e;return function(e){return rt(e)?(this._observerField(t,q.create(e)),this.geometryChange(),this):this[t]}}function l(e,t){for(var n=0;t.length>n;n++)e[t[n]]=c(t[n])}function c(e){return function(t){return rt(t)?(this.options.set(e,t),this):this.options.get(e)}}function d(){return"kdef"+gt++}function u(e,t,n){k(e,t,n,"x","width")}function h(e,t,n){k(e,t,n,"y","height")}function p(e){y(b(e),"x","y","width")}function f(e){y(b(e),"y","x","height")}function g(e,t){return v(e,t,"x","y","width")}function m(e,t){return v(e,t,"y","x","height")}function v(e,t,n,i,r){var o,a,s,l,c=[],d=w(e,t,r),u=t.origin.clone();for(l=0;d.length>l;l++)for(s=d[l],o=s[0],u[i]=o.bbox.origin[i],S(u,o.bbox,o.element),o.bbox.origin[n]=u[n],y(s,n,i,r),c.push([]),a=0;s.length>a;a++)c[l].push(s[a].element);return c}function _(e,t){var n,i,r=e.clippedBBox(),o=r.size,a=t.size;(o.width>a.width||o.height>a.height)&&(n=J.min(a.width/o.width,a.height/o.height),i=e.transform()||G.transform(),i.scale(n,n),e.transform(i))}function w(e,t,n){var i,r,o,a,s=t.size[n],l=0,c=[],d=[],u=function(){d.push({element:i,bbox:o})};for(a=0;e.length>a;a++)i=e[a],o=i.clippedBBox(),o&&(r=o.size[n],l+r>s?d.length?(c.push(d),d=[],u(),l=r):(u(),c.push(d),d=[],l=0):(u(),l+=r));return d.length&&c.push(d),c}function b(e){var t,n,i,r=[];for(i=0;e.length>i;i++)t=e[i],n=t.clippedBBox(),n&&r.push({element:t,bbox:n});return r}function y(e,t,n,i){var r,o,a,s,l;if(e.length>1)for(r=e[0].bbox,o=new q,l=1;e.length>l;l++)a=e[l].element,s=e[l].bbox,o[t]=r.origin[t]+r.size[i],o[n]=s.origin[n],S(o,s,a),s.origin[t]=o[t],r=s}function k(e,t,n,i,r){var o,a,s;for(n=n||"start",s=0;e.length>s;s++)o=e[s].clippedBBox(),o&&(a=o.origin.clone(),a[i]=x(o.size[r],t,n,i,r),S(a,o,e[s]))}function x(e,t,n,i,r){var o;return o=n==mt?t.origin[i]:n==vt?t.origin[i]+t.size[r]-e:t.origin[i]+(t.size[r]-e)/2}function C(e,t,n){var i=n.transform()||G.transform(),r=i.matrix();r.e+=e,r.f+=t,n.transform(i)}function S(e,t,n){C(e.x-t.origin.x,e.y-t.origin.y,n)}var T,D,A,E,I,P,M,z,F,R,H,B,L,N,O,V,U=window.kendo,W=U.Class,j=U.deepExtend,G=U.geometry,q=G.Point,$=G.Rect,Y=G.Size,Q=G.Matrix,K=G.toMatrix,X=U.drawing,Z=X.OptionsStore,J=Math,et=J.pow,tt=U.util,nt=tt.append,it=tt.arrayLimits,rt=tt.defined,ot=tt.last,at=tt.valueOrDefault,st=U.mixins.ObserversMixin,lt=e.inArray,ct=[].push,dt=[].pop,ut=[].splice,ht=[].shift,pt=[].slice,ft=[].unshift,gt=1,mt="start",vt="end",_t="horizontal",wt=W.extend({nodeType:"Element",init:function(e){this._initOptions(e)},_initOptions:function(e){var t,n;e=e||{},t=e.transform,n=e.clip,t&&(e.transform=G.transform(t)),n&&!n.id&&(n.id=d()),this.options=new Z(e),this.options.addObserver(this)},transform:function(e){return rt(e)?void this.options.set("transform",G.transform(e)):this.options.get("transform")},parentTransform:function(){for(var e,t,n=this;n.parent;)n=n.parent,e=n.transform(),e&&(t=e.matrix().multiplyCopy(t||Q.unit()));return t?G.transform(t):void 0},currentTransform:function(e){var t,n,i=this.transform(),r=K(i);return rt(e)||(e=this.parentTransform()),t=K(e),n=r&&t?t.multiplyCopy(r):r||t,n?G.transform(n):void 0},visible:function(e){return rt(e)?(this.options.set("visible",e),this):this.options.get("visible")!==!1},clip:function(e){var t=this.options;return rt(e)?(e&&!e.id&&(e.id=d()),t.set("clip",e),this):t.get("clip")},opacity:function(e){return rt(e)?(this.options.set("opacity",e),this):at(this.options.get("opacity"),1)},clippedBBox:function(e){var t,n=this._clippedBBox(e);return n?(t=this.clip(),t?$.intersect(n,t.bbox(e)):n):void 0},_clippedBBox:function(e){return this.bbox(e)}});j(wt.fn,st),T=W.extend({init:function(e){e=e||[],this.length=0,this._splice(0,e.length,e)},elements:function(e){return e?(this._splice(0,this.length,e),this._change(),this):this.slice(0)},push:function(){var e=arguments,t=ct.apply(this,e);return this._add(e),t},slice:pt,pop:function(){var e=this.length,t=dt.apply(this);return e&&this._remove([t]),t},splice:function(e,t){var n=pt.call(arguments,2),i=this._splice(e,t,n);return this._change(),i},shift:function(){var e=this.length,t=ht.apply(this);return e&&this._remove([t]),t},unshift:function(){var e=arguments,t=ft.apply(this,e);return this._add(e),t},indexOf:function(e){var t,n,i=this;for(t=0,n=i.length;n>t;t++)if(i[t]===e)return t;return-1},_splice:function(e,t,n){var i=ut.apply(this,[e,t].concat(n));return this._clearObserver(i),this._setObserver(n),i},_add:function(e){this._setObserver(e),this._change()},_remove:function(e){this._clearObserver(e),this._change()},_setObserver:function(e){for(var t=0;e.length>t;t++)e[t].addObserver(this)},_clearObserver:function(e){for(var t=0;e.length>t;t++)e[t].removeObserver(this)},_change:function(){}}),j(T.fn,st),D=wt.extend({nodeType:"Group",init:function(e){wt.fn.init.call(this,e),this.children=[]},childrenChange:function(e,t,n){this.trigger("childrenChange",{action:e,items:t,index:n})},append:function(){return nt(this.children,arguments),this._reparent(arguments,this),this.childrenChange("add",arguments),this},insertAt:function(e,t){return this.children.splice(t,0,e),e.parent=this,this.childrenChange("add",[e],t),this},remove:function(e){var t=lt(e,this.children);return t>=0&&(this.children.splice(t,1),e.parent=null,this.childrenChange("remove",[e],t)),this},removeAt:function(e){if(e>=0&&this.children.length>e){var t=this.children[e];this.children.splice(e,1),t.parent=null,this.childrenChange("remove",[t],e)}return this},clear:function(){var e=this.children;return this.children=[],this._reparent(e,null),this.childrenChange("remove",e,0),this},bbox:function(e){return t(this.children,!0,this.currentTransform(e))},rawBBox:function(){return t(this.children,!1)},_clippedBBox:function(e){return n(this.children,this.currentTransform(e))},currentTransform:function(e){return wt.fn.currentTransform.call(this,e)||null},_reparent:function(e,t){var n,i,r;for(n=0;e.length>n;n++)i=e[n],r=i.parent,r&&r!=this&&r.remove&&r.remove(i),i.parent=t}}),X.mixins.Traversable.extend(D.fn,"children"),A=wt.extend({nodeType:"Text",init:function(e,t,n){wt.fn.init.call(this,n),this.content(e),this.position(t||new G.Point),this.options.font||(this.options.font="12px sans-serif"),rt(this.options.fill)||this.fill("#000")},content:function(e){return rt(e)?(this.options.set("content",e),this):this.options.get("content")},measure:function(){var e=X.util.measureText(this.content(),{font:this.options.get("font")});return e},rect:function(){var e=this.measure(),t=this.position().clone();return new G.Rect(t,[e.width,e.height])},bbox:function(e){var t=K(this.currentTransform(e));return this.rect().bbox(t)},rawBBox:function(){return this.rect().bbox()}}),X.mixins.Paintable.extend(A.fn),a(A.fn,["position"]),E=wt.extend({nodeType:"Circle",init:function(e,t){wt.fn.init.call(this,t),this.geometry(e||new G.Circle),rt(this.options.stroke)||this.stroke("#000")},bbox:function(e){var t=K(this.currentTransform(e)),n=this._geometry.bbox(t),r=this.options.get("stroke.width");return r&&i(n,r/2),n},rawBBox:function(){return this._geometry.bbox()}}),X.mixins.Paintable.extend(E.fn),r(E.fn,["geometry"]),I=wt.extend({nodeType:"Arc",init:function(e,t){wt.fn.init.call(this,t),this.geometry(e||new G.Arc),rt(this.options.stroke)||this.stroke("#000")},bbox:function(e){var t=K(this.currentTransform(e)),n=this.geometry().bbox(t),r=this.options.get("stroke.width");return r&&i(n,r/2),n},rawBBox:function(){return this.geometry().bbox()},toPath:function(){var e,t=new z,n=this.geometry().curvePoints();if(n.length>0)for(t.moveTo(n[0].x,n[0].y),e=1;n.length>e;e+=3)t.curveTo(n[e],n[e+1],n[e+2]);return t}}),X.mixins.Paintable.extend(I.fn),r(I.fn,["geometry"]),P=T.extend({_change:function(){this.geometryChange()}}),M=W.extend({init:function(e,t,n){this.anchor(e||new q),this.controlIn(t),this.controlOut(n)},bboxTo:function(e,t){var n,i=this.anchor().transformCopy(t),r=e.anchor().transformCopy(t);return n=this.controlOut()&&e.controlIn()?this._curveBoundingBox(i,this.controlOut().transformCopy(t),e.controlIn().transformCopy(t),r):this._lineBoundingBox(i,r)},_lineBoundingBox:function(e,t){return $.fromPoints(e,t)},_curveBoundingBox:function(e,t,n,i){var r=[e,t,n,i],o=this._curveExtremesFor(r,"x"),a=this._curveExtremesFor(r,"y"),s=it([o.min,o.max,e.x,i.x]),l=it([a.min,a.max,e.y,i.y]);return $.fromPoints(new q(s.min,l.min),new q(s.max,l.max))},_curveExtremesFor:function(e,t){var n=this._curveExtremes(e[0][t],e[1][t],e[2][t],e[3][t]);return{min:this._calculateCurveAt(n.min,t,e),max:this._calculateCurveAt(n.max,t,e)}},_calculateCurveAt:function(e,t,n){var i=1-e;return et(i,3)*n[0][t]+3*et(i,2)*e*n[1][t]+3*et(e,2)*i*n[2][t]+et(e,3)*n[3][t]},_curveExtremes:function(e,t,n,i){var r,o,a=e-3*t+3*n-i,s=-2*(e-2*t+n),l=e-t,c=J.sqrt(s*s-4*a*l),d=0,u=1;return 0===a?0!==s&&(d=u=-l/s):isNaN(c)||(d=(-s+c)/(2*a),u=(-s-c)/(2*a)),r=J.max(J.min(d,u),0),(0>r||r>1)&&(r=0),o=J.min(J.max(d,u),1),(o>1||0>o)&&(o=1),{min:r,max:o}}}),a(M.fn,["anchor","controlIn","controlOut"]),j(M.fn,st),z=wt.extend({nodeType:"Path",init:function(e){wt.fn.init.call(this,e),this.segments=new P,this.segments.addObserver(this),rt(this.options.stroke)||(this.stroke("#000"),rt(this.options.stroke.lineJoin)||this.options.set("stroke.lineJoin","miter"))},moveTo:function(e,t){return this.suspend(),this.segments.elements([]),this.resume(),this.lineTo(e,t),this},lineTo:function(e,t){var n=rt(t)?new q(e,t):e,i=new M(n);return this.segments.push(i),this},curveTo:function(e,t,n){var i,r;return this.segments.length>0&&(i=ot(this.segments),r=new M(n,t),this.suspend(),i.controlOut(e),this.resume(),this.segments.push(r)),this},arc:function(e,t,n,i,r){var o,a,s,l,c;return this.segments.length>0&&(o=ot(this.segments),a=o.anchor(),s=tt.rad(e),l=new q(a.x-n*J.cos(s),a.y-i*J.sin(s)),c=new G.Arc(l,{startAngle:e,endAngle:t,radiusX:n,radiusY:i,anticlockwise:r}),this._addArcSegments(c)),this},arcTo:function(e,t,n,i,r){var o,a,s;return this.segments.length>0&&(o=ot(this.segments),a=o.anchor(),s=G.Arc.fromPoints(a,e,t,n,i,r),this._addArcSegments(s)),this},_addArcSegments:function(e){var t,n;for(this.suspend(),t=e.curvePoints(),n=1;t.length>n;n+=3)this.curveTo(t[n],t[n+1],t[n+2]);this.resume(),this.geometryChange()},close:function(){return this.options.closed=!0,this.geometryChange(),this},bbox:function(e){var t=K(this.currentTransform(e)),n=this._bbox(t),r=this.options.get("stroke.width");return r&&i(n,r/2),n},rawBBox:function(){return this._bbox()},_bbox:function(e){var t,n,i,r,o=this.segments,a=o.length;if(1===a)n=o[0].anchor().transformCopy(e),t=new $(n,Y.ZERO);else if(a>0)for(i=1;a>i;i++)r=o[i-1].bboxTo(o[i],e),t=t?$.union(t,r):r;return t}}),X.mixins.Paintable.extend(z.fn),z.fromRect=function(e,t){return new z(t).moveTo(e.topLeft()).lineTo(e.topRight()).lineTo(e.bottomRight()).lineTo(e.bottomLeft()).close()},z.fromPoints=function(e,t){var n,i,r;if(e){for(n=new z(t),i=0;e.length>i;i++)r=q.create(e[i]),r&&(0===i?n.moveTo(r):n.lineTo(r));return n}},z.fromArc=function(e,t){var n=new z(t),i=e.startAngle,r=e.pointAt(i);return n.moveTo(r.x,r.y),n.arc(i,e.endAngle,e.radiusX,e.radiusY,e.anticlockwise),n},F=wt.extend({nodeType:"MultiPath",init:function(e){wt.fn.init.call(this,e),this.paths=new P,this.paths.addObserver(this),rt(this.options.stroke)||this.stroke("#000")},moveTo:function(e,t){var n=new z;return n.moveTo(e,t),this.paths.push(n),this},lineTo:function(e,t){return this.paths.length>0&&ot(this.paths).lineTo(e,t),this},curveTo:function(e,t,n){return this.paths.length>0&&ot(this.paths).curveTo(e,t,n),this},arc:function(e,t,n,i,r){return this.paths.length>0&&ot(this.paths).arc(e,t,n,i,r),this},arcTo:function(e,t,n,i,r){return this.paths.length>0&&ot(this.paths).arcTo(e,t,n,i,r),this},close:function(){return this.paths.length>0&&ot(this.paths).close(),this},bbox:function(e){return t(this.paths,!0,this.currentTransform(e))},rawBBox:function(){return t(this.paths,!1)},_clippedBBox:function(e){return n(this.paths,this.currentTransform(e))}}),X.mixins.Paintable.extend(F.fn),R=wt.extend({nodeType:"Image",init:function(e,t,n){wt.fn.init.call(this,n),this.src(e),this.rect(t||new G.Rect)},src:function(e){return rt(e)?(this.options.set("src",e),this):this.options.get("src")},bbox:function(e){var t=K(this.currentTransform(e));return this._rect.bbox(t)},rawBBox:function(){return this._rect.bbox()}}),r(R.fn,["rect"]),H=W.extend({init:function(e,t,n){this.options=new Z({offset:e,color:t,opacity:rt(n)?n:1}),this.options.addObserver(this)}}),l(H.fn,["offset","color","opacity"]),j(H.fn,st),H.create=function(e){if(rt(e)){var t;return t=e instanceof H?e:e.length>1?new H(e[0],e[1],e[2]):new H(e.offset,e.color,e.opacity)}},B=T.extend({_change:function(){this.optionsChange({field:"stops"})}}),L=W.extend({nodeType:"gradient",init:function(e){this.stops=new B(this._createStops(e.stops)),this.stops.addObserver(this),this._userSpace=e.userSpace,this.id=d()},userSpace:function(e){return rt(e)?(this._userSpace=e,this.optionsChange(),this):this._userSpace},_createStops:function(e){var t,n=[];for(e=e||[],t=0;e.length>t;t++)n.push(H.create(e[t]));return n},addStop:function(e,t,n){this.stops.push(new H(e,t,n))},removeStop:function(e){var t=this.stops.indexOf(e);t>=0&&this.stops.splice(t,1)}}),j(L.fn,st,{optionsChange:function(e){this.trigger("optionsChange",{field:"gradient"+(e?"."+e.field:""),value:this})},geometryChange:function(){this.optionsChange()}}),N=L.extend({init:function(e){e=e||{},L.fn.init.call(this,e),this.start(e.start||new q),this.end(e.end||new q(1,0))}}),a(N.fn,["start","end"]),O=L.extend({init:function(e){e=e||{},L.fn.init.call(this,e),this.center(e.center||new q),this._radius=rt(e.radius)?e.radius:1,this._fallbackFill=e.fallbackFill},radius:function(e){return rt(e)?(this._radius=e,this.geometryChange(),this):this._radius},fallbackFill:function(e){return rt(e)?(this._fallbackFill=e,this.optionsChange(),this):this._fallbackFill}}),a(O.fn,["center"]),V=D.extend({init:function(e,t){D.fn.init.call(this,U.deepExtend({},this._defaults,t)),this._rect=e,this._fieldMap={}},_defaults:{alignContent:mt,justifyContent:mt,alignItems:mt,spacing:0,orientation:_t,lineSpacing:0,wrap:!0},rect:function(e){return e?(this._rect=e,this):this._rect},_initMap:function(){var e=this.options,t=this._fieldMap;e.orientation==_t?(t.sizeField="width",t.groupsSizeField="height",t.groupAxis="x",t.groupsAxis="y"):(t.sizeField="height",t.groupsSizeField="width",t.groupAxis="y",t.groupsAxis="x")},reflow:function(){var e,t,n,i,r,o,a,s,l,c,d,u,h,p,f,g,m,v,_,w,b,y,k,C,T,D;if(this._rect&&0!==this.children.length){for(this._initMap(),this.options.transform&&this.transform(null),e=this.options,t=this._fieldMap,n=this._rect,i=this._initGroups(),r=i.groups,o=i.groupsSize,a=t.sizeField,s=t.groupsSizeField,l=t.groupAxis,c=t.groupsAxis,d=x(o,n,e.alignContent,c,s),u=new q,h=new q,p=new G.Size,w=0;r.length>w;w++){for(v=r[w],u[l]=f=x(v.size,n,e.justifyContent,l,a),u[c]=d,p[a]=v.size,p[s]=v.lineSize,_=new $(u,p),b=0;v.bboxes.length>b;b++)m=v.elements[b],g=v.bboxes[b],h[l]=f,h[c]=x(g.size[s],_,e.alignItems,c,s),S(h,g,m),f+=g.size[a]+e.spacing;d+=v.lineSize+e.lineSpacing}!e.wrap&&v.size>n.size[a]&&(y=n.size[a]/_.size[a],k=_.topLeft().scale(y,y),C=_.size[s]*y,T=x(C,n,e.alignContent,c,s),D=G.transform(),"x"===l?D.translate(n.origin.x-k.x,T-k.y):D.translate(T-k.x,n.origin.y-k.y),D.scale(y,y),this.transform(D))}},_initGroups:function(){var e,t,n,i=this.options,r=this.children,o=i.lineSpacing,a=this._fieldMap.sizeField,s=-o,l=[],c=this._newGroup(),d=function(){l.push(c),s+=c.lineSize+o};for(n=0;r.length>n;n++)t=r[n],e=r[n].clippedBBox(),t.visible()&&e&&(i.wrap&&c.size+e.size[a]+i.spacing>this._rect.size[a]?0===c.bboxes.length?(this._addToGroup(c,e,t),d(),c=this._newGroup()):(d(),c=this._newGroup(),this._addToGroup(c,e,t)):this._addToGroup(c,e,t));return c.bboxes.length&&d(),{groups:l,groupsSize:s}},_addToGroup:function(e,t,n){e.size+=t.size[this._fieldMap.sizeField]+this.options.spacing,e.lineSize=Math.max(t.size[this._fieldMap.groupsSizeField],e.lineSize),e.bboxes.push(t),e.elements.push(n)},_newGroup:function(){return{lineSize:0,size:-this.options.spacing,bboxes:[],elements:[]}}}),j(X,{align:u,Arc:I,Circle:E,Element:wt,ElementsArray:T,fit:_,Gradient:L,GradientStop:H,Group:D,Image:R,Layout:V,LinearGradient:N,MultiPath:F,Path:z,RadialGradient:O,Segment:M,stack:p,Text:A,vAlign:h,vStack:f,vWrap:m,wrap:g})}(window.kendo.jQuery),function(e){function t(e){var t=[];return e.replace(g,function(e,n){t.push(parseFloat(n))}),t}function n(e,t,n){var i,r=t?0:1;for(i=0;e.length>i;i+=2)e.splice(i+r,0,n)}function i(e,t){return e&&t?t.scaleCopy(2).translate(-e.x,-e.y):void 0}function r(e,t,n){var i=1/3;return t=t.clone().scale(2/3),{controlOut:t.clone().translateWith(e.scaleCopy(i)),controlIn:t.translateWith(n.scaleCopy(i))}}var o=window.kendo,a=o.drawing,s=o.geometry,l=o.Class,c=s.Point,d=o.deepExtend,u=e.trim,h=o.util,p=h.last,f=/([a-z]{1})([^a-z]*)(z)?/gi,g=/[,\s]?(-?(?:\d+\.)?\d+)/g,m="m",v="z",_=l.extend({parse:function(e,n){var i,r=new a.MultiPath(n),o=new c;return e.replace(f,function(e,n,a,s){var l=n.toLowerCase(),c=l===n,d=t(u(a));if(l===m&&(c?(o.x+=d[0],o.y+=d[1]):(o.x=d[0],o.y=d[1]),r.moveTo(o.x,o.y),d.length>2&&(l="l",d.splice(0,2))),w[l])w[l](r,{parameters:d,position:o,isRelative:c,previousCommand:i}),s&&s.toLowerCase()===v&&r.close();else if(l!==m)throw Error("Error while parsing SVG path. Unsupported command: "+l);i=l}),r}}),w={l:function(e,t){var n,i,r=t.parameters,o=t.position;for(n=0;r.length>n;n+=2)i=new c(r[n],r[n+1]),t.isRelative&&i.translateWith(o),e.lineTo(i.x,i.y),o.x=i.x,o.y=i.y},c:function(e,t){var n,i,r,o,a=t.parameters,s=t.position;for(o=0;a.length>o;o+=6)n=new c(a[o],a[o+1]),i=new c(a[o+2],a[o+3]),r=new c(a[o+4],a[o+5]),t.isRelative&&(i.translateWith(s),n.translateWith(s),r.translateWith(s)),e.curveTo(n,i,r),s.x=r.x,s.y=r.y},v:function(e,t){var i=t.isRelative?0:t.position.x;n(t.parameters,!0,i),this.l(e,t)},h:function(e,t){var i=t.isRelative?0:t.position.y;n(t.parameters,!1,i),this.l(e,t)},a:function(e,t){var n,i,r,o,a,s,l=t.parameters,d=t.position;for(n=0;l.length>n;n+=7)i=l[n],r=l[n+1],o=l[n+3],a=l[n+4],s=new c(l[n+5],l[n+6]),t.isRelative&&s.translateWith(d),e.arcTo(s,i,r,o,a),d.x=s.x,d.y=s.y},s:function(e,t){var n,r,o,a,s,l=t.parameters,d=t.position,u=t.previousCommand;for(("s"==u||"c"==u)&&(a=p(p(e.paths).segments).controlIn()),s=0;l.length>s;s+=4)o=new c(l[s],l[s+1]),r=new c(l[s+2],l[s+3]),t.isRelative&&(o.translateWith(d),r.translateWith(d)),n=a?i(a,d):d.clone(),a=o,e.curveTo(n,o,r),d.x=r.x,d.y=r.y},q:function(e,t){var n,i,o,a,s=t.parameters,l=t.position;for(a=0;s.length>a;a+=4)o=new c(s[a],s[a+1]),i=new c(s[a+2],s[a+3]),t.isRelative&&(o.translateWith(l),i.translateWith(l)),n=r(l,o,i),e.curveTo(n.controlOut,n.controlIn,i),l.x=i.x,l.y=i.y},t:function(e,t){var n,o,a,s,l,d=t.parameters,u=t.position,h=t.previousCommand;for(("q"==h||"t"==h)&&(s=p(p(e.paths).segments),o=s.controlIn().clone().translateWith(u.scaleCopy(-1/3)).scale(1.5)),l=0;d.length>l;l+=2)a=new c(d[l],d[l+1]),t.isRelative&&a.translateWith(u),o=o?i(o,u):u.clone(),n=r(u,o,a),e.curveTo(n.controlOut,n.controlIn,a),u.x=a.x,u.y=a.y}};_.current=new _,a.Path.parse=function(e,t){return _.current.parse(e,t)},d(a,{PathParser:_})}(window.kendo.jQuery),function(e){function t(e){var t,n,i,r;try{t=e.getScreenCTM?e.getScreenCTM():null}catch(o){}t&&(n=-t.e%1,i=-t.f%1,r=e.style,(0!==n||0!==i)&&(r.left=n+"px",r.top=i+"px"))}function n(){var e=document.getElementsByTagName("base")[0],t="",n=document.location.href,i=n.indexOf("#");return e&&!d.support.browser.msie&&(-1!==i&&(n=n.substring(0,i)),t=n),t}function i(e){return"url("+n()+"#"+e+")"}function r(e){var t,n,i,r=new F({encodeText:!0}),o=e.clippedBBox();return o&&(t=o.getOrigin(),n=new p.Group,n.transform(h.transform().translate(-t.x,-t.y)),n.children.push(e),e=n),r.load([e]),i=""+r.render()+"",r.destroy(),i}function o(t,n){var i=r(t);return n&&n.raw||(i="data:image/svg+xml;base64,"+g.encodeBase64(i)),e.Deferred().resolve(i).promise()}function a(e,t){return"clip"==e||"fill"==e&&(!t||t.nodeType==C)}function s(e){if(!e||!e.indexOf||e.indexOf("&")<0)return e;var t=s._element;return t.innerHTML=e,t.textContent||t.innerText}var l,c=document,d=window.kendo,u=d.deepExtend,h=d.geometry,p=d.drawing,f=p.BaseNode,g=d.util,m=g.defined,v=g.isTransparent,_=g.renderAttr,w=g.renderAllAttr,b=g.renderTemplate,y=e.inArray,k="butt",x=p.DASH_ARRAYS,C="gradient",S="none",T=".kendo",D="solid",A=" ",E="http://www.w3.org/2000/svg",I="transform",P="undefined",M=p.Surface.extend({init:function(e,n){p.Surface.fn.init.call(this,e,n),this._root=new F(this.options),Q(this.element[0],this._template(this)),this._rootElement=this.element[0].firstElementChild,t(this._rootElement),this._root.attachTo(this._rootElement),this.element.on("click"+T,this._click),this.element.on("mouseover"+T,this._mouseenter),this.element.on("mouseout"+T,this._mouseleave),this.resize()},type:"svg",destroy:function(){this._root&&(this._root.destroy(),this._root=null,this._rootElement=null,this.element.off(T)),p.Surface.fn.destroy.call(this)},translate:function(e){var t=d.format("{0} {1} {2} {3}",Math.round(e.x),Math.round(e.y),this._size.width,this._size.height);this._offset=e,this._rootElement.setAttribute("viewBox",t)},draw:function(e){p.Surface.fn.draw.call(this,e),this._root.load([e])},clear:function(){p.Surface.fn.clear.call(this),this._root.clear()},svg:function(){return""+this._template(this)},exportVisual:function(){var e,t=this._visual,n=this._offset;return n&&(e=new p.Group,e.children.push(t),e.transform(h.transform().translate(-n.x,-n.y)),t=e),t},_resize:function(){this._offset&&this.translate(this._offset)},_template:b("#= d._root.render() #")}),z=f.extend({init:function(e){f.fn.init.call(this,e),this.definitions={}},destroy:function(){this.element&&(this.element._kendoNode=null,this.element=null),this.clearDefinitions(),f.fn.destroy.call(this)},load:function(e,t){var n,i,r,o,a=this,s=a.element;for(o=0;e.length>o;o++)i=e[o],r=i.children,n=new Y[i.nodeType](i),m(t)?a.insertAt(n,t):a.append(n),n.createDefinitions(),r&&r.length>0&&n.load(r),s&&n.attachTo(s,t)},root:function(){for(var e=this;e.parent;)e=e.parent;return e},attachTo:function(e,t){var n,i=c.createElement("div");Q(i,""+this.render()+""),n=i.firstChild.firstChild,n&&(m(t)?e.insertBefore(n,e.childNodes[t]||null):e.appendChild(n),this.setElement(n))},setElement:function(e){var t,n,i=this.childNodes;for(this.element&&(this.element._kendoNode=null),this.element=e,this.element._kendoNode=this,n=0;i.length>n;n++)t=e.childNodes[n],i[n].setElement(t)},clear:function(){var e,t;for(this.clearDefinitions(),this.element&&(this.element.innerHTML=""),e=this.childNodes,t=0;e.length>t;t++)e[t].destroy();this.childNodes=[]},removeSelf:function(){if(this.element){var e=this.element.parentNode;e&&e.removeChild(this.element),this.element=null}f.fn.removeSelf.call(this)},template:b("#= d.renderChildren() #"),render:function(){return this.template(this)},renderChildren:function(){var e,t=this.childNodes,n="";for(e=0;t.length>e;e++)n+=t[e].render();return n},optionsChange:function(e){var t=e.field,n=e.value;"visible"===t?this.css("display",n?"":S):l[t]&&a(t,n)?this.updateDefinition(t,n):"opacity"===t&&this.attr("opacity",n),f.fn.optionsChange.call(this,e)},attr:function(e,t){this.element&&this.element.setAttribute(e,t)},allAttr:function(e){for(var t=0;e.length>t;t++)this.attr(e[t][0],e[t][1])},css:function(e,t){this.element&&(this.element.style[e]=t)},allCss:function(e){for(var t=0;e.length>t;t++)this.css(e[t][0],e[t][1])},removeAttr:function(e){this.element&&this.element.removeAttribute(e)},mapTransform:function(e){var t=[];return e&&t.push([I,"matrix("+e.matrix().toString(6)+")"]),t -},renderTransform:function(){return w(this.mapTransform(this.srcElement.transform()))},transformChange:function(e){e?this.allAttr(this.mapTransform(e)):this.removeAttr(I)},mapStyle:function(){var e=this.srcElement.options,t=[["cursor",e.cursor]];return e.visible===!1&&t.push(["display",S]),t},renderStyle:function(){return _("style",g.renderStyle(this.mapStyle()))},renderOpacity:function(){return _("opacity",this.srcElement.options.opacity)},createDefinitions:function(){var e,t,n,i,r=this.srcElement,o=this.definitions;if(r){n=r.options;for(t in l)e=n.get(t),e&&a(t,e)&&(o[t]=e,i=!0);i&&this.definitionChange({action:"add",definitions:o})}},definitionChange:function(e){this.parent&&this.parent.definitionChange(e)},updateDefinition:function(e,t){var n=this.definitions,r=n[e],o=l[e],a={};r&&(a[e]=r,this.definitionChange({action:"remove",definitions:a}),delete n[e]),t?(a[e]=t,this.definitionChange({action:"add",definitions:a}),n[e]=t,this.attr(o,i(t.id))):r&&this.removeAttr(o)},clearDefinitions:function(){var e,t=this.definitions;for(e in t){this.definitionChange({action:"remove",definitions:t}),this.definitions={};break}},renderDefinitions:function(){return w(this.mapDefinitions())},mapDefinitions:function(){var e,t=this.definitions,n=[];for(e in t)n.push([l[e],i(t[e].id)]);return n}}),F=z.extend({init:function(e){z.fn.init.call(this),this.options=e,this.defs=new R},attachTo:function(e){this.element=e,this.defs.attachTo(e.firstElementChild)},clear:function(){f.fn.clear.call(this)},template:b("#=d.defs.render()##= d.renderChildren() #"),definitionChange:function(e){this.defs.definitionChange(e)}}),R=z.extend({init:function(){z.fn.init.call(this),this.definitionMap={}},attachTo:function(e){this.element=e},template:b("#= d.renderChildren()#"),definitionChange:function(e){var t=e.definitions,n=e.action;"add"==n?this.addDefinitions(t):"remove"==n&&this.removeDefinitions(t)},createDefinition:function(e,t){var n;return"clip"==e?n=H:"fill"==e&&(t instanceof p.LinearGradient?n=q:t instanceof p.RadialGradient&&(n=$)),new n(t)},addDefinitions:function(e){for(var t in e)this.addDefinition(t,e[t])},addDefinition:function(e,t){var n,i=this.definitionMap,r=t.id,o=this.element,a=i[r];a?a.count++:(n=this.createDefinition(e,t),i[r]={element:n,count:1},this.append(n),o&&n.attachTo(this.element))},removeDefinitions:function(e){for(var t in e)this.removeDefinition(e[t])},removeDefinition:function(e){var t=this.definitionMap,n=e.id,i=t[n];i&&(i.count--,0===i.count&&(this.remove(y(i.element,this.childNodes),1),delete t[n]))}}),H=z.extend({init:function(e){z.fn.init.call(this),this.srcElement=e,this.id=e.id,this.load([e])},template:b("#= d.renderChildren()#")}),B=z.extend({template:b("#= d.renderChildren() #"),optionsChange:function(e){e.field==I&&this.transformChange(e.value),z.fn.optionsChange.call(this,e)}}),L=z.extend({geometryChange:function(){this.attr("d",this.renderData()),this.invalidate()},optionsChange:function(e){switch(e.field){case"fill":e.value?this.allAttr(this.mapFill(e.value)):this.removeAttr("fill");break;case"fill.color":this.allAttr(this.mapFill({color:e.value}));break;case"stroke":e.value?this.allAttr(this.mapStroke(e.value)):this.removeAttr("stroke");break;case I:this.transformChange(e.value);break;default:var t=this.attributeMap[e.field];t&&this.attr(t,e.value)}z.fn.optionsChange.call(this,e)},attributeMap:{"fill.opacity":"fill-opacity","stroke.color":"stroke","stroke.width":"stroke-width","stroke.opacity":"stroke-opacity"},content:function(){this.element&&(this.element.textContent=this.srcElement.content())},renderData:function(){return this.printPath(this.srcElement)},printPath:function(e){var t,n,i,r,o,a=e.segments,s=a.length;if(s>0){for(t=[],o=1;s>o;o++)i=this.segmentType(a[o-1],a[o]),i!==r&&(r=i,t.push(i)),t.push("L"===i?this.printPoints(a[o].anchor()):this.printPoints(a[o-1].controlOut(),a[o].controlIn(),a[o].anchor()));return n="M"+this.printPoints(a[0].anchor())+A+t.join(A),e.options.closed&&(n+="Z"),n}},printPoints:function(){var e,t=arguments,n=t.length,i=[];for(e=0;n>e;e++)i.push(t[e].toString(3));return i.join(A)},segmentType:function(e,t){return e.controlOut()&&t.controlIn()?"C":"L"},mapStroke:function(e){var t=[];return e&&!v(e.color)?(t.push(["stroke",e.color]),t.push(["stroke-width",e.width]),t.push(["stroke-linecap",this.renderLinecap(e)]),t.push(["stroke-linejoin",e.lineJoin]),m(e.opacity)&&t.push(["stroke-opacity",e.opacity]),m(e.dashType)&&t.push(["stroke-dasharray",this.renderDashType(e)])):t.push(["stroke",S]),t},renderStroke:function(){return w(this.mapStroke(this.srcElement.options.stroke))},renderDashType:function(e){var t,n,i,r=e.width||1,o=e.dashType;if(o&&o!=D){for(t=x[o.toLowerCase()],n=[],i=0;t.length>i;i++)n.push(t[i]*r);return n.join(" ")}},renderLinecap:function(e){var t=e.dashType,n=e.lineCap;return t&&t!=D?k:n},mapFill:function(e){var t=[];return e&&e.nodeType==C||(e&&!v(e.color)?(t.push(["fill",e.color]),m(e.opacity)&&t.push(["fill-opacity",e.opacity])):t.push(["fill",S])),t},renderFill:function(){return w(this.mapFill(this.srcElement.options.fill))},template:b("")}),N=L.extend({renderData:function(){return this.printPath(this.srcElement.toPath())}}),O=L.extend({renderData:function(){var e,t,n=this.srcElement.paths;if(n.length>0){for(e=[],t=0;n.length>t;t++)e.push(this.printPath(n[t]));return e.join(" ")}}}),V=L.extend({geometryChange:function(){var e=this.center();this.attr("cx",e.x),this.attr("cy",e.y),this.attr("r",this.radius()),this.invalidate()},center:function(){return this.srcElement.geometry().center},radius:function(){return this.srcElement.geometry().radius},template:b("")}),U=L.extend({geometryChange:function(){var e=this.pos();this.attr("x",e.x),this.attr("y",e.y),this.invalidate()},optionsChange:function(e){"font"===e.field?(this.attr("style",g.renderStyle(this.mapStyle())),this.geometryChange()):"content"===e.field&&L.fn.content.call(this,this.srcElement.content()),L.fn.optionsChange.call(this,e)},mapStyle:function(){var e=L.fn.mapStyle.call(this),t=this.srcElement.options.font;return e.push(["font",d.htmlEncode(t)]),e},pos:function(){var e=this.srcElement.position(),t=this.srcElement.measure();return e.clone().setY(e.y+t.baseline)},content:function(){var e=this.srcElement.content(),t=this.root().options;return t&&t.encodeText&&(e=s(e),e=d.htmlEncode(e)),e},template:b("#= d.content() #")}),W=L.extend({geometryChange:function(){this.allAttr(this.mapPosition()),this.invalidate()},optionsChange:function(e){"src"===e.field&&this.allAttr(this.mapSource()),L.fn.optionsChange.call(this,e)},mapPosition:function(){var e=this.srcElement.rect(),t=e.topLeft();return[["x",t.x],["y",t.y],["width",e.width()+"px"],["height",e.height()+"px"]]},renderPosition:function(){return w(this.mapPosition())},mapSource:function(){return[["xlink:href",this.srcElement.src()]]},renderSource:function(){return w(this.mapSource())},template:b("")}),j=z.extend({template:b(""),renderOffset:function(){return _("offset",this.srcElement.offset())},mapStyle:function(){var e=this.srcElement;return[["stop-color",e.color()],["stop-opacity",e.opacity()]]},optionsChange:function(e){"offset"==e.field?this.attr(e.field,e.value):("color"==e.field||"opacity"==e.field)&&this.css("stop-"+e.field,e.value)}}),G=z.extend({init:function(e){z.fn.init.call(this,e),this.id=e.id,this.loadStops()},loadStops:function(){var e,t,n=this.srcElement,i=n.stops,r=this.element;for(t=0;i.length>t;t++)e=new j(i[t]),this.append(e),r&&e.attachTo(r)},optionsChange:function(e){"gradient.stops"==e.field?(f.fn.clear.call(this),this.loadStops()):e.field==C&&this.allAttr(this.mapCoordinates())},renderCoordinates:function(){return w(this.mapCoordinates())},mapSpace:function(){return["gradientUnits",this.srcElement.userSpace()?"userSpaceOnUse":"objectBoundingBox"]}}),q=G.extend({template:b("#= d.renderChildren()#"),mapCoordinates:function(){var e=this.srcElement,t=e.start(),n=e.end(),i=[["x1",t.x],["y1",t.y],["x2",n.x],["y2",n.y],this.mapSpace()];return i}}),$=G.extend({template:b("#= d.renderChildren()#"),mapCoordinates:function(){var e=this.srcElement,t=e.center(),n=e.radius(),i=[["cx",t.x],["cy",t.y],["r",n],this.mapSpace()];return i}}),Y={Group:B,Text:U,Path:L,MultiPath:O,Circle:V,Arc:N,Image:W},Q=function(e,t){e.innerHTML=t};!function(){var e="",t=c.createElement("div"),n=typeof DOMParser!=P;t.innerHTML=e,n&&t.firstChild.namespaceURI!=E&&(Q=function(e,t){var n=new DOMParser,i=n.parseFromString(t,"text/xml"),r=c.adoptNode(i.documentElement);e.innerHTML="",e.appendChild(r)})}(),s._element=document.createElement("span"),l={clip:"clip-path",fill:"fill"},d.support.svg=function(){return c.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}(),d.support.svg&&p.SurfaceFactory.current.register("svg",M,10),u(p,{exportSVG:o,svg:{ArcNode:N,CircleNode:V,ClipNode:H,DefinitionNode:R,GradientStopNode:j,GroupNode:B,ImageNode:W,LinearGradientNode:q,MultiPathNode:O,Node:z,PathNode:L,RadialGradientNode:$,RootNode:F,Surface:M,TextNode:U,_exportGroup:r}})}(window.kendo.jQuery),function(e){function t(t,n){var i,r,o,a,s,l,c={width:"800px",height:"600px",cors:"Anonymous"},d=t.clippedBBox();return d&&(i=d.getOrigin(),r=new b.Group,r.transform(w.transform().translate(-i.x,-i.y)),r.children.push(t),t=r,o=d.getSize(),c.width=o.width+"px",c.height=o.height+"px"),n=p(c,n),a=e("
    ").css({display:"none",width:n.width,height:n.height}).appendTo(document.body),s=new T(a,n),s.draw(t),l=s.image(),l.always(function(){s.destroy(),a.remove()}),l}function n(e,t){var n,i,r;for(r=0;t.length>r;r++)i=t[r],n=h.parseColor(i.color()),n.a*=i.opacity(),e.addColorStop(i.offset(),n.toCssRgba())}var i,r,o,a,s,l,c,d,u=document,h=window.kendo,p=h.deepExtend,f=h.util,g=f.defined,m=f.isTransparent,v=f.renderTemplate,_=f.valueOrDefault,w=h.geometry,b=h.drawing,y=b.BaseNode,k="butt",x=b.DASH_ARRAYS,C=1e3/60,S="solid",T=b.Surface.extend({init:function(t,n){b.Surface.fn.init.call(this,t,n),this.element[0].innerHTML=this._template(this);var r=this.element[0].firstElementChild;r.width=e(t).width(),r.height=e(t).height(),this._rootElement=r,this._root=new i(r)},destroy:function(){b.Surface.fn.destroy.call(this),this._root&&(this._root.destroy(),this._root=null)},type:"canvas",draw:function(e){b.Surface.fn.draw.call(this,e),this._root.load([e],void 0,this.options.cors)},clear:function(){b.Surface.fn.clear.call(this),this._root.clear()},image:function(){var t,n=this._root,i=this._rootElement,r=[];return n.traverse(function(e){e.loading&&r.push(e.loading)}),t=e.Deferred(),e.when.apply(e,r).done(function(){n._invalidate();try{var e=i.toDataURL();t.resolve(e)}catch(r){t.reject(r)}}).fail(function(e){t.reject(e)}),t.promise()},_resize:function(){this._rootElement.width=this._size.width,this._rootElement.height=this._size.height,this._root.invalidate()},_template:v("")}),D=y.extend({init:function(e){y.fn.init.call(this,e),e&&this.initClip()},initClip:function(){var e=this.srcElement.clip();e&&(this.clip=e,e.addObserver(this))},clear:function(){this.srcElement&&this.srcElement.removeObserver(this),this.clearClip(),y.fn.clear.call(this)},clearClip:function(){this.clip&&(this.clip.removeObserver(this),delete this.clip)},setClip:function(e){this.clip&&(e.beginPath(),r.fn.renderPoints(e,this.clip),e.clip())},optionsChange:function(e){"clip"==e.field&&(this.clearClip(),this.initClip()),y.fn.optionsChange.call(this,e)},setTransform:function(e){if(this.srcElement){var t=this.srcElement.transform();t&&e.transform.apply(e,t.matrix().toArray(6))}},load:function(e,t,n){var i,r,o,a,s=this;for(a=0;e.length>a;a++)r=e[a],o=r.children,i=new d[r.nodeType](r,n),o&&o.length>0&&i.load(o,t,n),g(t)?s.insertAt(i,t):s.append(i);s.invalidate()},setOpacity:function(e){if(this.srcElement){var t=this.srcElement.opacity();g(t)&&this.globalAlpha(e,t)}},globalAlpha:function(e,t){t&&e.globalAlpha&&(t*=e.globalAlpha),e.globalAlpha=t},visible:function(){var e=this.srcElement;return!e||e&&e.options.visible!==!1}}),A=D.extend({renderTo:function(e){var t,n,i;if(this.visible()){for(e.save(),this.setTransform(e),this.setClip(e),this.setOpacity(e),t=this.childNodes,n=0;t.length>n;n++)i=t[n],i.visible()&&i.renderTo(e);e.restore()}}});b.mixins.Traversable.extend(A.fn,"childNodes"),i=A.extend({init:function(t){A.fn.init.call(this),this.canvas=t,this.ctx=t.getContext("2d"),this.invalidate=h.throttle(e.proxy(this._invalidate,this),C)},destroy:function(){A.fn.destroy.call(this),this.canvas=null,this.ctx=null},_invalidate:function(){this.ctx&&(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.renderTo(this.ctx))}}),b.mixins.Traversable.extend(i.fn,"childNodes"),r=D.extend({renderTo:function(e){e.save(),this.setTransform(e),this.setClip(e),this.setOpacity(e),e.beginPath(),this.renderPoints(e,this.srcElement),this.setLineDash(e),this.setLineCap(e),this.setLineJoin(e),this.setFill(e),this.setStroke(e),e.restore()},setFill:function(e){var t=this.srcElement.options.fill,n=!1;return t&&("gradient"==t.nodeType?(this.setGradientFill(e,t),n=!0):m(t.color)||(e.fillStyle=t.color,e.save(),this.globalAlpha(e,t.opacity),e.fill(),e.restore(),n=!0)),n},setGradientFill:function(e,t){var i,r,o,a,s=this.srcElement.rawBBox();t instanceof b.LinearGradient?(r=t.start(),o=t.end(),i=e.createLinearGradient(r.x,r.y,o.x,o.y)):t instanceof b.RadialGradient&&(a=t.center(),i=e.createRadialGradient(a.x,a.y,0,a.x,a.y,t.radius())),n(i,t.stops),e.save(),t.userSpace()||e.transform(s.width(),0,0,s.height(),s.origin.x,s.origin.y),e.fillStyle=i,e.fill(),e.restore()},setStroke:function(e){var t=this.srcElement.options.stroke;return t&&!m(t.color)&&t.width>0?(e.strokeStyle=t.color,e.lineWidth=_(t.width,1),e.save(),this.globalAlpha(e,t.opacity),e.stroke(),e.restore(),!0):void 0},dashType:function(){var e=this.srcElement.options.stroke;return e&&e.dashType?e.dashType.toLowerCase():void 0},setLineDash:function(e){var t,n=this.dashType();n&&n!=S&&(t=x[n],e.setLineDash?e.setLineDash(t):(e.mozDash=t,e.webkitLineDash=t))},setLineCap:function(e){var t=this.dashType(),n=this.srcElement.options.stroke;t&&t!==S?e.lineCap=k:n&&n.lineCap&&(e.lineCap=n.lineCap)},setLineJoin:function(e){var t=this.srcElement.options.stroke;t&&t.lineJoin&&(e.lineJoin=t.lineJoin)},renderPoints:function(e,t){var n,i,r,o,a,s,l=t.segments;if(0!==l.length){for(n=l[0],i=n.anchor(),e.moveTo(i.x,i.y),r=1;l.length>r;r++)n=l[r],i=n.anchor(),o=l[r-1],a=o.controlOut(),s=n.controlIn(),a&&s?e.bezierCurveTo(a.x,a.y,s.x,s.y,i.x,i.y):e.lineTo(i.x,i.y);t.options.closed&&e.closePath()}}}),o=r.extend({renderPoints:function(e){var t,n=this.srcElement.paths;for(t=0;n.length>t;t++)r.fn.renderPoints(e,n[t])}}),a=r.extend({renderPoints:function(e){var t=this.srcElement.geometry(),n=t.center,i=t.radius;e.arc(n.x,n.y,i,0,2*Math.PI)}}),s=r.extend({renderPoints:function(e){var t=this.srcElement.toPath();r.fn.renderPoints.call(this,e,t)}}),l=r.extend({renderTo:function(e){var t=this.srcElement,n=t.position(),i=t.measure();e.save(),this.setTransform(e),this.setClip(e),this.setOpacity(e),e.beginPath(),e.font=t.options.font,this.setFill(e)&&e.fillText(t.content(),n.x,n.y+i.baseline),this.setStroke(e)&&(this.setLineDash(e),e.strokeText(t.content(),n.x,n.y+i.baseline)),e.restore()}}),c=r.extend({init:function(t,n){var i,o;r.fn.init.call(this,t),this.onLoad=e.proxy(this.onLoad,this),this.onError=e.proxy(this.onError,this),this.loading=e.Deferred(),i=this.img=new Image,n&&!/^data:/i.test(t.src())&&(i.crossOrigin=n),o=i.src=t.src(),i.complete?this.onLoad():(i.onload=this.onLoad,i.onerror=this.onError)},renderTo:function(e){"resolved"===this.loading.state()&&(e.save(),this.setTransform(e),this.setClip(e),this.drawImage(e),e.restore())},optionsChange:function(t){"src"===t.field?(this.loading=e.Deferred(),this.img.src=this.srcElement.src()):r.fn.optionsChange.call(this,t)},onLoad:function(){this.loading.resolve(),this.invalidate()},onError:function(){this.loading.reject(Error("Unable to load image '"+this.img.src+"'. Check for connectivity and verify CORS headers."))},drawImage:function(e){var t=this.srcElement.rect(),n=t.topLeft();e.drawImage(this.img,n.x,n.y,t.width(),t.height())}}),d={Group:A,Text:l,Path:r,MultiPath:o,Circle:a,Arc:s,Image:c},h.support.canvas=function(){return!!u.createElement("canvas").getContext}(),h.support.canvas&&b.SurfaceFactory.current.register("canvas",T,20),p(h.drawing,{exportImage:t,canvas:{ArcNode:s,CircleNode:a,GroupNode:A,ImageNode:c,MultiPathNode:o,Node:D,PathNode:r,RootNode:i,Surface:T,TextNode:l}})}(window.kendo.jQuery),function(e){function t(){if(u.namespaces&&!u.namespaces.kvml){u.namespaces.add("kvml","urn:schemas-microsoft-com:vml");var e=u.styleSheets.length>30?u.styleSheets[0]:u.createStyleSheet();e.addRule(".kvml","behavior:url(#default#VML)")}}function n(e){var t=u.createElement("kvml:"+e);return t.className="kvml",t}function i(e){var t,n=e.length,i=[];for(t=0;n>t;t++)i.push(e[t].scaleCopy(M).toString(0,","));return i.join(" ")}function r(e,t){var n,r,a,s,l,c=e.segments,d=c.length;if(d>0){for(n=[],l=1;d>l;l++)a=o(c[l-1],c[l]),a!==s&&(s=a,n.push(a)),n.push("l"===a?i([c[l].anchor()]):i([c[l-1].controlOut(),c[l].controlIn(),c[l].anchor()]));return r="m "+i([c[0].anchor()])+" "+n.join(" "),e.options.closed&&(r+=" x"),t!==!0&&(r+=" e"),r}}function o(e,t){return e.controlOut()&&t.controlIn()?"c":"l"}function a(e){return 0===e.indexOf("fill")||0===e.indexOf(F)}function s(e,t,n){var i,r=n*E(t.opacity(),1);return i=e?l(e,t.color(),r):l(t.color(),"#fff",1-r)}function l(e,t,n){var i=new x(e),r=new x(t),o=c(i.r,r.r,n),a=c(i.g,r.g,n),s=c(i.b,r.b,n);return new x(o,a,s).toHex()}function c(e,t,n){return h.round(n*t+(1-n)*e)}var d,u=document,h=Math,p=h.atan2,f=h.ceil,g=h.sqrt,m=window.kendo,v=m.deepExtend,_=e.noop,w=m.drawing,b=w.BaseNode,y=m.geometry,k=y.toMatrix,x=m.Color,C=m.util,S=C.isTransparent,T=C.defined,D=C.deg,A=C.round,E=C.valueOrDefault,I="none",P=".kendo",M=100,z=M*M,F="gradient",R=4,H=w.Surface.extend({init:function(e,n){w.Surface.fn.init.call(this,e,n),t(),this.element.empty(),this._root=new L,this._root.attachTo(this.element[0]),this.element.on("click"+P,this._click),this.element.on("mouseover"+P,this._mouseenter),this.element.on("mouseout"+P,this._mouseleave)},type:"vml",destroy:function(){this._root&&(this._root.destroy(),this._root=null,this.element.off(P)),w.Surface.fn.destroy.call(this)},draw:function(e){w.Surface.fn.draw.call(this,e),this._root.load([e],void 0,null)},clear:function(){w.Surface.fn.clear.call(this),this._root.clear()}}),B=b.extend({init:function(e){b.fn.init.call(this,e),this.createElement(),this.attachReference()},observe:_,destroy:function(){this.element&&(this.element._kendoNode=null,this.element=null),b.fn.destroy.call(this)},clear:function(){var e,t;for(this.element&&(this.element.innerHTML=""),e=this.childNodes,t=0;e.length>t;t++)e[t].destroy();this.childNodes=[]},removeSelf:function(){this.element&&(this.element.parentNode.removeChild(this.element),this.element=null),b.fn.removeSelf.call(this)},createElement:function(){this.element=u.createElement("div")},attachReference:function(){this.element._kendoNode=this},load:function(e,t,n,i){var r,o,a,s,l,c;for(i=E(i,1),this.srcElement&&(i*=E(this.srcElement.options.opacity,1)),r=0;e.length>r;r++)o=e[r],a=o.children,s=o.currentTransform(n),l=i*E(o.options.opacity,1),c=new at[o.nodeType](o,s,l),a&&a.length>0&&c.load(a,t,s,i),T(t)?this.insertAt(c,t):this.append(c),c.attachTo(this.element,t)},attachTo:function(e,t){T(t)?e.insertBefore(this.element,e.children[t]||null):e.appendChild(this.element)},optionsChange:function(e){"visible"==e.field&&this.css("display",e.value!==!1?"":I)},setStyle:function(){this.allCss(this.mapStyle())},mapStyle:function(){var e=[];return this.srcElement&&this.srcElement.options.visible===!1&&e.push(["display",I]),e},mapOpacityTo:function(e,t){var n=E(this.opacity,1);n*=E(t,1),e.push(["opacity",n])},attr:function(e,t){this.element&&(this.element[e]=t)},allAttr:function(e){for(var t=0;e.length>t;t++)this.attr(e[t][0],e[t][1])},css:function(e,t){this.element&&(this.element.style[e]=t)},allCss:function(e){for(var t=0;e.length>t;t++)this.css(e[t][0],e[t][1])}}),L=B.extend({createElement:function(){B.fn.createElement.call(this),this.allCss([["width","100%"],["height","100%"],["position","relative"],["visibility","visible"]])},attachReference:_}),N=m.Class.extend({init:function(e,t){this.srcElement=e,this.observer=t,e.addObserver(this)},geometryChange:function(){this.observer.optionsChange({field:"clip",value:this.srcElement})},clear:function(){this.srcElement.removeObserver(this)}}),O=B.extend({init:function(e){B.fn.init.call(this,e),e&&this.initClip()},observe:function(){b.fn.observe.call(this)},mapStyle:function(){var e=B.fn.mapStyle.call(this);return this.srcElement&&this.srcElement.clip()&&e.push(["clip",this.clipRect()]),e},optionsChange:function(e){"clip"==e.field&&(this.clearClip(),this.initClip(),this.setClip()),B.fn.optionsChange.call(this,e)},clear:function(){this.clearClip(),B.fn.clear.call(this)},initClip:function(){this.srcElement.clip()&&(this.clip=new N(this.srcElement.clip(),this),this.clip.observer=this)},clearClip:function(){this.clip&&(this.clip.clear(),this.clip=null,this.css("clip",this.clipRect()))},setClip:function(){this.clip&&this.css("clip",this.clipRect())},clipRect:function(){var e,t,n,i=d,r=this.srcElement.clip();return r&&(e=this.clipBBox(r),t=e.topLeft(),n=e.bottomRight(),i=m.format("rect({0}px {1}px {2}px {3}px)",t.y,n.x,n.y,t.x)),i},clipBBox:function(e){var t=this.srcElement.rawBBox().topLeft(),n=e.rawBBox();return n.origin.translate(-t.x,-t.y),n}}),V=O.extend({createElement:function(){B.fn.createElement.call(this),this.setStyle()},attachTo:function(e,t){this.css("display",I),B.fn.attachTo.call(this,e,t),this.srcElement.options.visible!==!1&&this.css("display","")},_attachTo:function(e){var t=document.createDocumentFragment();t.appendChild(this.element),e.appendChild(t)},mapStyle:function(){var e=O.fn.mapStyle.call(this);return e.push(["position","absolute"]),e.push(["white-space","nowrap"]),e},optionsChange:function(e){"transform"===e.field&&this.refreshTransform(),"opacity"===e.field&&this.refreshOpacity(),O.fn.optionsChange.call(this,e)},refreshTransform:function(e){var t,n=this.srcElement.currentTransform(e),i=this.childNodes,r=i.length;for(this.setClip(),t=0;r>t;t++)i[t].refreshTransform(n)},currentOpacity:function(){var e=E(this.srcElement.options.opacity,1);return this.parent&&this.parent.currentOpacity&&(e*=this.parent.currentOpacity()),e},refreshOpacity:function(){var e,t=this.childNodes,n=t.length,i=this.currentOpacity();for(e=0;n>e;e++)t[e].refreshOpacity(i)},initClip:function(){if(O.fn.initClip.call(this),this.clip){var e=this.clip.srcElement.bbox(this.srcElement.currentTransform());e&&(this.css("width",e.width()+e.origin.x),this.css("height",e.height()+e.origin.y))}},clipBBox:function(e){return e.bbox(this.srcElement.currentTransform())},clearClip:function(){O.fn.clearClip.call(this)}}),U=B.extend({init:function(e,t){this.opacity=t,B.fn.init.call(this,e)},createElement:function(){this.element=n("stroke"),this.setOpacity()},optionsChange:function(e){0===e.field.indexOf("stroke")&&this.setStroke()},refreshOpacity:function(e){this.opacity=e,this.setStroke()},setStroke:function(){this.allAttr(this.mapStroke())},setOpacity:function(){this.setStroke()},mapStroke:function(){var e,t=this.srcElement.options.stroke,n=[];return t&&!S(t.color)&&0!==t.width?(n.push(["on","true"]),n.push(["color",t.color]),n.push(["weight",(t.width||1)+"px"]),this.mapOpacityTo(n,t.opacity),T(t.dashType)&&n.push(["dashstyle",t.dashType]),T(t.lineJoin)&&n.push(["joinstyle",t.lineJoin]),T(t.lineCap)&&(e=t.lineCap.toLowerCase(),"butt"===e&&(e="butt"===e?"flat":e),n.push(["endcap",e]))):n.push(["on","false"]),n}}),W=B.extend({init:function(e,t,n){this.opacity=n,B.fn.init.call(this,e)},createElement:function(){this.element=n("fill"),this.setFill()},optionsChange:function(e){a(e.field)&&this.setFill()},refreshOpacity:function(e){this.opacity=e,this.setOpacity()},setFill:function(){this.allAttr(this.mapFill())},setOpacity:function(){this.setFill()},attr:function(e,t){var n,i=this.element;if(i){for(n=e.split(".");n.length>1;)i=i[n.shift()];i[n[0]]=t}},mapFill:function(){var e=this.srcElement.fill(),t=[["on","false"]];return e&&(e.nodeType==F?t=this.mapGradient(e):S(e.color)||(t=this.mapFillColor(e))),t},mapFillColor:function(e){var t=[["on","true"],["color",e.color]];return this.mapOpacityTo(t,e.opacity),t},mapGradient:function(e){var t,n=this.srcElement.options,i=n.fallbackFill||e.fallbackFill&&e.fallbackFill();return t=e instanceof w.LinearGradient?this.mapLinearGradient(e):e instanceof w.RadialGradient&&e.supportVML?this.mapRadialGradient(e):i?this.mapFillColor(i):[["on","false"]]},mapLinearGradient:function(e){var t=e.start(),n=e.end(),i=C.deg(p(n.y-t.y,n.x-t.x)),r=[["on","true"],["type",F],["focus",0],["method","none"],["angle",270-i]];return this.addColors(r),r},mapRadialGradient:function(e){var t=this.srcElement.rawBBox(),n=e.center(),i=(n.x-t.origin.x)/t.width(),r=(n.y-t.origin.y)/t.height(),o=[["on","true"],["type","gradienttitle"],["focus","100%"],["focusposition",i+" "+r],["method","none"]];return this.addColors(o),o},addColors:function(e){var t,n,i=this.srcElement.options,r=E(this.opacity,1),o=[],a=i.fill.stops,l=i.baseColor,c=this.element.colors?"colors.value":"colors",d=s(l,a[0],r),u=s(l,a[a.length-1],r);for(n=0;a.length>n;n++)t=a[n],o.push(h.round(100*t.offset())+"% "+s(l,t,r));e.push([c,o.join(",")],["color",d],["color2",u])}}),j=B.extend({init:function(e,t){this.transform=t,B.fn.init.call(this,e)},createElement:function(){this.element=n("skew"),this.setTransform()},optionsChange:function(e){"transform"===e.field&&this.refresh(this.srcElement.currentTransform())},refresh:function(e){this.transform=e,this.setTransform()},transformOrigin:function(){return"-0.5,-0.5"},setTransform:function(){this.allAttr(this.mapTransform())},mapTransform:function(){var e=this.transform,t=[],n=k(e);return n?(n.round(R),t.push(["on","true"],["matrix",[n.a,n.c,n.b,n.d,0,0].join(",")],["offset",n.e+"px,"+n.f+"px"],["origin",this.transformOrigin()])):t.push(["on","false"]),t}}),G=O.extend({init:function(e,t,n){this.fill=this.createFillNode(e,t,n),this.stroke=new U(e,n),this.transform=this.createTransformNode(e,t),O.fn.init.call(this,e)},attachTo:function(e,t){this.fill.attachTo(this.element),this.stroke.attachTo(this.element),this.transform.attachTo(this.element),B.fn.attachTo.call(this,e,t)},createFillNode:function(e,t,n){return new W(e,t,n)},createTransformNode:function(e,t){return new j(e,t)},createElement:function(){this.element=n("shape"),this.setCoordsize(),this.setStyle()},optionsChange:function(e){a(e.field)?this.fill.optionsChange(e):0===e.field.indexOf("stroke")?this.stroke.optionsChange(e):"transform"===e.field?this.transform.optionsChange(e):"opacity"===e.field&&(this.fill.setOpacity(),this.stroke.setOpacity()),O.fn.optionsChange.call(this,e)},refreshTransform:function(e){this.transform.refresh(this.srcElement.currentTransform(e))},refreshOpacity:function(e){e*=E(this.srcElement.options.opacity,1),this.fill.refreshOpacity(e),this.stroke.refreshOpacity(e)},mapStyle:function(e,t){var n,i=O.fn.mapStyle.call(this);return e&&t||(e=t=M),i.push(["position","absolute"],["width",e+"px"],["height",t+"px"]),n=this.srcElement.options.cursor,n&&i.push(["cursor",n]),i},setCoordsize:function(){this.allAttr([["coordorigin","0 0"],["coordsize",z+" "+z]])}}),q=B.extend({createElement:function(){this.element=n("path"),this.setPathData()},geometryChange:function(){this.setPathData()},setPathData:function(){this.attr("v",this.renderData())},renderData:function(){return r(this.srcElement)}}),$=G.extend({init:function(e,t,n){this.pathData=this.createDataNode(e),G.fn.init.call(this,e,t,n)},attachTo:function(e,t){this.pathData.attachTo(this.element),G.fn.attachTo.call(this,e,t)},createDataNode:function(e){return new q(e)},geometryChange:function(){this.pathData.geometryChange(),G.fn.geometryChange.call(this)}}),Y=q.extend({renderData:function(){var e,t,n,i=this.srcElement.paths;if(i.length>0){for(e=[],t=0;i.length>t;t++)n=i.length-1>t,e.push(r(i[t],n));return e.join(" ")}}}),Q=$.extend({createDataNode:function(e){return new Y(e)}}),K=j.extend({transformOrigin:function(){var e=this.srcElement.geometry().bbox(),t=e.center(),n=-f(t.x)/f(e.width()),i=-f(t.y)/f(e.height());return n+","+i}}),X=G.extend({createElement:function(){this.element=n("oval"),this.setStyle()},createTransformNode:function(e,t){return new K(e,t)},geometryChange:function(){G.fn.geometryChange.call(this),this.setStyle(),this.refreshTransform()},mapStyle:function(){var e=this.srcElement.geometry(),t=e.radius,n=e.center,i=f(2*t),r=G.fn.mapStyle.call(this,i,i);return r.push(["left",f(n.x-t)+"px"],["top",f(n.y-t)+"px"]),r}}),Z=q.extend({renderData:function(){return r(this.srcElement.toPath())}}),J=$.extend({createDataNode:function(e){return new Z(e)}}),et=q.extend({createElement:function(){q.fn.createElement.call(this),this.attr("textpathok",!0)},renderData:function(){var e=this.srcElement.rect(),t=e.center();return"m "+i([new y.Point(e.topLeft().x,t.y)])+" l "+i([new y.Point(e.bottomRight().x,t.y)])}}),tt=B.extend({createElement:function(){this.element=n("textpath"),this.attr("on",!0),this.attr("fitpath",!1),this.setStyle(),this.setString()},optionsChange:function(e){"content"===e.field?this.setString():this.setStyle(),B.fn.optionsChange.call(this,e)},mapStyle:function(){return[["font",this.srcElement.options.font]]},setString:function(){this.attr("string",this.srcElement.content())}}),nt=$.extend({init:function(e,t,n){this.path=new tt(e),$.fn.init.call(this,e,t,n)},createDataNode:function(e){return new et(e)},attachTo:function(e,t){this.path.attachTo(this.element),$.fn.attachTo.call(this,e,t)},optionsChange:function(e){("font"===e.field||"content"===e.field)&&(this.path.optionsChange(e),this.pathData.geometryChange(e)),$.fn.optionsChange.call(this,e)}}),it=q.extend({renderData:function(){var e=this.srcElement.rect(),t=(new w.Path).moveTo(e.topLeft()).lineTo(e.topRight()).lineTo(e.bottomRight()).lineTo(e.bottomLeft()).close();return r(t)}}),rt=j.extend({init:function(e,t,n){this.opacity=n,j.fn.init.call(this,e,t)},createElement:function(){this.element=n("fill"),this.attr("type","frame"),this.attr("rotate",!0),this.setOpacity(),this.setSrc(),this.setTransform()},optionsChange:function(e){"src"===e.field&&this.setSrc(),j.fn.optionsChange.call(this,e)},geometryChange:function(){this.refresh()},refreshOpacity:function(e){this.opacity=e,this.setOpacity()},setOpacity:function(){var e=[];this.mapOpacityTo(e,this.srcElement.options.opacity),this.allAttr(e)},setSrc:function(){this.attr("src",this.srcElement.src())},mapTransform:function(){var e,t,n,i,r,o,a,s,l=this.srcElement,c=l.rawBBox(),d=c.center(),u=M/2,h=M,f=c.width()/h,m=c.height()/h,v=0,_=this.transform; -return _?(n=k(_),i=g(n.a*n.a+n.b*n.b),r=g(n.c*n.c+n.d*n.d),f*=i,m*=r,o=D(p(n.b,n.d)),a=D(p(-n.c,n.a)),v=(o+a)/2,0!==v?(s=l.bbox().center(),e=(s.x-u)/h,t=(s.y-u)/h):(e=(d.x*i+n.e-u)/h,t=(d.y*r+n.f-u)/h)):(e=(d.x-u)/h,t=(d.y-u)/h),f=A(f,R),m=A(m,R),e=A(e,R),t=A(t,R),v=A(v,R),[["size",f+","+m],["position",e+","+t],["angle",v]]}}),ot=$.extend({createFillNode:function(e,t,n){return new rt(e,t,n)},createDataNode:function(e){return new it(e)},optionsChange:function(e){("src"===e.field||"transform"===e.field)&&this.fill.optionsChange(e),$.fn.optionsChange.call(this,e)},geometryChange:function(){this.fill.geometryChange(),$.fn.geometryChange.call(this)},refreshTransform:function(e){$.fn.refreshTransform.call(this,e),this.fill.refresh(this.srcElement.currentTransform(e))}}),at={Group:V,Text:nt,Path:$,MultiPath:Q,Circle:X,Arc:J,Image:ot};m.support.vml=function(){var e=m.support.browser;return e.msie&&9>e.version}(),d="inherit",m.support.browser.msie&&8>m.support.browser.version&&(d="rect(auto auto auto auto)"),m.support.vml&&w.SurfaceFactory.current.register("vml",H,30),v(w,{vml:{ArcDataNode:Z,ArcNode:J,CircleTransformNode:K,CircleNode:X,FillNode:W,GroupNode:V,ImageNode:ot,ImageFillNode:rt,ImagePathDataNode:it,MultiPathDataNode:Y,MultiPathNode:Q,Node:B,PathDataNode:q,PathNode:$,RootNode:L,StrokeNode:U,Surface:H,TextNode:nt,TextPathNode:tt,TextPathDataNode:et,TransformNode:j}})}(window.kendo.jQuery),function(e,t,n){"use strict";function i(n,i){function o(t){var n=new at.Group,i=t.getBoundingClientRect();return M(n,[1,0,0,1,-i.left,-i.top]),ht._clipbox=!1,ht._matrix=st.Matrix.unit(),ht._stackingContext={element:t,group:n},e(t).addClass("k-pdf-export"),et(t,n),e(t).removeClass("k-pdf-export"),n}function a(t){return null!=t?("string"==typeof t&&(t=kendo.template(t.replace(/^\s+|\s+$/g,""))),"function"==typeof t?function(n){var i=t(n);return i?e(i)[0]:void 0}:function(){return e(t).clone()[0]}):void 0}function s(n,i,r,o,s,l,c){function d(){function e(){setTimeout(function(){n({pages:k,container:C})},10)}var t,i;("-"!=r||s)&&u(x),t=g(),x.parentNode.insertBefore(t,x),t.appendChild(x),_?(i=k.length,k.forEach(function(t,n){var r=_({element:t,pageNum:n+1,totalPages:k.length});r&&(t.appendChild(r),h(r,function(){0===--i&&e()}))})):e()}function u(n){var i,o,a,l,c=b(n),d=t(y(c,"padding-bottom")),h=t(y(c,"border-bottom-width")),p=S;for(S+=d+h,i=!0,o=n.firstChild;o;o=o.nextSibling)if(1==o.nodeType){if(i=!1,a=e(o),a.is(r)){f(o);continue}if(!s){u(o);continue}if(!/^(?:static|relative)$/.test(y(b(o),"position")))continue;l=m(o),1==l?f(o):l&&(a.data("kendoChart")||/^(?:img|tr|iframe|svg|object|canvas|input|textarea|select|video|h[1-6])/i.test(o.tagName))?f(o):u(o)}else 3==o.nodeType&&s&&(v(o,i),i=!1);S=p}function p(e){var t=e.parentNode,n=t.firstChild;if(e===n)return!0;if(e===t.children[0]){if(7==n.nodeType||8==n.nodeType)return!0;if(3==n.nodeType)return!/\S/.test(n.data)}return!1}function f(e){var t,n;return 1==e.nodeType&&e!==x&&p(e)?f(e.parentNode):(t=g(),n=w.createRange(),n.setStartBefore(x),n.setEndBefore(e),t.appendChild(n.extractContents()),void x.parentNode.insertBefore(t,x))}function g(){var t=w.createElement("KENDO-PDF-PAGE");return e(t).css({display:"block",boxSizing:"content-box",width:o||"auto",padding:l.top+"px "+l.right+"px "+l.bottom+"px "+l.left+"px",position:"relative",height:s||"auto",overflow:s||o?"hidden":"visible",clear:"both"}),c&&c.pageClassName&&(t.className=c.pageClassName),k.push(t),t}function m(e){var t,n,i=e.getBoundingClientRect();return 0===i.width||0===i.height?0:(t=x.getBoundingClientRect().top,n=s-S,i.height>n?3:i.top-t>n?1:i.bottom-t>n?2:0)}function v(e,t){var n,i,r,o,a;/\S/.test(e.data)&&(n=e.data.length,i=w.createRange(),i.selectNodeContents(e),r=m(i),r&&(o=e,1==r?f(t?e.parentNode:e):(!function s(t,n,r){return i.setEnd(e,n),t==n||n==r?n:m(i)?s(t,t+n>>1,n):s(n,n+r>>1,r)}(0,n>>1,n),!/\S/.test(""+i)&&t?f(e.parentNode):(o=e.splitText(i.endOffset),a=g(),i.setStartBefore(x),a.appendChild(i.extractContents()),x.parentNode.insertBefore(a,x))),v(o)))}var _=a(c.template),w=i.ownerDocument,k=[],x=e(i).clone(!0,!0)[0],C=w.createElement("KENDO-PDF-DOCUMENT"),S=0;e(C).css({display:"block",position:"absolute",boxSizing:"content-box",left:"-10000px",top:"-10000px"}),o&&(e(C).css({width:o,paddingLeft:l.left,paddingRight:l.right}),e(x).css({overflow:"hidden"})),C.appendChild(x),i.parentNode.insertBefore(C,i),c.beforePageBreak?setTimeout(function(){c.beforePageBreak(C,d)},15):setTimeout(d,15)}i||(i={});var l=e.Deferred();if(n=e(n)[0],!n)return l.reject("No element to export");if("function"!=typeof window.getComputedStyle)throw Error("window.getComputedStyle is missing. You are using an unsupported browser, or running in IE8 compatibility mode. Drawing HTML is supported in Chrome, Firefox, Safari and IE9+.");return kendo.pdf&&kendo.pdf.defineFont(r(n.ownerDocument)),h(n,function(){var e,t=i&&i.forcePageBreak,r=i&&i.paperSize&&"auto"!=i.paperSize,a=r&&kendo.pdf.getPaperOptions(function(e,t){return e in i?i[e]:t}),c=r&&a.paperSize[0],d=r&&a.paperSize[1],u=i.margin&&a.margin;t||d?(u||(u={left:0,top:0,right:0,bottom:0}),e=new at.Group({pdf:{multiPage:!0,paperSize:r?a.paperSize:"auto"}}),s(function(t){if(i.progress){var n=!1,r=0;!function a(){t.pages.length>r?(e.append(o(t.pages[r])),i.progress({pageNum:++r,totalPages:t.pages.length,cancel:function(){n=!0}}),n?t.container.parentNode.removeChild(t.container):setTimeout(a)):(t.container.parentNode.removeChild(t.container),l.resolve(e))}()}else t.pages.forEach(function(t){e.append(o(t))}),t.container.parentNode.removeChild(t.container),l.resolve(e)},n,t,c?c-u.left-u.right:null,d?d-u.top-u.bottom:null,u,i)):l.resolve(o(n))}),l.promise()}function r(e){function t(e){if(e){var t=null;try{t=e.cssRules}catch(n){}t&&i(e,t)}}function n(e){var t,n=y(e.style,"src");return n?rt(n).reduce(function(e,t){var n=ot(t);return n&&e.push(n),e},[]):(t=ot(e.cssText),t?[t]:[])}function i(e,i){var o,a,s,l,c,d,u;for(o=0;i.length>o;++o)switch(a=i[o],a.type){case 3:t(a.styleSheet);break;case 5:s=a.style,l=rt(y(s,"font-family")),c=/^(400|bold)$/i.test(y(s,"font-weight")),d="italic"==y(s,"font-style"),u=n(a),u.length>0&&r(e,l,c,d,u[0])}}function r(e,t,n,i,r){/^data:/i.test(r)||/^[^\/:]+:\/\//.test(r)||/^\//.test(r)||(r=(e.href+"").replace(/[^\/]*$/,"")+r),t.forEach(function(e){e=e.replace(/^(['"]?)(.*?)\1$/,"$2"),n&&(e+="|bold"),i&&(e+="|italic"),o[e]=r})}var o,a;for(null==e&&(e=document),o={},a=0;e.styleSheets.length>a;++a)t(e.styleSheets[a]);return o}function o(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function a(e){return e="_counter_"+e,ht[e]}function s(e){var t=[],n=ht;for(e="_counter_"+e;n;)o(n,e)&&t.push(n[e]),n=Object.getPrototypeOf(n);return t.reverse()}function l(e,t){var n=ht;for(e="_counter_"+e;n&&!o(n,e);)n=Object.getPrototypeOf(n);n||(n=ht._root),n[e]=(n[e]||0)+(null==t?1:t)}function c(e,t){e="_counter_"+e,ht[e]=null==t?0:t}function d(e,n,i){var r,o,a;for(r=0;e.length>r;)o=e[r++],a=t(e[r]),isNaN(a)?n(o,i):(n(o,a),++r)}function u(e,t){var n=kendo.parseColor(e);return n&&(n=n.toRGB(),t?n=n.toCssRgba():0===n.a&&(n=null)),n}function h(e,t){function n(e){ut[e]||(ut[e]=!0,o.push(e))}function i(){--r<=0&&t()}var r,o=[];!function a(e){/^img$/i.test(e.tagName)&&n(e.src),it(y(b(e),"background-image")).forEach(function(e){"url"==e.type&&n(e.url)}),lt.call(e.children).forEach(a)}(e),r=o.length,0===r&&i(),o.forEach(function(e){var t=ut[e]=new Image;/^data:/i.test(e)||(t.crossOrigin="Anonymous"),t.src=e,t.complete?i():(t.onload=i,t.onerror=function(){ut[e]=null,i()})})}function p(e){for(var t={1:"i",10:"x",100:"c",2:"ii",20:"xx",200:"cc",3:"iii",30:"xxx",300:"ccc",4:"iv",40:"xl",400:"cd",5:"v",50:"l",500:"d",6:"vi",60:"lx",600:"dc",7:"vii",70:"lxx",700:"dcc",8:"viii",80:"lxxx",800:"dccc",9:"ix",90:"xc",900:"cm",1e3:"m"},n=[1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],i="";e>0;)n[0]>e?n.shift():(i+=t[n[0]],e-=n[0]);return i}function f(e){var t,i="";do t=e%26,i=String.fromCharCode(97+t)+i,e=n.floor(e/26);while(e>0);return i}function g(e,t,n){var i,r;ht=Object.create(ht),ht[e.tagName.toLowerCase()]={element:e,style:t},i=y(t,"text-decoration"),i&&"none"!=i&&(r=y(t,"color"),i.split(/\s+/g).forEach(function(e){ht[e]||(ht[e]=r)})),w(t)&&(ht._stackingContext={element:e,group:n})}function m(){ht=Object.getPrototypeOf(ht)}function v(e){if(null!=ht._clipbox){var t=e.bbox(ht._matrix);ht._clipbox=ht._clipbox?st.Rect.intersect(ht._clipbox,t):t}}function _(){var e=ht._clipbox;return null==e?!0:e?0===e.width()||0===e.height():void 0}function w(e){function t(t){return y(e,t)}return"none"!=t("transform")||"static"!=t("position")&&"auto"!=t("z-index")||t("opacity")<1?!0:void 0}function b(e,t){return window.getComputedStyle(e,t||null)}function y(e,t){return e.getPropertyValue(t)||ct.webkit&&e.getPropertyValue("-webkit-"+t)||ct.mozilla&&e.getPropertyValue("-moz-"+t)||ct.opera&&e.getPropertyValue("-o-"+t)||ct.msie&&e.getPropertyValue("-ms-"+t)}function k(e,t,n,i){e.setProperty(t,n,i),ct.webkit?e.setProperty("-webkit-"+t,n,i):ct.mozilla?e.setProperty("-moz-"+t,n,i):ct.opera?e.setProperty("-o-"+t,n,i):ct.msie&&(e.setProperty("-ms-"+t,n,i),t="ms"+t.replace(/(^|-)([a-z])/g,function(e,t,n){return t+n.toUpperCase()}),e[t]=n)}function x(e){if(ct.msie){var t=e.getClientRects();if(2==t.length&&0===t[1].width)return t[0]}return e.getBoundingClientRect()}function C(e,n){return n="border-"+n,{width:t(y(e,n+"-width")),style:y(e,n+"-style"),color:u(y(e,n+"-color"),!0)}}function S(e,t){var n=e.style.cssText,i=t();return e.style.cssText=n,i}function T(e,n){var i=y(e,"border-"+n+"-radius").split(/\s+/g).map(t);return 1==i.length&&i.push(i[0]),R({x:i[0],y:i[1]})}function D(e){var t=e.getBoundingClientRect();return t=A(t,"border-*-width",e),t=A(t,"padding-*",e)}function A(e,n,i){var r,o,a,s,l;return"string"==typeof n?(r=b(i),o=t(y(r,n.replace("*","top"))),a=t(y(r,n.replace("*","right"))),s=t(y(r,n.replace("*","bottom"))),l=t(y(r,n.replace("*","left")))):"number"==typeof n&&(o=a=s=l=n),{top:e.top+o,right:e.right-a,bottom:e.bottom-s,left:e.left+l,width:e.right-e.left-a-l,height:e.bottom-e.top-s-o}}function E(e){var n,i,r=y(e,"transform");return"none"==r?null:(n=/^\s*matrix\(\s*(.*?)\s*\)\s*$/.exec(r),n?(i=y(e,"transform-origin"),n=n[1].split(/\s*,\s*/g).map(t),i=i.split(/\s+/g).map(t),{matrix:n,origin:i}):void 0)}function I(e){return 180*e/n.PI%360}function P(e){var i=t(e);return/grad$/.test(e)?n.PI*i/200:/rad$/.test(e)?i:/turn$/.test(e)?n.PI*i*2:/deg$/.test(e)?n.PI*i/180:void 0}function M(e,t){return t=new st.Matrix(t[0],t[1],t[2],t[3],t[4],t[5]),e.transform(t),t}function z(e,t){e.clip(t)}function F(e,t,n,i){for(var r=new st.Arc([t,n],i).curvePoints(),o=1;r.length>o;)e.curveTo(r[o++],r[o++],r[o++])}function R(e){return(0>=e.x||0>=e.y)&&(e.x=e.y=0),e}function H(e,t,i,r,o){var a=n.max(0,t.x),s=n.max(0,t.y),l=n.max(0,i.x),c=n.max(0,i.y),d=n.max(0,r.x),u=n.max(0,r.y),h=n.max(0,o.x),p=n.max(0,o.y),f=n.min(e.width/(a+l),e.height/(c+u),e.width/(d+h),e.height/(p+s));return 1>f&&(a*=f,s*=f,l*=f,c*=f,d*=f,u*=f,h*=f,p*=f),{tl:{x:a,y:s},tr:{x:l,y:c},br:{x:d,y:u},bl:{x:h,y:p}}}function B(e,n,i){var r,o,a,s,l,c,d,u,h=b(e),p=T(h,"top-left"),f=T(h,"top-right"),g=T(h,"bottom-left"),m=T(h,"bottom-right");return("padding"==i||"content"==i)&&(r=C(h,"top"),o=C(h,"right"),a=C(h,"bottom"),s=C(h,"left"),p.x-=s.width,p.y-=r.width,f.x-=o.width,f.y-=r.width,m.x-=o.width,m.y-=a.width,g.x-=s.width,g.y-=a.width,"content"==i&&(l=t(y(h,"padding-top")),c=t(y(h,"padding-right")),d=t(y(h,"padding-bottom")),u=t(y(h,"padding-left")),p.x-=u,p.y-=l,f.x-=c,f.y-=l,m.x-=c,m.y-=d,g.x-=u,g.y-=d)),"number"==typeof i&&(p.x-=i,p.y-=i,f.x-=i,f.y-=i,m.x-=i,m.y-=i,g.x-=i,g.y-=i),L(n,p,f,m,g)}function L(e,t,n,i,r){var o=H(e,t,n,i,r),a=o.tl,s=o.tr,l=o.br,c=o.bl,d=new at.Path({fill:null,stroke:null});return d.moveTo(e.left,e.top+a.y),a.x&&F(d,e.left+a.x,e.top+a.y,{startAngle:-180,endAngle:-90,radiusX:a.x,radiusY:a.y}),d.lineTo(e.right-s.x,e.top),s.x&&F(d,e.right-s.x,e.top+s.y,{startAngle:-90,endAngle:0,radiusX:s.x,radiusY:s.y}),d.lineTo(e.right,e.bottom-l.y),l.x&&F(d,e.right-l.x,e.bottom-l.y,{startAngle:0,endAngle:90,radiusX:l.x,radiusY:l.y}),d.lineTo(e.left+c.x,e.bottom),c.x&&F(d,e.left+c.x,e.bottom-c.y,{startAngle:90,endAngle:180,radiusX:c.x,radiusY:c.y}),d.close()}function N(e,n){var i=t(e)+"";switch(n){case"decimal-leading-zero":return 2>i.length&&(i="0"+i),i;case"lower-roman":return p(e);case"upper-roman":return p(e).toUpperCase();case"lower-latin":case"lower-alpha":return f(e-1);case"upper-latin":case"upper-alpha":return f(e-1).toUpperCase();default:return i}}function O(e,t){function n(e,t,n){return n?(n=n.replace(/^\s*(["'])(.*)\1\s*$/,"$2"),s(e).map(function(e){return N(e,t)}).join(n)):N(a(e)||0,t)}var i,r=rt(t,/^\s+/),o=[];return r.forEach(function(t){var r;(i=/^\s*(["'])(.*)\1\s*$/.exec(t))?o.push(i[2].replace(/\\([0-9a-f]{4})/gi,function(e,t){return String.fromCharCode(parseInt(t,16))})):(i=/^\s*counter\((.*?)\)\s*$/.exec(t))?(r=rt(i[1]),o.push(n(r[0],r[1]))):(i=/^\s*counters\((.*?)\)\s*$/.exec(t))?(r=rt(i[1]),o.push(n(r[0],r[2],r[1]))):o.push((i=/^\s*attr\((.*?)\)\s*$/.exec(t))?e.getAttribute(i[1])||"":t)}),o.join("")}function V(e){var t,n;if(e.cssText)return e.cssText;for(t=[],n=0;e.length>n;++n)t.push(e[n]+": "+y(e,e[n]));return t.join(";\n")}function U(e,n){function i(n,i){var o,a=b(e,n);a.content&&"normal"!=a.content&&"none"!=a.content&&"0px"!=a.width&&(o=e.ownerDocument.createElement(dt),o.style.cssText=V(a),o.textContent=O(e,a.content),e.insertBefore(o,i),":before"!=n||/absolute|fixed/.test(y(o.style,"position"))||(o.style.marginLeft=t(y(o.style,"margin-left"))-o.offsetWidth+"px"),r.push(o))}if(e.tagName==dt)return void W(e,n);var r=[];i(":before",e.firstChild),i(":after",null),W(e,n),r.forEach(function(t){e.removeChild(t)})}function W(i,r){function o(e){var t,n,r,o,a,s;if(/^td$/i.test(i.tagName)&&(t=ht.table,t&&"collapse"==y(t.style,"border-collapse"))){if(n=C(t.style,"left").width,r=C(t.style,"top").width,0===n&&0===r)return e;if(o=t.element.getBoundingClientRect(),a=t.element.rows[0].cells[0],s=a.getBoundingClientRect(),s.top==o.top||s.left==o.left)return lt.call(e).map(function(e){return{left:e.left+n,top:e.top+r,right:e.right+n,bottom:e.bottom+r,height:e.height,width:e.width}})}return e}function a(e,t,i,o,a,s,l,c){function d(t,r,o){var a=n.PI/2*t/(t+i),s={x:r.x-t,y:r.y-i},l=new at.Path({fill:{color:e},stroke:null}).moveTo(0,0);M(l,o),F(l,0,r.y,{startAngle:-90,endAngle:-I(a),radiusX:r.x,radiusY:r.y}),s.x>0&&s.y>0?(l.lineTo(s.x*n.cos(a),r.y-s.y*n.sin(a)),F(l,0,r.y,{startAngle:-I(a),endAngle:-90,radiusX:s.x,radiusY:s.y,anticlockwise:!0})):s.x>0?l.lineTo(s.x,i).lineTo(0,i):l.lineTo(s.x,i).lineTo(s.x,0),h.append(l.close())}if(!(0>=i)){var u,h=new at.Group;M(h,c),r.append(h),R(s),R(l),u=new at.Path({fill:{color:e},stroke:null}),h.append(u),u.moveTo(s.x?n.max(s.x,o):0,0).lineTo(t-(l.x?n.max(l.x,a):0),0).lineTo(t-n.max(l.x,a),i).lineTo(n.max(s.x,o),i).close(),s.x&&d(o,s,[-1,0,0,1,s.x,0]),l.x&&d(a,l,[1,0,0,1,t-l.x,0])}}function s(t){var n,o,a=new at.Group;for(z(a,L(t,U,W,$,q)),r.append(a),"A"==i.tagName&&i.href&&!/^#?$/.test(e(i).attr("href"))&&(a._pdfLink={url:i.href,top:t.top,right:t.right,bottom:t.bottom,left:t.left}),K&&(n=new at.Path({fill:{color:K.toCssRgba()},stroke:null}),n.moveTo(t.left,t.top).lineTo(t.right,t.top).lineTo(t.right,t.bottom).lineTo(t.left,t.bottom).close(),a.append(n)),o=h.length;--o>=0;)l(a,t,h[o],g[o%g.length],m[o%m.length],_[o%_.length],w[o%w.length])}function l(e,n,r,o,a,s,l){function c(e,n,r,c,d){function u(){for(;m.origin.x>n.left;)m.origin.x-=r}function h(){for(;m.origin.y>n.top;)m.origin.y-=c}function p(){for(;n.right>m.origin.x;)d(e,m.clone()),m.origin.x+=r}var f,g,m,v,_=r/c,w=n;if("content-box"==s?(w=A(w,"border-*-width",i),w=A(w,"padding-*",i)):"padding-box"==s&&(w=A(w,"border-*-width",i)),/^\s*auto(\s+auto)?\s*$/.test(l)||(f=l.split(/\s+/g),r=/%$/.test(f[0])?w.width*t(f[0])/100:t(f[0]),c=1==f.length||"auto"==f[1]?r/_:/%$/.test(f[1])?w.height*t(f[1])/100:t(f[1])),g=(a+"").split(/\s+/),1==g.length&&(g[1]="50%"),g[0]=/%$/.test(g[0])?t(g[0])/100*(w.width-r):t(g[0]),g[1]=/%$/.test(g[1])?t(g[1])/100*(w.height-c):t(g[1]),m=new st.Rect([w.left+g[0],w.top+g[1]],[r,c]),"no-repeat"==o)d(e,m);else if("repeat-x"==o)u(),p();else if("repeat-y"==o)for(h();n.bottom>m.origin.y;)d(e,m.clone()),m.origin.y+=c;else if("repeat"==o)for(u(),h(),v=m.origin.clone();n.bottom>m.origin.y;)m.origin.x=v.x,p(),m.origin.y+=c}if(r&&"none"!=r)if("url"==r.type){if(/^url\(\"data:image\/svg/i.test(r.url))return;var d=ut[r.url];d&&d.width>0&&d.height>0&&c(e,n,d.width,d.height,function(e,t){e.append(new at.Image(r.url,t))})}else{if("linear"!=r.type)return;c(e,n,n.width,n.height,j(r))}}function c(){function e(e){S(i,function(){i.style.position="relative";var t=i.ownerDocument.createElement(dt);t.style.position="absolute",t.style.boxSizing="border-box","outside"==o?(t.style.width="6em",t.style.left="-6.8em",t.style.textAlign="right"):t.style.left="0px",e(t),i.insertBefore(t,i.firstChild),et(t,r),i.removeChild(t)})}function t(e){var t,n=i.parentNode.children;for(t=0;n.length>t;++t)if(n[t]===i)return e(t,n.length)}var n,o,a=y(E,"list-style-type");if("none"!=a)switch(n=y(E,"list-style-image"),o=y(E,"list-style-position"),a){case"circle":case"disc":case"square":e(function(e){e.style.fontSize="60%",e.style.lineHeight="200%",e.style.paddingRight="0.5em",e.style.fontFamily="DejaVu Serif",e.innerHTML={disc:"●",circle:"◯",square:"■"}[a]});break;case"decimal":case"decimal-leading-zero":e(function(e){t(function(t){++t,"decimal-leading-zero"==a&&2>(t+"").length&&(t="0"+t),e.innerHTML=t+"."})});break;case"lower-roman":case"upper-roman":e(function(e){t(function(t){t=p(t+1),"upper-roman"==a&&(t=t.toUpperCase()),e.innerHTML=t+"."})});break;case"lower-latin":case"lower-alpha":case"upper-latin":case"upper-alpha":e(function(e){t(function(t){t=f(t),/^upper/i.test(a)&&(t=t.toUpperCase()),e.innerHTML=t+"."})})}}function d(e,t,n){function o(e){return{x:e.y,y:e.x}}var l,c,d,u,h,p,f,g;if(0!==e.width&&0!==e.height&&(s(e),l=V.width>0&&(t&&"ltr"==Q||n&&"rtl"==Q),c=N.width>0&&(n&&"ltr"==Q||t&&"rtl"==Q),0!==P.width||0!==V.width||0!==N.width||0!==O.width)){if(P.color==N.color&&P.color==O.color&&P.color==V.color&&P.width==N.width&&P.width==O.width&&P.width==V.width&&l&&c)return e=A(e,P.width/2),d=B(i,e,P.width/2),d.options.stroke={color:P.color,width:P.width},void r.append(d);if(0===U.x&&0===W.x&&0===$.x&&0===q.x&&2>P.width&&2>V.width&&2>N.width&&2>O.width)return P.width>0&&r.append(new at.Path({stroke:{width:P.width,color:P.color}}).moveTo(e.left,e.top+P.width/2).lineTo(e.right,e.top+P.width/2)),O.width>0&&r.append(new at.Path({stroke:{width:O.width,color:O.color}}).moveTo(e.left,e.bottom-O.width/2).lineTo(e.right,e.bottom-O.width/2)),l&&r.append(new at.Path({stroke:{width:V.width,color:V.color}}).moveTo(e.left+V.width/2,e.top).lineTo(e.left+V.width/2,e.bottom)),void(c&&r.append(new at.Path({stroke:{width:N.width,color:N.color}}).moveTo(e.right-N.width/2,e.top).lineTo(e.right-N.width/2,e.bottom)));u=H(e,U,W,$,q),h=u.tl,p=u.tr,f=u.br,g=u.bl,a(P.color,e.width,P.width,V.width,N.width,h,p,[1,0,0,1,e.left,e.top]),a(O.color,e.width,O.width,N.width,V.width,f,g,[-1,0,0,-1,e.right,e.bottom]),a(V.color,e.height,V.width,O.width,P.width,o(g),o(h),[0,-1,1,0,e.left,e.bottom]),a(N.color,e.height,N.width,P.width,O.width,o(p),o(f),[0,1,-1,0,e.right,e.top])}}var h,g,m,_,w,k,x,D,E=b(i),P=C(E,"top"),N=C(E,"right"),O=C(E,"bottom"),V=C(E,"left"),U=T(E,"top-left"),W=T(E,"top-right"),q=T(E,"bottom-left"),$=T(E,"bottom-right"),Q=y(E,"direction"),K=y(E,"background-color");for(K=u(K),h=it(y(E,"background-image")),g=rt(y(E,"background-repeat")),m=rt(y(E,"background-position")),_=rt(y(E,"background-origin")),w=rt(y(E,"background-size")),ct.msie&&10>ct.version&&(m=rt(i.currentStyle.backgroundPosition)),k=A(i.getBoundingClientRect(),"border-*-width",i),function(){var e,n,i,o,a,s,l,c=y(E,"clip"),d=/^\s*rect\((.*)\)\s*$/.exec(c);d&&(e=d[1].split(/[ ,]+/g),n="auto"==e[0]?k.top:t(e[0])+k.top,i="auto"==e[1]?k.right:t(e[1])+k.left,o="auto"==e[2]?k.bottom:t(e[2])+k.top,a="auto"==e[3]?k.left:t(e[3])+k.left,s=new at.Group,l=(new at.Path).moveTo(a,n).lineTo(i,n).lineTo(i,o).lineTo(a,o).close(),z(s,l),r.append(s),r=s,v(l))}(),x=i.getClientRects(),1==x.length&&(x=[i.getBoundingClientRect()]),x=o(x),D=0;x.length>D;++D)d(x[D],0===D,D==x.length-1);return x.length>0&&"list-item"==y(E,"display")&&c(x[0]),function(){function e(){var e=B(i,k,"padding"),t=new at.Group;z(t,e),r.append(t),r=t,v(e)}Y(i)?e():/^(hidden|auto|scroll)/.test(y(E,"overflow"))?e():/^(hidden|auto|scroll)/.test(y(E,"overflow-x"))?e():/^(hidden|auto|scroll)/.test(y(E,"overflow-y"))&&e()}(),G(i,r)||X(i,r),r}function j(e){return function(i,r){{var o,a,s,l,c,d,u,h,p,f,g,m,v,_=r.width(),w=r.height();r.topLeft()}switch(e.type){case"linear":switch(o=null!=e.angle?e.angle:n.PI,e.to){case"top":o=0;break;case"left":o=-n.PI/2;break;case"bottom":o=n.PI;break;case"right":o=n.PI/2;break;case"top left":case"left top":o=-n.atan2(w,_);break;case"top right":case"right top":o=n.atan2(w,_);break;case"bottom left":case"left bottom":o=n.PI+n.atan2(w,_);break;case"bottom right":case"right bottom":o=n.PI-n.atan2(w,_)}e.reverse&&(o-=n.PI),o%=2*n.PI,0>o&&(o+=2*n.PI),a=n.abs(_*n.sin(o))+n.abs(w*n.cos(o)),s=n.atan(_*n.tan(o)/w),l=n.sin(s),c=n.cos(s),d=n.abs(l)+n.abs(c),u=d/2*l,h=d/2*c,o>n.PI/2&&3*n.PI/2>=o&&(u=-u,h=-h),p=[],f=0,g=e.stops.map(function(n,i){var r,o=n.percent;return o?o=t(o)/100:n.length?o=t(n.length)/a:0===i?o=0:i==e.stops.length-1&&(o=1),r={color:n.color.toCssRgba(),offset:o},null!=o?(f=o,p.forEach(function(e,t){var n=e.stop;n.offset=e.left+(f-e.left)*(t+1)/(p.length+1)}),p=[]):p.push({left:f,stop:r}),r}),m=[.5-u,.5+h],v=[.5+u,.5-h],i.append(at.Path.fromRect(r).stroke(null).fill(new at.LinearGradient({start:m,end:v,stops:g,userSpace:!1})));break;case"radial":window.console&&window.console.log&&window.console.log("Radial gradients are not yet supported in HTML renderer")}}}function G(t,n){var i,r,o,a;return t.getAttribute(kendo.attr("role"))&&(i=kendo.widgetInstance(e(t)),i&&(i.exportDOMVisual||i.exportVisual))?(r=i.exportDOMVisual?i.exportDOMVisual():i.exportVisual())?(o=new at.Group,o.children.push(r),a=t.getBoundingClientRect(),o.transform(st.transform().translate(a.left,a.top)),n.append(o),!0):!1:void 0}function q(e,t,n){var i=D(e),r=new st.Rect([i.left,i.top],[i.width,i.height]),o=new at.Image(t,r);z(o,B(e,i,"content")),n.append(o)}function $(e,n){var i=b(e),r=b(n),o=t(y(i,"z-index")),a=t(y(r,"z-index")),s=y(i,"position"),l=y(r,"position");return isNaN(o)&&isNaN(a)?/static|absolute/.test(s)&&/static|absolute/.test(l)?0:"static"==s?-1:"static"==l?1:0:isNaN(o)?0===a?0:a>0?-1:1:isNaN(a)?0===o?0:o>0?1:-1:t(o)-t(a)}function Y(e){return/^(?:textarea|select|input)$/i.test(e.tagName)}function Q(e){return e.selectedOptions&&e.selectedOptions.length>0?e.selectedOptions[0]:e.options[e.selectedIndex]}function K(e,t){var n,i,r=e.tagName.toLowerCase(),o=e.parentNode,a=e.ownerDocument,s=a.createElement(dt);if(s.style.cssText=V(b(e)),s.style.display="inline-block","input"==r&&(s.style.whiteSpace="pre"),("select"==r||"textarea"==r)&&(s.style.overflow="auto"),"select"==r)if(e.multiple)for(i=0;e.options.length>i;++i)n=a.createElement(dt),n.style.cssText=V(b(e.options[i])),n.style.display="block",n.textContent=e.options[i].textContent,s.appendChild(n);else n=Q(e),n&&(s.textContent=n.textContent);else s.textContent=e.value;o.insertBefore(s,e),s.scrollLeft=e.scrollLeft,s.scrollTop=e.scrollTop,X(s,t),o.removeChild(s)}function X(e,t){var n,i,r,o,a,s,l,c,d;switch(ht._stackingContext.element===e&&(ht._stackingContext.group=t),e.tagName.toLowerCase()){case"img":q(e,e.src,t);break;case"canvas":try{q(e,e.toDataURL("image/png"),t)}catch(u){}break;case"textarea":case"input":case"select":K(e,t);break;default:for(n=[],i=[],r=[],o=[],a=e.firstChild;a;a=a.nextSibling)switch(a.nodeType){case 3:/\S/.test(a.data)&&Z(e,a,t);break;case 1:s=b(a),l=y(s,"display"),c=y(s,"float"),d=y(s,"position"),"static"!=d?o.push(a):"inline"!=l?"none"!=c?i.push(a):n.push(a):r.push(a)}n.sort($).forEach(function(e){et(e,t)}),i.sort($).forEach(function(e){et(e,t)}),r.sort($).forEach(function(e){et(e,t)}),o.sort($).forEach(function(e){et(e,t)})}}function Z(e,i,r){function o(){var e,t,r,o,s,l,h,p=d,f=c.substr(d).search(/\S/);if(d+=f,0>f||d>=u)return!0;if(m.setStart(i,d),m.setEnd(i,d+1),e=m.getBoundingClientRect(),t=!1,w&&(f=c.substr(d).search(/\s/),f>=0&&(m.setEnd(i,d+f),r=m.getBoundingClientRect(),r.bottom==e.bottom&&(e=r,t=!0,d+=f))),!t){if(f=function g(t,n,r){m.setEnd(i,n);var o=x(m);return o.bottom!=e.bottom&&n>t?g(t,t+n>>1,n):o.right!=e.right?(e=o,r>n?g(n,n+r>>1,r):n):n}(d,n.min(u,d+C),u),f==d)return!0;if(d=f,f=(""+m).search(/\s+$/),0===f)return;f>0&&(m.setEnd(i,m.startOffset+f),e=m.getBoundingClientRect())}if(ct.msie&&(e=m.getClientRects()[0]),o=""+m,/^(?:pre|pre-wrap)$/i.test(k)){if(/\t/.test(o)){for(s=0,f=p;m.startOffset>f;++f)l=c.charCodeAt(f),9==l?s+=8-s%8:10==l||13==l?s=0:s++;for(;(f=o.search(" "))>=0;)h=" ".substr(0,8-(s+f)%8),o=o.substr(0,f)+h+o.substr(f+1)}}else o=o.replace(/\s+/g," ");a(o,e)}function a(e,t){var n,i,o;ct.msie&&!isNaN(p)&&(n=at.util.measureText(e,{font:f}),i=(t.top+t.bottom-n.height)/2,t={top:i,right:t.right,bottom:i+n.height,left:t.left,height:n.height,width:t.right-t.left}),o=new nt(e,new st.Rect([t.left,t.top],[t.width,t.height]),{font:f,fill:{color:g}}),r.append(o),s(t)}function s(e){function t(t,n){var i,o;t&&(i=h/12,o=new at.Path({stroke:{width:i,color:t}}),n-=i,o.moveTo(e.left,n).lineTo(e.right,n),r.append(o))}t(ht.underline,e.bottom),t(ht["line-through"],e.bottom-e.height/2.7),t(ht.overline,e.top)}var l,c,d,u,h,p,f,g,m,v,w,k,C;if(!_()&&(l=b(e),!(t(y(l,"text-indent"))<-500)&&(c=i.data,d=0,u=c.search(/\S\s*$/)+1,u&&(h=y(l,"font-size"),p=y(l,"line-height"),f=[y(l,"font-style"),y(l,"font-variant"),y(l,"font-weight"),h,y(l,"font-family")].join(" "),h=t(h),p=t(p),0!==h))))for(g=y(l,"color"),m=e.ownerDocument.createRange(),v=y(l,"text-align"),w="justify"==v,k=y(l,"white-space"),C=e.getBoundingClientRect().width/h*5,0===C&&(C=500);!o(););}function J(e,n,i){var r,o,a,s,l,c;for("auto"!=i?(r=ht._stackingContext.group,i=t(i)):(r=n,i=0),o=r.children,a=0;o.length>a&&!(null!=o[a]._dom_zIndex&&o[a]._dom_zIndex>i);++a);return s=new at.Group,r.insertAt(s,a),s._dom_zIndex=i,r!==n&&ht._clipbox&&(l=ht._matrix.invert(),c=ht._clipbox.transformCopy(l),z(s,at.Path.fromRect(c))),s}function et(e,n){var i,r,o,a,s,u,h,p=b(e),f=y(p,"counter-reset");f&&d(rt(f,/^\s+/),c,0),i=y(p,"counter-increment"),i&&d(rt(i,/^\s+/),l,1),/^(style|script|link|meta|iframe|svg|col|colgroup)$/i.test(e.tagName)||null!=ht._clipbox&&(r=t(y(p,"opacity")),o=y(p,"visibility"),a=y(p,"display"),0!==r&&"hidden"!=o&&"none"!=a&&(s=E(p),h=y(p,"z-index"),(s||1>r)&&"auto"==h&&(h=0),u=J(e,n,h),1>r&&u.opacity(r*u.opacity()),g(e,p,u),s?S(e,function(){var t,n,i,r;k(e.style,"transform","none","important"),k(e.style,"transition","none","important"),"static"==y(p,"position")&&k(e.style,"position","relative","important"),t=e.getBoundingClientRect(),n=t.left+s.origin[0],i=t.top+s.origin[1],r=[1,0,0,1,-n,-i],r=tt(r,s.matrix),r=tt(r,[1,0,0,1,n,i]),r=M(u,r),ht._matrix=ht._matrix.multiplyCopy(r),U(e,u)}):U(e,u),m()))}function tt(e,t){var n=e[0],i=e[1],r=e[2],o=e[3],a=e[4],s=e[5],l=t[0],c=t[1],d=t[2],u=t[3],h=t[4],p=t[5];return[n*l+i*d,n*c+i*u,r*l+o*d,r*c+o*u,a*l+s*d+h,a*c+s*u+p]}var nt,it,rt,ot,at=kendo.drawing,st=kendo.geometry,lt=Array.prototype.slice,ct=kendo.support.browser,dt="KENDO-PSEUDO-ELEMENT",ut={},ht={};ht._root=ht,nt=at.Text.extend({nodeType:"Text",init:function(e,t,n){at.Text.fn.init.call(this,e,t.getOrigin(),n),this._pdfRect=t},rect:function(){return this._pdfRect},rawBBox:function(){return this._pdfRect}}),at.drawDOM=i,i.getFontFaces=r,it=function(){function e(e){function f(){var t=s.exec(e);t&&(e=e.substr(t[1].length))}function g(t){f();var n=t.exec(e);return n?(e=e.substr(n[1].length),n[1]):void 0}function m(){var t,r,o=kendo.parseColor(e,!0);return o?(e=e.substr(o.match[0].length),o=o.toRGB(),(t=g(i))||(r=g(n)),{color:o,length:t,percent:r}):void 0}function v(t){var i,o,s,u,h,p,f=[],v=!1;if(g(l)){for(i=g(a),i?(i=P(i),g(d)):(o=g(r),"to"==o?o=g(r):o&&/^-/.test(t)&&(v=!0),s=g(r),g(d)),/-moz-/.test(t)&&null==i&&null==o&&(u=g(n),h=g(n),v=!0,"0%"==u?o="left":"100%"==u&&(o="right"),"0%"==h?s="top":"100%"==h&&(s="bottom"),g(d));e&&!g(c)&&(p=m());)f.push(p),g(d);return{type:"linear",angle:i,to:o&&s?o+" "+s:o?o:s?s:null,stops:f,reverse:v}}}function _(){if(g(l)){var e=g(h);return e=e.replace(/^['"]+|["']+$/g,""),g(c),{type:"url",url:e}}}var w,b=e;return o(p,b)?p[b]:((w=g(t))?w=v(w):(w=g(u))&&(w=_()),p[b]=w||{type:"none"})}var t=/^((-webkit-|-moz-|-o-|-ms-)?linear-gradient\s*)\(/,n=/^([-0-9.]+%)/,i=/^([-0-9.]+px)/,r=/^(left|right|top|bottom|to|center)\W/,a=/^([-0-9.]+(deg|grad|rad|turn))/,s=/^(\s+)/,l=/^(\()/,c=/^(\))/,d=/^(,)/,u=/^(url)\(/,h=/^(.*?)\)/,p={},f={};return function(t){return o(f,t)?f[t]:f[t]=rt(t).map(e)}}(),rt=function(){var e={};return function(t,n){function i(e){return h=e.exec(t.substr(c))}function r(e){return e.replace(/^\s+|\s+$/g,"")}var a,s,l,c,d,u,h;if(n||(n=/^\s*,\s*/),a=t+n,o(e,a))return e[a];for(s=[],l=0,c=0,d=0,u=!1;t.length>c;)!u&&i(/^[\(\[\{]/)?(d++,c++):!u&&i(/^[\)\]\}]/)?(d--,c++):!u&&i(/^[\"\']/)?(u=h[0],c++):"'"==u&&i(/^\\\'/)?c+=2:'"'==u&&i(/^\\\"/)?c+=2:"'"==u&&i(/^\'/)?(u=!1,c++):'"'==u&&i(/^\"/)?(u=!1,c++):i(n)?(!u&&!d&&c>l&&(s.push(r(t.substring(l,c))),l=c+h[0].length),c+=h[0].length):c++;return c>l&&s.push(r(t.substring(l,c))),e[a]=s}}(),ot=function(){var e={};return function(t){var n,i=e[t];return i||((n=/url\((['"]?)([^'")]*?)\1\)\s+format\((['"]?)truetype\3\)/.exec(t))?i=e[t]=n[2]:(n=/url\((['"]?)([^'")]*?\.ttf)\1\)/.exec(t))&&(i=e[t]=n[2])),i}}()}(window.kendo.jQuery,parseFloat,Math),function(e){var t=e.noop,n=window.kendo,i=n.Class,r=n.util,o=n.animationFrame,a=n.deepExtend,s=i.extend({init:function(e,t){var n=this;n.options=a({},n.options,t),n.element=e},options:{duration:500,easing:"swing"},setup:t,step:t,play:function(){var t=this,n=t.options,i=e.easing[n.easing],a=n.duration,s=n.delay||0,l=r.now()+s,c=l+a;0===a?(t.step(1),t.abort()):setTimeout(function(){var e=function(){var n,s,d,u;t._stopped||(n=r.now(),s=r.limitValue(n-l,0,a),d=s/a,u=i(d,s,0,1,a),t.step(u),c>n?o(e):t.abort())};e()},s)},abort:function(){this._stopped=!0},destroy:function(){this.abort()}}),l=function(){this._items=[]};l.prototype={register:function(e,t){this._items.push({name:e,type:t})},create:function(e,t){var n,i,r,o=this._items;if(t&&t.type)for(i=t.type.toLowerCase(),r=0;o.length>r;r++)if(o[r].name.toLowerCase()===i){n=o[r];break}return n?new n.type(e,t):void 0}},l.current=new l,s.create=function(e,t,n){return l.current.create(e,t,n)},a(n.drawing,{Animation:s,AnimationFactory:l})}(window.kendo.jQuery,Math),function(e){function t(t){var n,i=s.ui.validator.ruleResolvers||{},r={};for(n in i)e.extend(!0,r,i[n].resolve(t));return r}function n(e){return e.replace(/&/g,"&").replace(/"/g,'"').replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}function i(e){return e=(e+"").split("."),e.length>1?e[1].length:0}function r(t){return e(e.parseHTML?e.parseHTML(t):t)}function o(t,n){var i,r,o,a,l=e();for(o=0,a=t.length;a>o;o++)i=t[o],u.test(i.className)&&(r=i.getAttribute(s.attr("for")),r===n&&(l=l.add(i)));return l}var a,s=window.kendo,l=s.ui.Widget,c=".kendoValidator",d="k-invalid-msg",u=RegExp(d,"i"),h="k-invalid",p="k-valid",f=/^((([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])))$/i,g=/^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([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])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i,m=":input:not(:button,[type=submit],[type=reset],[disabled],[readonly])",v=":checkbox:not([disabled],[readonly])",_="[type=number],[type=range]",w="blur",b="name",y="form",k="novalidate",x=e.proxy,C=function(e,t){return"string"==typeof t&&(t=RegExp("^(?:"+t+")$")),t.test(e) -},S=function(e,t,n){var i=e.val();return e.filter(t).length&&""!==i?C(i,n):!0},T=function(e,t){return e.length?null!=e[0].attributes[t]:!1};s.ui.validator||(s.ui.validator={rules:{},messages:{}}),a=l.extend({init:function(n,i){var r=this,o=t(n),a="["+s.attr("validate")+"!=false]";i=i||{},i.rules=e.extend({},s.ui.validator.rules,o.rules,i.rules),i.messages=e.extend({},s.ui.validator.messages,o.messages,i.messages),l.fn.init.call(r,n,i),r._errorTemplate=s.template(r.options.errorTemplate),r.element.is(y)&&r.element.attr(k,k),r._inputSelector=m+a,r._checkboxSelector=v+a,r._errors={},r._attachEvents(),r._isValidated=!1},events:["validate","change"],options:{name:"Validator",errorTemplate:' #=message#',messages:{required:"{0} is required",pattern:"{0} is not valid",min:"{0} should be greater than or equal to {1}",max:"{0} should be smaller than or equal to {1}",step:"{0} is not valid",email:"{0} is not valid email",url:"{0} is not valid URL",date:"{0} is not valid date",dateCompare:"End date should be greater than or equal to the start date"},rules:{required:function(e){var t=e.filter("[type=checkbox]").length&&!e.is(":checked"),n=e.val();return!(T(e,"required")&&(""===n||!n||t))},pattern:function(e){return e.filter("[type=text],[type=email],[type=url],[type=tel],[type=search],[type=password]").filter("[pattern]").length&&""!==e.val()?C(e.val(),e.attr("pattern")):!0},min:function(e){if(e.filter(_+",["+s.attr("type")+"=number]").filter("[min]").length&&""!==e.val()){var t=parseFloat(e.attr("min"))||0,n=s.parseFloat(e.val());return n>=t}return!0},max:function(e){if(e.filter(_+",["+s.attr("type")+"=number]").filter("[max]").length&&""!==e.val()){var t=parseFloat(e.attr("max"))||0,n=s.parseFloat(e.val());return t>=n}return!0},step:function(e){if(e.filter(_+",["+s.attr("type")+"=number]").filter("[step]").length&&""!==e.val()){var t,n=parseFloat(e.attr("min"))||0,r=parseFloat(e.attr("step"))||1,o=parseFloat(e.val()),a=i(r);return a?(t=Math.pow(10,a),Math.floor((o-n)*t)%(r*t)/Math.pow(100,a)===0):(o-n)%r===0}return!0},email:function(e){return S(e,"[type=email],["+s.attr("type")+"=email]",f)},url:function(e){return S(e,"[type=url],["+s.attr("type")+"=url]",g)},date:function(e){return e.filter("[type^=date],["+s.attr("type")+"=date]").length&&""!==e.val()?null!==s.parseDate(e.val(),e.attr(s.attr("format"))):!0}},validateOnBlur:!0},destroy:function(){l.fn.destroy.call(this),this.element.off(c)},value:function(){return this._isValidated?0===this.errors().length:!1},_submit:function(e){return this.validate()?!0:(e.stopPropagation(),e.stopImmediatePropagation(),e.preventDefault(),!1)},_checkElement:function(e){var t=this.value();this.validateInput(e),this.value()!==t&&this.trigger("change")},_attachEvents:function(){var t=this;t.element.is(y)&&t.element.on("submit"+c,x(t._submit,t)),t.options.validateOnBlur&&(t.element.is(m)?(t.element.on(w+c,function(){t._checkElement(t.element)}),t.element.is(v)&&t.element.on("click"+c,function(){t._checkElement(t.element)})):(t.element.on(w+c,t._inputSelector,function(){t._checkElement(e(this))}),t.element.on("click"+c,t._checkboxSelector,function(){t._checkElement(e(this))})))},validate:function(){var e,t,n,i,r=!1,o=this.value();if(this._errors={},this.element.is(m))r=this.validateInput(this.element);else{for(i=!1,e=this.element.find(this._inputSelector),t=0,n=e.length;n>t;t++)this.validateInput(e.eq(t))||(i=!0);r=!i}return this.trigger("validate",{valid:r}),o!==r&&this.trigger("change"),r},validateInput:function(t){var i,o,a,l,c,u,f,g,m,v;return t=e(t),this._isValidated=!0,i=this,o=i._errorTemplate,a=i._checkValidity(t),l=a.valid,c="."+d,u=t.attr(b)||"",f=i._findMessageContainer(u).add(t.next(c).filter(function(){var t=e(this);return t.filter("["+s.attr("for")+"]").length?t.attr(s.attr("for"))===u:!0})).hide(),t.removeAttr("aria-invalid"),l?delete i._errors[u]:(g=i._extractMessage(t,a.key),i._errors[u]=g,m=r(o({message:n(g)})),v=f.attr("id"),i._decorateMessageContainer(m,u),v&&m.attr("id",v),f.replaceWith(m).length||m.insertAfter(t),m.show(),t.attr("aria-invalid",!0)),t.toggleClass(h,!l),t.toggleClass(p,l),l},hideMessages:function(){var e=this,t="."+d,n=e.element;n.is(m)?n.next(t).hide():n.find(t).hide()},_findMessageContainer:function(t){var n,i,r,a=s.ui.validator.messageLocators,l=e();for(i=0,r=this.element.length;r>i;i++)l=l.add(o(this.element[i].getElementsByTagName("*"),t));for(n in a)l=l.add(a[n].locate(this.element,t));return l},_decorateMessageContainer:function(e,t){var n,i=s.ui.validator.messageLocators;e.addClass(d).attr(s.attr("for"),t||"");for(n in i)i[n].decorate(e,t);e.attr("role","alert")},_extractMessage:function(e,t){var n=this,i=n.options.messages[t],r=e.attr(b);return i=s.isFunction(i)?i(e):i,s.format(e.attr(s.attr(t+"-msg"))||e.attr("validationMessage")||e.attr("title")||i||"",r,e.attr(t))},_checkValidity:function(e){var t,n=this.options.rules;for(t in n)if(!n[t].call(this,e))return{valid:!1,key:t};return{valid:!0}},errors:function(){var e,t=[],n=this._errors;for(e in n)t.push(n[e]);return t}}),s.ui.plugin(a)}(window.kendo.jQuery),function(e){function t(e,t){var n=e.x.location,i=e.y.location,r=t.x.location,o=t.y.location,a=n-r,s=i-o;return{center:{x:(n+r)/2,y:(i+o)/2},distance:Math.sqrt(a*a+s*s)}}function n(e){var t,n,i,r=[],a=e.originalEvent,s=e.currentTarget,l=0;if(e.api)r.push({id:2,event:e,target:e.target,currentTarget:e.target,location:e,type:"api"});else if(e.type.match(/touch/))for(n=a?a.changedTouches:[],t=n.length;t>l;l++)i=n[l],r.push({location:i,event:e,target:i.target,currentTarget:s,id:i.identifier,type:"touch"});else r.push(o.pointers||o.msPointers?{location:a,event:e,target:e.target,currentTarget:s,id:a.pointerId,type:"pointer"}:{id:1,event:e,target:e.target,currentTarget:s,location:e,type:"mouse"});return r}function i(e){for(var t=r.eventMap.up.split(" "),n=0,i=t.length;i>n;n++)e(t[n])}var r=window.kendo,o=r.support,a=window.document,s=r.Class,l=r.Observable,c=e.now,d=e.extend,u=o.mobileOS,h=u&&u.android,p=800,f=o.browser.msie?5:0,g="press",m="hold",v="select",_="start",w="move",b="end",y="cancel",k="tap",x="release",C="gesturestart",S="gesturechange",T="gestureend",D="gesturetap",A={api:0,touch:0,mouse:9,pointer:9},E=!o.touch||o.mouseAndTouchPresent,I=s.extend({init:function(e,t){var n=this;n.axis=e,n._updateLocationData(t),n.startLocation=n.location,n.velocity=n.delta=0,n.timeStamp=c()},move:function(e){var t=this,n=e["page"+t.axis],i=c(),r=i-t.timeStamp||1;(n||!h)&&(t.delta=n-t.location,t._updateLocationData(e),t.initialDelta=n-t.startLocation,t.velocity=t.delta/r,t.timeStamp=i)},_updateLocationData:function(e){var t=this,n=t.axis;t.location=e["page"+n],t.client=e["client"+n],t.screen=e["screen"+n]}}),P=s.extend({init:function(e,t,n){d(this,{x:new I("X",n.location),y:new I("Y",n.location),type:n.type,threshold:e.threshold||A[n.type],userEvents:e,target:t,currentTarget:n.currentTarget,initialTouch:n.target,id:n.id,pressEvent:n,_moved:!1,_finished:!1})},press:function(){this._holdTimeout=setTimeout(e.proxy(this,"_hold"),this.userEvents.minHold),this._trigger(g,this.pressEvent)},_hold:function(){this._trigger(m,this.pressEvent)},move:function(e){var t=this;if(!t._finished){if(t.x.move(e.location),t.y.move(e.location),!t._moved){if(t._withinIgnoreThreshold())return;if(M.current&&M.current!==t.userEvents)return t.dispose();t._start(e)}t._finished||t._trigger(w,e)}},end:function(e){var t=this;t.endTime=c(),t._finished||(t._finished=!0,t._trigger(x,e),t._moved?t._trigger(b,e):t._trigger(k,e),clearTimeout(t._holdTimeout),t.dispose())},dispose:function(){var t=this.userEvents,n=t.touches;this._finished=!0,this.pressEvent=null,clearTimeout(this._holdTimeout),n.splice(e.inArray(this,n),1)},skip:function(){this.dispose()},cancel:function(){this.dispose()},isMoved:function(){return this._moved},_start:function(e){clearTimeout(this._holdTimeout),this.startTime=c(),this._moved=!0,this._trigger(_,e)},_trigger:function(e,t){var n=this,i=t.event,r={touch:n,x:n.x,y:n.y,target:n.target,event:i};n.userEvents.notify(e,r)&&i.preventDefault()},_withinIgnoreThreshold:function(){var e=this.x.initialDelta,t=this.y.initialDelta;return Math.sqrt(e*e+t*t)<=this.threshold}}),M=l.extend({init:function(t,n){var s,c,u,h=this,A=r.guid();n=n||{},s=h.filter=n.filter,h.threshold=n.threshold||f,h.minHold=n.minHold||p,h.touches=[],h._maxTouches=n.multiTouch?2:1,h.allowSelection=n.allowSelection,h.captureUpIfMoved=n.captureUpIfMoved,h.eventNS=A,t=e(t).handler(h),l.fn.init.call(h),d(h,{element:t,surface:e(n.global&&E?a.documentElement:n.surface||t),stopPropagation:n.stopPropagation,pressed:!1}),h.surface.handler(h).on(r.applyEventMap("move",A),"_move").on(r.applyEventMap("up cancel",A),"_end"),t.on(r.applyEventMap("down",A),s,"_start"),(o.pointers||o.msPointers)&&t.css("-ms-touch-action","pinch-zoom double-tap-zoom"),n.preventDragEvent&&t.on(r.applyEventMap("dragstart",A),r.preventDefault),t.on(r.applyEventMap("mousedown",A),s,{root:t},"_select"),h.captureUpIfMoved&&o.eventCapture&&(c=h.surface[0],u=e.proxy(h.preventIfMoving,h),i(function(e){c.addEventListener(e,u,!0)})),h.bind([g,m,k,_,w,b,x,y,C,S,T,D,v],n)},preventIfMoving:function(e){this._isMoved()&&e.preventDefault()},destroy:function(){var e,t=this;t._destroyed||(t._destroyed=!0,t.captureUpIfMoved&&o.eventCapture&&(e=t.surface[0],i(function(n){e.removeEventListener(n,t.preventIfMoving)})),t.element.kendoDestroy(t.eventNS),t.surface.kendoDestroy(t.eventNS),t.element.removeData("handler"),t.surface.removeData("handler"),t._disposeAll(),t.unbind(),delete t.surface,delete t.element,delete t.currentTarget)},capture:function(){M.current=this},cancel:function(){this._disposeAll(),this.trigger(y)},notify:function(e,n){var i=this,r=i.touches;if(this._isMultiTouch()){switch(e){case w:e=S;break;case b:e=T;break;case k:e=D}d(n,{touches:r},t(r[0],r[1]))}return this.trigger(e,d(n,{type:e}))},press:function(e,t,n){this._apiCall("_start",e,t,n)},move:function(e,t){this._apiCall("_move",e,t)},end:function(e,t){this._apiCall("_end",e,t)},_isMultiTouch:function(){return this.touches.length>1},_maxTouchesReached:function(){return this.touches.length>=this._maxTouches},_disposeAll:function(){for(var e=this.touches;e.length>0;)e.pop().dispose()},_isMoved:function(){return e.grep(this.touches,function(e){return e.isMoved()}).length},_select:function(e){(!this.allowSelection||this.trigger(v,{event:e}))&&e.preventDefault()},_start:function(t){var i,r,o=this,a=0,s=o.filter,l=n(t),c=l.length,d=t.which;if(!(d&&d>1||o._maxTouchesReached()))for(M.current=null,o.currentTarget=t.currentTarget,o.stopPropagation&&t.stopPropagation();c>a&&!o._maxTouchesReached();a++)r=l[a],i=s?e(r.currentTarget):o.element,i.length&&(r=new P(o,i,r),o.touches.push(r),r.press(),o._isMultiTouch()&&o.notify("gesturestart",{}))},_move:function(e){this._eachTouch("move",e)},_end:function(e){this._eachTouch("end",e)},_eachTouch:function(e,t){var i,r,o,a,s=this,l={},c=n(t),d=s.touches;for(i=0;d.length>i;i++)r=d[i],l[r.id]=r;for(i=0;c.length>i;i++)o=c[i],a=l[o.id],a&&a[e](o)},_apiCall:function(t,n,i,r){this[t]({api:!0,pageX:n,pageY:i,clientX:n,clientY:i,target:e(r||this.element)[0],stopPropagation:e.noop,preventDefault:e.noop})}});M.defaultThreshold=function(e){f=e},M.minHold=function(e){p=e},r.getTouches=n,r.touchDelta=t,r.UserEvents=M}(window.kendo.jQuery),function(e,t){function n(t,n){try{return e.contains(t,n)||t==n}catch(i){return!1}}function i(e,t){return parseInt(e.css(t),10)||0}function r(e,t){return Math.min(Math.max(e,t.min),t.max)}function o(e,t){var n=A(e),r=n.left+i(e,"borderLeftWidth")+i(e,"paddingLeft"),o=n.top+i(e,"borderTopWidth")+i(e,"paddingTop"),a=r+e.width()-t.outerWidth(!0),s=o+e.height()-t.outerHeight(!0);return{x:{min:r,max:a},y:{min:o,max:s}}}function a(n,i,r){for(var o,a,s=0,l=i&&i.length,c=r&&r.length;n&&n.parentNode;){for(s=0;l>s;s++)if(o=i[s],o.element[0]===n)return{target:o,targetElement:n};for(s=0;c>s;s++)if(a=r[s],e.contains(a.element[0],n)&&w.matchesSelector.call(n,a.options.filter))return{target:a,targetElement:n};n=n.parentNode}return t}function s(e,t){var n,i=t.options.group,r=e[i];if(x.fn.destroy.call(t),r.length>1){for(n=0;r.length>n;n++)if(r[n]==t){r.splice(n,1);break}}else r.length=0,delete e[i]}function l(e){var t,n,i,r=b.body;return e[0]===r?(n=r.scrollTop,i=r.scrollLeft,{top:n,left:i,bottom:n+y.height(),right:i+y.width()}):(t=e.offset(),t.bottom=t.top+e.height(),t.right=t.left+e.width(),t)}function c(e){return e===b.body||e===b.documentElement||e===b}function d(t){if(!t||c(t))return e(b.body);for(var n=e(t)[0];!_.isScrollable(n)&&!c(n);)n=n.parentNode;return e(n)}function u(e,t,n){var i={x:0,y:0},r=50;return r>e-n.left?i.x=-(r-(e-n.left)):r>n.right-e&&(i.x=r-(n.right-e)),r>t-n.top?i.y=-(r-(t-n.top)):r>n.bottom-t&&(i.y=r-(n.bottom-t)),i}var h,p,f,g,m,v,_=window.kendo,w=_.support,b=window.document,y=e(window),k=_.Class,x=_.ui.Widget,C=_.Observable,S=_.UserEvents,T=e.proxy,D=e.extend,A=_.getOffset,E={},I={},P={},M=_.elementUnderCursor,z="keyup",F="change",R="dragstart",H="hold",B="drag",L="dragend",N="dragcancel",O="hintDestroyed",V="dragenter",U="dragleave",W="drop",j=C.extend({init:function(t,n){var i=this,r=t[0];i.capture=!1,r.addEventListener?(e.each(_.eventMap.down.split(" "),function(){r.addEventListener(this,T(i._press,i),!0)}),e.each(_.eventMap.up.split(" "),function(){r.addEventListener(this,T(i._release,i),!0)})):(e.each(_.eventMap.down.split(" "),function(){r.attachEvent(this,T(i._press,i))}),e.each(_.eventMap.up.split(" "),function(){r.attachEvent(this,T(i._release,i))})),C.fn.init.call(i),i.bind(["press","release"],n||{})},captureNext:function(){this.capture=!0},cancelCapture:function(){this.capture=!1},_press:function(e){var t=this;t.trigger("press"),t.capture&&e.preventDefault()},_release:function(e){var t=this;t.trigger("release"),t.capture&&(e.preventDefault(),t.cancelCapture())}}),G=C.extend({init:function(t){var n=this;C.fn.init.call(n),n.forcedEnabled=!1,e.extend(n,t),n.scale=1,n.horizontal?(n.measure="offsetWidth",n.scrollSize="scrollWidth",n.axis="x"):(n.measure="offsetHeight",n.scrollSize="scrollHeight",n.axis="y")},makeVirtual:function(){e.extend(this,{virtual:!0,forcedEnabled:!0,_virtualMin:0,_virtualMax:0})},virtualSize:function(e,t){(this._virtualMin!==e||this._virtualMax!==t)&&(this._virtualMin=e,this._virtualMax=t,this.update())},outOfBounds:function(e){return e>this.max||this.min>e},forceEnabled:function(){this.forcedEnabled=!0},getSize:function(){return this.container[0][this.measure]},getTotal:function(){return this.element[0][this.scrollSize]},rescale:function(e){this.scale=e},update:function(e){var t=this,n=t.virtual?t._virtualMax:t.getTotal(),i=n*t.scale,r=t.getSize();(0!==n||t.forcedEnabled)&&(t.max=t.virtual?-t._virtualMin:0,t.size=r,t.total=i,t.min=Math.min(t.max,r-i),t.minScale=r/n,t.centerOffset=(i-r)/2,t.enabled=t.forcedEnabled||i>r,e||t.trigger(F,t))}}),q=C.extend({init:function(e){var t=this;C.fn.init.call(t),t.x=new G(D({horizontal:!0},e)),t.y=new G(D({horizontal:!1},e)),t.container=e.container,t.forcedMinScale=e.minScale,t.maxScale=e.maxScale||100,t.bind(F,e)},rescale:function(e){this.x.rescale(e),this.y.rescale(e),this.refresh()},centerCoordinates:function(){return{x:Math.min(0,-this.x.centerOffset),y:Math.min(0,-this.y.centerOffset)}},refresh:function(){var e=this;e.x.update(),e.y.update(),e.enabled=e.x.enabled||e.y.enabled,e.minScale=e.forcedMinScale||Math.min(e.x.minScale,e.y.minScale),e.fitScale=Math.max(e.x.minScale,e.y.minScale),e.trigger(F)}}),$=C.extend({init:function(e){var t=this;D(t,e),C.fn.init.call(t)},outOfBounds:function(){return this.dimension.outOfBounds(this.movable[this.axis])},dragMove:function(e){var t=this,n=t.dimension,i=t.axis,r=t.movable,o=r[i]+e;n.enabled&&((n.min>o&&0>e||o>n.max&&e>0)&&(e*=t.resistance),r.translateAxis(i,e),t.trigger(F,t))}}),Y=k.extend({init:function(e){var t,n,i,r,o=this;D(o,{elastic:!0},e),i=o.elastic?.5:0,r=o.movable,o.x=t=new $({axis:"x",dimension:o.dimensions.x,resistance:i,movable:r}),o.y=n=new $({axis:"y",dimension:o.dimensions.y,resistance:i,movable:r}),o.userEvents.bind(["move","end","gesturestart","gesturechange"],{gesturestart:function(e){o.gesture=e,o.offset=o.dimensions.container.offset()},gesturechange:function(e){var i,a,s,l=o.gesture,c=l.center,d=e.center,u=e.distance/l.distance,h=o.dimensions.minScale,p=o.dimensions.maxScale;h>=r.scale&&1>u&&(u+=.8*(1-u)),r.scale*u>=p&&(u=p/r.scale),a=r.x+o.offset.left,s=r.y+o.offset.top,i={x:(a-c.x)*u+d.x-a,y:(s-c.y)*u+d.y-s},r.scaleWith(u),t.dragMove(i.x),n.dragMove(i.y),o.dimensions.rescale(r.scale),o.gesture=e,e.preventDefault()},move:function(e){e.event.target.tagName.match(/textarea|input/i)||(t.dimension.enabled||n.dimension.enabled?(t.dragMove(e.x.delta),n.dragMove(e.y.delta),e.preventDefault()):e.touch.skip())},end:function(e){e.preventDefault()}})}}),Q=w.transitions.prefix+"Transform";p=w.hasHW3D?function(e,t,n){return"translate3d("+e+"px,"+t+"px,0) scale("+n+")"}:function(e,t,n){return"translate("+e+"px,"+t+"px) scale("+n+")"},f=C.extend({init:function(t){var n=this;C.fn.init.call(n),n.element=e(t),n.element[0].style.webkitTransformOrigin="left top",n.x=0,n.y=0,n.scale=1,n._saveCoordinates(p(n.x,n.y,n.scale))},translateAxis:function(e,t){this[e]+=t,this.refresh()},scaleTo:function(e){this.scale=e,this.refresh()},scaleWith:function(e){this.scale*=e,this.refresh()},translate:function(e){this.x+=e.x,this.y+=e.y,this.refresh()},moveAxis:function(e,t){this[e]=t,this.refresh()},moveTo:function(e){D(this,e),this.refresh()},refresh:function(){var e,t=this,n=t.x,i=t.y;t.round&&(n=Math.round(n),i=Math.round(i)),e=p(n,i,t.scale),e!=t.coordinates&&(_.support.browser.msie&&10>_.support.browser.version?(t.element[0].style.position="absolute",t.element[0].style.left=t.x+"px",t.element[0].style.top=t.y+"px"):t.element[0].style[Q]=e,t._saveCoordinates(e),t.trigger(F))},_saveCoordinates:function(e){this.coordinates=e}}),g=x.extend({init:function(e,t){var n,i=this;x.fn.init.call(i,e,t),n=i.options.group,n in I?I[n].push(i):I[n]=[i]},events:[V,U,W],options:{name:"DropTarget",group:"default"},destroy:function(){s(I,this)},_trigger:function(e,n){var i=this,r=E[i.options.group];return r?i.trigger(e,D({},n.event,{draggable:r,dropTarget:n.dropTarget})):t},_over:function(e){this._trigger(V,e)},_out:function(e){this._trigger(U,e)},_drop:function(e){var t=this,n=E[t.options.group];n&&(n.dropped=!t._trigger(W,e))}}),g.destroyGroup=function(e){var t,n=I[e]||P[e];if(n){for(t=0;n.length>t;t++)x.fn.destroy.call(n[t]);n.length=0,delete I[e],delete P[e]}},g._cache=I,m=g.extend({init:function(e,t){var n,i=this;x.fn.init.call(i,e,t),n=i.options.group,n in P?P[n].push(i):P[n]=[i]},destroy:function(){s(P,this)},options:{name:"DropTargetArea",group:"default",filter:null}}),v=x.extend({init:function(e,t){var n=this;x.fn.init.call(n,e,t),n._activated=!1,n.userEvents=new S(n.element,{global:!0,allowSelection:!0,filter:n.options.filter,threshold:n.options.distance,start:T(n._start,n),hold:T(n._hold,n),move:T(n._drag,n),end:T(n._end,n),cancel:T(n._cancel,n),select:T(n._select,n)}),n._afterEndHandler=T(n._afterEnd,n),n._captureEscape=T(n._captureEscape,n)},events:[H,R,B,L,N,O],options:{name:"Draggable",distance:_.support.touch?0:5,group:"default",cursorOffset:null,axis:null,container:null,filter:null,ignore:null,holdToDrag:!1,autoScroll:!1,dropped:!1},cancelHold:function(){this._activated=!1},_captureEscape:function(e){var t=this;e.keyCode===_.keys.ESC&&(t._trigger(N,{event:e}),t.userEvents.cancel())},_updateHint:function(t){var n,i=this,o=i.options,a=i.boundaries,s=o.axis,l=i.options.cursorOffset;l?n={left:t.x.location+l.left,top:t.y.location+l.top}:(i.hintOffset.left+=t.x.delta,i.hintOffset.top+=t.y.delta,n=e.extend({},i.hintOffset)),a&&(n.top=r(n.top,a.y),n.left=r(n.left,a.x)),"x"===s?delete n.top:"y"===s&&delete n.left,i.hint.css(n)},_shouldIgnoreTarget:function(t){var n=this.options.ignore;return n&&e(t).is(n)},_select:function(e){this._shouldIgnoreTarget(e.event.target)||e.preventDefault()},_start:function(n){var i,r=this,a=r.options,s=a.container,l=a.hint;return this._shouldIgnoreTarget(n.touch.initialTouch)||a.holdToDrag&&!r._activated?(r.userEvents.cancel(),t):(r.currentTarget=n.target,r.currentTargetOffset=A(r.currentTarget),l&&(r.hint&&r.hint.stop(!0,!0).remove(),r.hint=_.isFunction(l)?e(l.call(r,r.currentTarget)):l,i=A(r.currentTarget),r.hintOffset=i,r.hint.css({position:"absolute",zIndex:2e4,left:i.left,top:i.top}).appendTo(b.body),r.angular("compile",function(){r.hint.removeAttr("ng-repeat");for(var t=e(n.target);!t.data("$$kendoScope")&&t.length;)t=t.parent();return{elements:r.hint.get(),scopeFrom:t.data("$$kendoScope")}})),E[a.group]=r,r.dropped=!1,s&&(r.boundaries=o(s,r.hint)),r._trigger(R,n)&&(r.userEvents.cancel(),r._afterEnd()),r.userEvents.capture(),e(b).on(z,r._captureEscape),t)},_hold:function(e){this.currentTarget=e.target,this._trigger(H,e)?this.userEvents.cancel():this._activated=!0},_drag:function(n){var i,r,o=this;n.preventDefault(),i=this._elementUnderCursor(n),o._withDropTarget(i,function(i,r){if(!i)return h&&(h._trigger(U,D(n,{dropTarget:e(h.targetElement)})),h=null),t;if(h){if(r===h.targetElement)return;h._trigger(U,D(n,{dropTarget:e(h.targetElement)}))}i._trigger(V,D(n,{dropTarget:e(r)})),h=D(i,{targetElement:r})}),o._trigger(B,D(n,{dropTarget:h,elementUnderCursor:i})),this.options.autoScroll&&(this._cursorElement!==i&&(this._scrollableParent=d(i),this._cursorElement=i),this._scrollableParent[0]&&(r=u(n.x.location,n.y.location,l(this._scrollableParent)),this._scrollCompenstation=e.extend({},this.hintOffset),this._scrollVelocity=r,0===r.y&&0===r.x?(clearInterval(this._scrollInterval),this._scrollInterval=null):this._scrollInterval||(this._scrollInterval=setInterval(e.proxy(this,"_autoScroll"),50)))),o.hint&&o._updateHint(n)},_autoScroll:function(){var e,t,n,i,r,o,a,s=this._scrollableParent[0],l=this._scrollVelocity,c=this._scrollCompenstation;s&&(n=s===b.body,n?(e=b.body.offsetHeight>y.height(),t=b.body.offsetWidth>y.width()):(e=s.scrollHeight>=s.offsetHeight,t=s.scrollWidth>=s.offsetWidth),i=s.scrollTop+l.y,r=e&&i>0&&s.scrollHeight>i,o=s.scrollLeft+l.x,a=t&&o>0&&s.scrollWidth>o,r&&(s.scrollTop+=l.y),a&&(s.scrollLeft+=l.x),n&&(a||r)&&(r&&(c.top+=l.y),a&&(c.left+=l.x),this.hint.css(c)))},_end:function(t){this._withDropTarget(this._elementUnderCursor(t),function(n,i){n&&(n._drop(D({},t,{dropTarget:e(i)})),h=null)}),this._trigger(L,t),this._cancel(t.event)},_cancel:function(){var e=this;e._scrollableParent=null,clearInterval(this._scrollInterval),e._activated=!1,e.hint&&!e.dropped?setTimeout(function(){e.hint.stop(!0,!0).animate(e.currentTargetOffset,"fast",e._afterEndHandler)},0):e._afterEnd()},_trigger:function(e,t){var n=this;return n.trigger(e,D({},t.event,{x:t.x,y:t.y,currentTarget:n.currentTarget,initialTarget:t.touch?t.touch.initialTouch:null,dropTarget:t.dropTarget,elementUnderCursor:t.elementUnderCursor}))},_elementUnderCursor:function(e){var t=M(e),i=this.hint;return i&&n(i[0],t)&&(i.hide(),t=M(e),t||(t=M(e)),i.show()),t},_withDropTarget:function(e,t){var n,i=this.options.group,r=I[i],o=P[i];(r&&r.length||o&&o.length)&&(n=a(e,r,o),n?t(n.target,n.targetElement):t())},destroy:function(){var e=this;x.fn.destroy.call(e),e._afterEnd(),e.userEvents.destroy(),this._scrollableParent=null,this._cursorElement=null,clearInterval(this._scrollInterval),e.currentTarget=null},_afterEnd:function(){var t=this;t.hint&&t.hint.remove(),delete E[t.options.group],t.trigger("destroy"),t.trigger(O),e(b).off(z,t._captureEscape)}}),_.ui.plugin(g),_.ui.plugin(m),_.ui.plugin(v),_.TapCapture=j,_.containerBoundaries=o,D(_.ui,{Pane:Y,PaneDimensions:q,Movable:f}),_.ui.Draggable.utils={autoScrollVelocity:u,scrollableViewPort:l,findScrollableParent:d}}(window.kendo.jQuery),function(e,t){var n=window.kendo,i=n.mobile,r=n.effects,o=i.ui,a=e.proxy,s=e.extend,l=o.Widget,c=n.Class,d=n.ui.Movable,u=n.ui.Pane,h=n.ui.PaneDimensions,p=r.Transition,f=r.Animation,g=Math.abs,m=500,v=.7,_=.96,w=10,b=55,y=.5,k=5,x="km-scroller-release",C="km-scroller-refresh",S="pull",T="change",D="resize",A="scroll",E=2,I=f.extend({init:function(e){var t=this;f.fn.init.call(t),s(t,e),t.userEvents.bind("gestureend",a(t.start,t)),t.tapCapture.bind("press",a(t.cancel,t))},enabled:function(){return this.dimensions.minScale>this.movable.scale},done:function(){return.01>this.dimensions.minScale-this.movable.scale},tick:function(){var e=this.movable;e.scaleWith(1.1),this.dimensions.rescale(e.scale)},onEnd:function(){var e=this.movable;e.scaleTo(this.dimensions.minScale),this.dimensions.rescale(e.scale)}}),P=f.extend({init:function(e){var t=this;f.fn.init.call(t),s(t,e,{transition:new p({axis:e.axis,movable:e.movable,onEnd:function(){t._end()}})}),t.tapCapture.bind("press",function(){t.cancel()}),t.userEvents.bind("end",a(t.start,t)),t.userEvents.bind("gestureend",a(t.start,t)),t.userEvents.bind("tap",a(t.onEnd,t))},onCancel:function(){this.transition.cancel()},freeze:function(e){var t=this;t.cancel(),t._moveTo(e)},onEnd:function(){var e=this;e.paneAxis.outOfBounds()?e._snapBack():e._end()},done:function(){return g(this.velocity)<1},start:function(e){var t,n=this;n.dimension.enabled&&(n.paneAxis.outOfBounds()?n._snapBack():(t=e.touch.id===E?0:e.touch[n.axis].velocity,n.velocity=Math.max(Math.min(t*n.velocityMultiplier,b),-b),n.tapCapture.captureNext(),f.fn.start.call(n)))},tick:function(){var e=this,t=e.dimension,n=e.paneAxis.outOfBounds()?y:e.friction,i=e.velocity*=n,r=e.movable[e.axis]+i;!e.elastic&&t.outOfBounds(r)&&(r=Math.max(Math.min(r,t.max),t.min),e.velocity=0),e.movable.moveAxis(e.axis,r)},_end:function(){this.tapCapture.cancelCapture(),this.end()},_snapBack:function(){var e=this,t=e.dimension,n=e.movable[e.axis]>t.max?t.max:t.min;e._moveTo(n)},_moveTo:function(e){this.transition.moveTo({location:e,duration:m,ease:p.easeOutExpo})}}),M=f.extend({init:function(e){var t=this;n.effects.Animation.fn.init.call(this),s(t,e,{origin:{},destination:{},offset:{}})},tick:function(){this._updateCoordinates(),this.moveTo(this.origin)},done:function(){return g(this.offset.y)');s(n,t,{element:r,elementSize:0,movable:new d(r),scrollMovable:t.movable,alwaysVisible:t.alwaysVisible,size:i?"width":"height"}),n.scrollMovable.bind(T,a(n.refresh,n)),n.container.append(r),t.alwaysVisible&&n.show()},refresh:function(){var e=this,t=e.axis,n=e.dimension,i=n.size,r=e.scrollMovable,o=i/n.total,a=Math.round(-r[t]*o),s=Math.round(i*o);o>=1?this.element.css("display","none"):this.element.css("display",""),a+s>i?s=i-a:0>a&&(s+=a,a=0),e.elementSize!=s&&(e.element.css(e.size,s+"px"),e.elementSize=s),e.movable.moveAxis(t,a)},show:function(){this.element.css({opacity:v,visibility:"visible"})},hide:function(){this.alwaysVisible||this.element.css({opacity:0})}}),F=l.extend({init:function(i,r){var o,c,p,f,m,v,_,w,b,y=this;return l.fn.init.call(y,i,r),i=y.element,(y._native=y.options.useNative&&n.support.hasNativeScrolling)?(i.addClass("km-native-scroller").prepend('
    '),s(y,{scrollElement:i,fixedContainer:i.children().first()}),t):(i.css("overflow","hidden").addClass("km-scroll-wrapper").wrapInner('
    ').prepend('
    '),o=i.children().eq(1),c=new n.TapCapture(i),p=new d(o),f=new h({element:o,container:i,forcedEnabled:y.options.zoom}),m=this.options.avoidScrolling,v=new n.UserEvents(i,{allowSelection:!0,preventDragEvent:!0,captureUpIfMoved:!0,multiTouch:y.options.zoom,start:function(t){f.refresh();var n=g(t.x.velocity),i=g(t.y.velocity),r=2*n>=i,o=e.contains(y.fixedContainer[0],t.event.target),a=2*i>=n;!o&&!m(t)&&y.enabled&&(f.x.enabled&&r||f.y.enabled&&a)?v.capture():v.cancel()}}),_=new u({movable:p,dimensions:f,userEvents:v,elastic:y.options.elastic}),w=new I({movable:p,dimensions:f,userEvents:v,tapCapture:c}),b=new M({moveTo:function(e){y.scrollTo(e.x,e.y)}}),p.bind(T,function(){y.scrollTop=-p.y,y.scrollLeft=-p.x,y.trigger(A,{scrollTop:y.scrollTop,scrollLeft:y.scrollLeft})}),y.options.mousewheelScrolling&&i.on("DOMMouseScroll mousewheel",a(this,"_wheelScroll")),s(y,{movable:p,dimensions:f,zoomSnapBack:w,animatedScroller:b,userEvents:v,pane:_,tapCapture:c,pulled:!1,enabled:!0,scrollElement:o,scrollTop:0,scrollLeft:0,fixedContainer:i.children().first()}),y._initAxis("x"),y._initAxis("y"),y._wheelEnd=function(){y._wheel=!1,y.userEvents.end(0,y._wheelY)},f.refresh(),y.options.pullToRefresh&&y._initPullToRefresh(),t)},_wheelScroll:function(e){this._wheel||(this._wheel=!0,this._wheelY=0,this.userEvents.press(0,this._wheelY)),clearTimeout(this._wheelTimeout),this._wheelTimeout=setTimeout(this._wheelEnd,50);var t=n.wheelDeltaY(e);t&&(this._wheelY+=t,this.userEvents.move(0,this._wheelY)),e.preventDefault()},makeVirtual:function(){this.dimensions.y.makeVirtual()},virtualSize:function(e,t){this.dimensions.y.virtualSize(e,t)},height:function(){return this.dimensions.y.size},scrollHeight:function(){return this.scrollElement[0].scrollHeight},scrollWidth:function(){return this.scrollElement[0].scrollWidth},options:{name:"Scroller",zoom:!1,pullOffset:140,visibleScrollHints:!1,elastic:!0,useNative:!1,mousewheelScrolling:!0,avoidScrolling:function(){return!1},pullToRefresh:!1,messages:{pullTemplate:"Pull to refresh",releaseTemplate:"Release to refresh",refreshTemplate:"Refreshing"}},events:[S,A,D],_resize:function(){this._native||this.contentResized()},setOptions:function(e){var t=this;l.fn.setOptions.call(t,e),e.pullToRefresh&&t._initPullToRefresh()},reset:function(){this._native?this.scrollElement.scrollTop(0):(this.movable.moveTo({x:0,y:0}),this._scale(1))},contentResized:function(){this.dimensions.refresh(),this.pane.x.outOfBounds()&&this.movable.moveAxis("x",this.dimensions.x.min),this.pane.y.outOfBounds()&&this.movable.moveAxis("y",this.dimensions.y.min)},zoomOut:function(){var e=this.dimensions;e.refresh(),this._scale(e.fitScale),this.movable.moveTo(e.centerCoordinates())},enable:function(){this.enabled=!0},disable:function(){this.enabled=!1},scrollTo:function(e,t){this._native?(this.scrollElement.scrollLeft(g(e)),this.scrollElement.scrollTop(g(t))):(this.dimensions.refresh(),this.movable.moveTo({x:e,y:t}))},animatedScrollTo:function(e,t,n){var i,r;this._native?this.scrollTo(e,t):(i={x:this.movable.x,y:this.movable.y},r={x:e,y:t},this.animatedScroller.setCoordinates(i,r),this.animatedScroller.setCallback(n),this.animatedScroller.start())},pullHandled:function(){var e=this;e.refreshHint.removeClass(C),e.hintContainer.html(e.pullTemplate({})),e.yinertia.onEnd(),e.xinertia.onEnd(),e.userEvents.cancel()},destroy:function(){l.fn.destroy.call(this),this.userEvents&&this.userEvents.destroy()},_scale:function(e){this.dimensions.rescale(e),this.movable.scaleTo(e)},_initPullToRefresh:function(){var e=this;e.dimensions.y.forceEnabled(),e.pullTemplate=n.template(e.options.messages.pullTemplate),e.releaseTemplate=n.template(e.options.messages.releaseTemplate),e.refreshTemplate=n.template(e.options.messages.refreshTemplate),e.scrollElement.prepend(''+e.pullTemplate({})+""),e.refreshHint=e.scrollElement.children().first(),e.hintContainer=e.refreshHint.children(".km-template"),e.pane.y.bind("change",a(e._paneChange,e)),e.userEvents.bind("end",a(e._dragEnd,e))},_dragEnd:function(){var e=this; -e.pulled&&(e.pulled=!1,e.refreshHint.removeClass(x).addClass(C),e.hintContainer.html(e.refreshTemplate({})),e.yinertia.freeze(e.options.pullOffset/2),e.trigger("pull"))},_paneChange:function(){var e=this;e.movable.y/y>e.options.pullOffset?e.pulled||(e.pulled=!0,e.refreshHint.removeClass(C).addClass(x),e.hintContainer.html(e.releaseTemplate({}))):e.pulled&&(e.pulled=!1,e.refreshHint.removeClass(x),e.hintContainer.html(e.pullTemplate({})))},_initAxis:function(e){var t=this,n=t.movable,i=t.dimensions[e],r=t.tapCapture,o=t.pane[e],a=new z({axis:e,movable:n,dimension:i,container:t.element,alwaysVisible:t.options.visibleScrollHints});i.bind(T,function(){a.refresh()}),o.bind(T,function(){a.show()}),t[e+"inertia"]=new P({axis:e,paneAxis:o,movable:n,tapCapture:r,userEvents:t.userEvents,dimension:i,elastic:t.options.elastic,friction:t.options.friction||_,velocityMultiplier:t.options.velocityMultiplier||w,end:function(){a.hide(),t.trigger("scrollEnd",{axis:e,scrollTop:t.scrollTop,scrollLeft:t.scrollLeft})}})}});o.plugin(F)}(window.kendo.jQuery),function(e,t){function n(e){return e.position().top+3}var i=window.kendo,r=i.ui.Widget,o=e.proxy,a=!1,s=".kendoGroupable",l="change",c=i.template('',{useWithBlock:!1}),d=function(t){return e('
    ').css({width:t.width(),paddingLeft:t.css("paddingLeft"),paddingRight:t.css("paddingRight"),lineHeight:t.height()+"px",paddingTop:t.css("paddingTop"),paddingBottom:t.css("paddingBottom")}).html(t.attr(i.attr("title"))||t.attr(i.attr("field"))).prepend('')},u=e('
    '),h=r.extend({init:function(c,h){var p,f,g=this,m=i.guid(),v=o(g._intializePositions,g),_=g._dropCuePositions=[];r.fn.init.call(g,c,h),a=i.support.isRtl(c),f=a?"right":"left",g.draggable=p=g.options.draggable||new i.ui.Draggable(g.element,{filter:g.options.draggableElements,hint:d,group:m}),g.groupContainer=e(g.options.groupContainer,g.element).kendoDropTarget({group:p.options.group,dragenter:function(e){g._canDrag(e.draggable.currentTarget)&&(e.draggable.hint.find(".k-drag-status").removeClass("k-denied").addClass("k-add"),u.css("top",n(g.groupContainer)).css(f,0).appendTo(g.groupContainer))},dragleave:function(e){e.draggable.hint.find(".k-drag-status").removeClass("k-add").addClass("k-denied"),u.remove()},drop:function(t){var n,r=t.draggable.currentTarget,o=r.attr(i.attr("field")),s=r.attr(i.attr("title")),l=g.indicator(o),c=g._dropCuePositions,d=c[c.length-1];(r.hasClass("k-group-indicator")||g._canDrag(r))&&(d?(n=g._dropCuePosition(i.getOffset(u).left+parseInt(d.element.css("marginLeft"),10)*(a?-1:1)+parseInt(d.element.css("marginRight"),10)),n&&g._canDrop(e(l),n.element,n.left)&&(n.before?n.element.before(l||g.buildIndicator(o,s)):n.element.after(l||g.buildIndicator(o,s)),g._change())):(g.groupContainer.append(g.buildIndicator(o,s)),g._change()))}}).kendoDraggable({filter:"div.k-group-indicator",hint:d,group:p.options.group,dragcancel:o(g._dragCancel,g),dragstart:function(e){var t=e.currentTarget,i=parseInt(t.css("marginLeft"),10),r=t.position(),o=a?r.left-i:r.left+t.outerWidth();v(),u.css({top:n(g.groupContainer),left:o}).appendTo(g.groupContainer),this.hint.find(".k-drag-status").removeClass("k-denied").addClass("k-add")},dragend:function(){g._dragEnd(this)},drag:o(g._drag,g)}).on("click"+s,".k-button",function(t){t.preventDefault(),g._removeIndicator(e(this).parent())}).on("click"+s,".k-link",function(t){var n=e(this).parent(),r=g.buildIndicator(n.attr(i.attr("field")),n.attr(i.attr("title")),"asc"==n.attr(i.attr("dir"))?"desc":"asc");n.before(r).remove(),g._change(),t.preventDefault()}),p.bind(["dragend","dragcancel","dragstart","drag"],{dragend:function(){g._dragEnd(this)},dragcancel:o(g._dragCancel,g),dragstart:function(e){var n,i,r;return g.options.allowDrag||g._canDrag(e.currentTarget)?(v(),_.length?(n=_[_.length-1].element,i=parseInt(n.css("marginRight"),10),r=n.position().left+n.outerWidth()+i):r=0,t):(e.preventDefault(),t)},drag:o(g._drag,g)}),g.dataSource=g.options.dataSource,g.dataSource&&g._refreshHandler?g.dataSource.unbind(l,g._refreshHandler):g._refreshHandler=o(g.refresh,g),g.dataSource&&(g.dataSource.bind("change",g._refreshHandler),g.refresh())},refresh:function(){var t=this,n=t.dataSource;t.groupContainer&&t.groupContainer.empty().append(e.map(n.group()||[],function(n){var r=n.field,o=i.attr("field"),a=t.element.find(t.options.filter).filter(function(){return e(this).attr(o)===r});return t.buildIndicator(n.field,a.attr(i.attr("title")),n.dir)}).join("")),t._invalidateGroupContainer()},destroy:function(){var e=this;r.fn.destroy.call(e),e.groupContainer.off(s),e.groupContainer.data("kendoDropTarget")&&e.groupContainer.data("kendoDropTarget").destroy(),e.groupContainer.data("kendoDraggable")&&e.groupContainer.data("kendoDraggable").destroy(),e.options.draggable||e.draggable.destroy(),e.dataSource&&e._refreshHandler&&(e.dataSource.unbind("change",e._refreshHandler),e._refreshHandler=null),e.groupContainer=e.element=e.draggable=null},options:{name:"Groupable",filter:"th",draggableElements:"th",messages:{empty:"Drag a column header and drop it here to group by that column"}},indicator:function(t){var n=e(".k-group-indicator",this.groupContainer);return e.grep(n,function(n){return e(n).attr(i.attr("field"))===t})[0]},buildIndicator:function(e,t,n){return c({field:e.replace(/"/g,"'"),dir:n,title:t,ns:i.ns})},descriptors:function(){var t,n,r,o,a,s=this,l=e(".k-group-indicator",s.groupContainer);return t=s.element.find(s.options.filter).map(function(){var t=e(this),r=t.attr(i.attr("aggregates")),s=t.attr(i.attr("field"));if(r&&""!==r)for(n=r.split(","),r=[],o=0,a=n.length;a>o;o++)r.push({field:s,aggregate:n[o]});return r}).toArray(),e.map(l,function(n){return n=e(n),r=n.attr(i.attr("field")),{field:r,dir:n.attr(i.attr("dir")),aggregates:t||[]}})},_removeIndicator:function(e){var t=this;e.remove(),t._invalidateGroupContainer(),t._change()},_change:function(){var e=this;e.dataSource&&e.dataSource.group(e.descriptors())},_dropCuePosition:function(t){var n,i,r,o,s,l=this._dropCuePositions;if(u.is(":visible")&&0!==l.length)return t=Math.ceil(t),n=l[l.length-1],i=n.left,r=n.right,o=parseInt(n.element.css("marginLeft"),10),s=parseInt(n.element.css("marginRight"),10),t>=r&&!a||i>t&&a?t={left:n.element.position().left+(a?-o:n.element.outerWidth()+s),element:n.element,before:!1}:(t=e.grep(l,function(e){return t>=e.left&&e.right>=t||a&&t>e.right})[0],t&&(t={left:a?t.element.position().left+t.element.outerWidth()+s:t.element.position().left-o,element:t.element,before:!0})),t},_drag:function(e){var t=this._dropCuePosition(e.x.location);t&&u.css({left:t.left,right:"auto"})},_canDrag:function(e){var t=e.attr(i.attr("field"));return"false"!=e.attr(i.attr("groupable"))&&t&&(e.hasClass("k-group-indicator")||!this.indicator(t))},_canDrop:function(e,t,n){var i=e.next(),r=e[0]!==t[0]&&(!i[0]||t[0]!==i[0]||!a&&n>i.position().left||a&&n
    '),s.find(c.options.filter).kendoDropTarget({group:c.options.group,dragenter:function(e){var n,r,o,a;d._draggable&&(n=this.element,o=!d._dropTargetAllowed(n)||d._isLastDraggable(),t(e.draggable.hint,o),o||(r=i(n),a=r.left,l.inSameContainer&&!l.inSameContainer({source:n,target:d._draggable,sourceIndex:d._index(n),targetIndex:d._index(d._draggable)})?d._dropTarget=n:d._index(n)>d._index(d._draggable)&&(a+=n.outerWidth()),d.reorderDropCue.css({height:n.outerHeight(),top:r.top,left:a}).appendTo(document.body)))},dragleave:function(e){t(e.draggable.hint,!0),d.reorderDropCue.remove(),d._dropTarget=null},drop:function(){var e,t,n;d._dropTarget=null,d._draggable&&(e=this.element,t=d._draggable,n=!1,d._dropTargetAllowed(e)&&!d._isLastDraggable()&&d.trigger(o,{element:d._draggable,target:e,oldIndex:d._index(t),newIndex:d._index(e),position:i(d.reorderDropCue).left>i(e).left?"after":"before"}))}}),c.bind(["dragcancel","dragend","dragstart","drag"],{dragcancel:function(){d.reorderDropCue.remove(),d._draggable=null,d._elements=null},dragend:function(){d.reorderDropCue.remove(),d._draggable=null,d._elements=null},dragstart:function(e){d._draggable=e.currentTarget,d._elements=d.element.find(d.draggable.options.filter)},drag:function(e){var t,n;d._dropTarget&&!this.hint.find(".k-drag-status").hasClass("k-denied")&&(t=i(d._dropTarget).left,n=d._dropTarget.outerWidth(),d.reorderDropCue.css(e.pageX>t+n/2?{left:t+n}:{left:t}))}})},options:{name:"Reorderable",filter:"*"},events:[o],_isLastDraggable:function(){var e,t=this.options.inSameContainer,n=this._draggable[0],i=this._elements.get(),r=!1;if(!t)return!1;for(;!r&&i.length>0;)e=i.pop(),r=n!==e&&t({source:n,target:e,sourceIndex:this._index(n),targetIndex:this._index(e)});return!r},_dropTargetAllowed:function(e){var t=this.options.inSameContainer,n=this.options.dragOverContainers,i=this._draggable;return i[0]===e[0]?!1:t&&n?t({source:i,target:e,sourceIndex:this._index(i),targetIndex:this._index(e)})?!0:n(this._index(i),this._index(e)):!0},_index:function(e){return this._elements.index(e)},destroy:function(){var t=this;r.fn.destroy.call(t),t.element.find(t.draggable.options.filter).each(function(){var t=e(this);t.data("kendoDropTarget")&&t.data("kendoDropTarget").destroy()}),t.draggable&&(t.draggable.destroy(),t.draggable.element=t.draggable=null),t.elements=t.reorderDropCue=t._elements=t._draggable=null}});n.ui.plugin(s)}(window.kendo.jQuery),function(e,t){var n=window.kendo,i=n.ui,r=i.Widget,o=e.proxy,a=n.isFunction,s=e.extend,l="horizontal",c="vertical",d="start",u="resize",h="resizeend",p=r.extend({init:function(e,t){var n=this;r.fn.init.call(n,e,t),n.orientation=n.options.orientation.toLowerCase()!=c?l:c,n._positionMouse=n.orientation==l?"x":"y",n._position=n.orientation==l?"left":"top",n._sizingDom=n.orientation==l?"outerWidth":"outerHeight",n.draggable=new i.Draggable(e,{distance:1,filter:t.handle,drag:o(n._resize,n),dragcancel:o(n._cancel,n),dragstart:o(n._start,n),dragend:o(n._stop,n)}),n.userEvents=n.draggable.userEvents},events:[u,h,d],options:{name:"Resizable",orientation:l},resize:function(){},_max:function(e){var n=this,i=n.hint?n.hint[n._sizingDom]():0,r=n.options.max;return a(r)?r(e):r!==t?n._initialElementPosition+r-i:r},_min:function(e){var n=this,i=n.options.min;return a(i)?i(e):i!==t?n._initialElementPosition+i:i},_start:function(t){var n=this,i=n.options.hint,r=e(t.currentTarget);n._initialElementPosition=r.position()[n._position],n._initialMousePosition=t[n._positionMouse].startLocation,i&&(n.hint=a(i)?e(i(r)):i,n.hint.css({position:"absolute"}).css(n._position,n._initialElementPosition).appendTo(n.element)),n.trigger(d,t),n._maxPosition=n._max(t),n._minPosition=n._min(t),e(document.body).css("cursor",r.css("cursor"))},_resize:function(e){var n,i=this,r=i._maxPosition,o=i._minPosition,a=i._initialElementPosition+(e[i._positionMouse].location-i._initialMousePosition);n=o!==t?Math.max(o,a):a,i.position=n=r!==t?Math.min(r,n):n,i.hint&&i.hint.toggleClass(i.options.invalidClass||"",n==r||n==o).css(i._position,n),i.resizing=!0,i.trigger(u,s(e,{position:n}))},_stop:function(t){var n=this;n.hint&&n.hint.remove(),n.resizing=!1,n.trigger(h,s(t,{position:n.position})),e(document.body).css("cursor","")},_cancel:function(e){var n=this;n.hint&&(n.position=t,n.hint.css(n._position,n._initialElementPosition),n._stop(e))},destroy:function(){var e=this;r.fn.destroy.call(e),e.draggable&&e.draggable.destroy()},press:function(e){if(e){var t=e.position(),n=this;n.userEvents.press(t.left,t.top,e[0]),n.targetPosition=t,n.target=e}},move:function(e){var n=this,i=n._position,r=n.targetPosition,o=n.position;o===t&&(o=r[i]),r[i]=o+e,n.userEvents.move(r.left,r.top)},end:function(){this.userEvents.end(),this.target=this.position=t}});n.ui.plugin(p)}(window.kendo.jQuery),function(e,t){function n(t,n){try{return e.contains(t,n)||t==n}catch(i){return!1}}function i(e){return e.clone()}function r(e){return e.clone().removeAttr("id").css("visibility","hidden")}var o=window.kendo,a=o.ui.Widget,s="start",l="beforeMove",c="move",d="end",u="change",h="cancel",p="sort",f="remove",g="receive",m=">*",v=-1,_=a.extend({init:function(e,t){var n=this;a.fn.init.call(n,e,t),n.options.placeholder||(n.options.placeholder=r),n.options.hint||(n.options.hint=i),n._draggable=n._createDraggable()},events:[s,l,c,d,u,h],options:{name:"Sortable",hint:null,placeholder:null,filter:m,holdToDrag:!1,disabled:null,container:null,connectWith:null,handler:null,cursorOffset:null,axis:null,ignore:null,autoScroll:!1,cursor:"auto"},destroy:function(){this._draggable.destroy(),a.fn.destroy.call(this)},_createDraggable:function(){var t=this,n=t.element,i=t.options;return new o.ui.Draggable(n,{filter:i.filter,hint:o.isFunction(i.hint)?i.hint:e(i.hint),holdToDrag:i.holdToDrag,container:i.container?e(i.container):null,cursorOffset:i.cursorOffset,axis:i.axis,ignore:i.ignore,autoScroll:i.autoScroll,dragstart:e.proxy(t._dragstart,t),dragcancel:e.proxy(t._dragcancel,t),drag:e.proxy(t._drag,t),dragend:e.proxy(t._dragend,t)})},_dragstart:function(t){var n=this.draggedElement=t.currentTarget,i=(t.target||o.elementUnderCursor(t),this.options.disabled),r=this.options.handler,a=this.options.placeholder,l=this.placeholder=e(o.isFunction(a)?a.call(this,n):a);i&&n.is(i)?t.preventDefault():r&&!e(t.initialTarget).is(r)?t.preventDefault():this.trigger(s,{item:n,draggableEvent:t})?t.preventDefault():(n.css("display","none"),n.before(l),this._setCursor())},_dragcancel:function(){this._cancel(),this.trigger(h,{item:this.draggedElement}),this._resetCursor()},_drag:function(n){var i,r,o,a,s,l=this.draggedElement,c=this._findTarget(n),d={left:n.x.location,top:n.y.location},u={x:n.x.delta,y:n.y.delta},h=this.options.axis,p={item:l,list:this,draggableEvent:n};if("x"===h||"y"===h)return this._movementByAxis(h,d,u[h],p),t;if(c){if(i=this._getElementCenter(c.element),r={left:Math.round(d.left-i.left),top:Math.round(d.top-i.top)},e.extend(p,{target:c.element}),c.appendToBottom)return this._movePlaceholder(c,null,p),t;if(c.appendAfterHidden&&this._movePlaceholder(c,"next",p),this._isFloating(c.element)?0>u.x&&0>r.left?o="prev":u.x>0&&r.left>0&&(o="next"):0>u.y&&0>r.top?o="prev":u.y>0&&r.top>0&&(o="next"),o){for(s="prev"===o?jQuery.fn.prev:jQuery.fn.next,a=s.call(c.element);a.length&&!a.is(":visible");)a=s.call(a);a[0]!=this.placeholder[0]&&this._movePlaceholder(c,o,p)}}},_dragend:function(n){var i,r,o,a,s=this.placeholder,l=this.draggedElement,c=this.indexOf(l),h=this.indexOf(s),m=this.options.connectWith;return this._resetCursor(),o={action:p,item:l,oldIndex:c,newIndex:h,draggableEvent:n},h>=0?r=this.trigger(d,o):(i=s.parents(m).getKendoSortable(),o.action=f,a=e.extend({},o,{action:g,oldIndex:v,newIndex:i.indexOf(s)}),r=!(!this.trigger(d,o)&&!i.trigger(d,a))),r||h===c?(this._cancel(),t):(s.replaceWith(l),l.show(),this._draggable.dropped=!0,o={action:this.indexOf(l)!=v?p:f,item:l,oldIndex:c,newIndex:this.indexOf(l),draggableEvent:n},this.trigger(u,o),i&&(a=e.extend({},o,{action:g,oldIndex:v,newIndex:i.indexOf(l)}),i.trigger(u,a)),t)},_findTarget:function(n){var i,r,o=this._findElementUnderCursor(n),a=this.options.connectWith;return e.contains(this.element[0],o)?(i=this.items(),r=i.filter(o)[0]||i.has(o)[0],r?{element:e(r),sortable:this}:null):this.element[0]==o&&this._isEmpty()?{element:this.element,sortable:this,appendToBottom:!0}:this.element[0]==o&&this._isLastHidden()?(r=this.items().eq(0),{element:r,sortable:this,appendAfterHidden:!0}):a?this._searchConnectedTargets(o,n):t},_findElementUnderCursor:function(e){{var t=o.elementUnderCursor(e),i=e.sender;this.items()}return n(i.hint[0],t)&&(i.hint.hide(),t=o.elementUnderCursor(e),t||(t=o.elementUnderCursor(e)),i.hint.show()),t},_searchConnectedTargets:function(t,n){var i,r,o,a,s=e(this.options.connectWith);for(a=0;s.length>a;a++)if(i=s.eq(a).getKendoSortable(),e.contains(s[a],t)){if(i)return r=i.items(),o=r.filter(t)[0]||r.has(t)[0],o?(i.placeholder=this.placeholder,{element:e(o),sortable:i}):null}else if(s[a]==t){if(i&&i._isEmpty())return{element:s.eq(a),sortable:i,appendToBottom:!0};if(this._isCursorAfterLast(i,n))return o=i.items().last(),{element:o,sortable:i}}},_isCursorAfterLast:function(e,t){var n,i,r=e.items().last(),a={left:t.x.location,top:t.y.location};return n=o.getOffset(r),n.top+=r.outerHeight(),n.left+=r.outerWidth(),i=this._isFloating(r)?n.left-a.left:n.top-a.top,0>i?!0:!1},_movementByAxis:function(t,n,i,r){var o,a="x"===t?n.left:n.top,s=0>i?this.placeholder.prev():this.placeholder.next();s.length&&!s.is(":visible")&&(s=0>i?s.prev():s.next()),e.extend(r,{target:s}),o=this._getElementCenter(s),o&&(o="x"===t?o.left:o.top),s.length&&0>i&&0>a-o?this._movePlaceholder({element:s,sortable:this},"prev",r):s.length&&i>0&&a-o>0&&this._movePlaceholder({element:s,sortable:this},"next",r)},_movePlaceholder:function(e,t,n){var i=this.placeholder;e.sortable.trigger(l,n)||(t?"prev"===t?e.element.before(i):"next"===t&&e.element.after(i):e.element.append(i),e.sortable.trigger(c,n))},_setCursor:function(){var t,n=this.options.cursor;n&&"auto"!==n&&(t=e(document.body),this._originalCursorType=t.css("cursor"),t.css({cursor:n}),this._cursorStylesheet||(this._cursorStylesheet=e("")),this._cursorStylesheet.appendTo(t))},_resetCursor:function(){this._originalCursorType&&(e(document.body).css("cursor",this._originalCursorType),this._originalCursorType=null,this._cursorStylesheet.remove())},_getElementCenter:function(e){var t=e.length?o.getOffset(e):null;return t&&(t.top+=e.outerHeight()/2,t.left+=e.outerWidth()/2),t},_isFloating:function(e){return/left|right/.test(e.css("float"))||/inline|table-cell/.test(e.css("display"))},_cancel:function(){this.draggedElement.show(),this.placeholder.remove()},_items:function(){var e,t=this.options.filter;return e=t?this.element.find(t):this.element.children()},indexOf:function(e){var t=this._items(),n=this.placeholder,i=this.draggedElement;return n&&e[0]==n[0]?t.not(i).index(e):t.not(n).index(e)},items:function(){var e=this.placeholder,t=this._items();return e&&(t=t.not(e)),t},_isEmpty:function(){return!this.items().length},_isLastHidden:function(){return 1===this.items().length&&this.items().is(":hidden")}});o.ui.plugin(_)}(window.kendo.jQuery),function(e,t){function n(e,t){if(!e.is(":visible"))return!1;var n=r.getOffset(e),i=t.left+t.width,o=t.top+t.height;return n.right=n.left+e.outerWidth(),n.bottom=n.top+e.outerHeight(),!(n.left>i||t.left>n.right||n.top>o||t.top>n.bottom)}var i,r=window.kendo,o=r.ui.Widget,a=e.proxy,s=Math.abs,l="aria-selected",c="k-state-selected",d="k-state-selecting",u="k-selectable",h="change",p=".kendoSelectable",f="k-state-unselecting",g="input,a,textarea,.k-multiselect-wrap,select,button,a.k-button>.k-icon,button.k-button>.k-icon,span.k-icon.k-i-expand,span.k-icon.k-i-collapse",m=r.support.browser.msie,v=!1;!function(e){!function(){e('
    ').on("click",">*",function(){v=!0}).find("span").click().end().off()}()}(e),i=o.extend({init:function(t,n){var i,s=this;o.fn.init.call(s,t,n),s._marquee=e("
    "),s._lastActive=null,s.element.addClass(u),s.relatedTarget=s.options.relatedTarget,i=s.options.multiple,this.options.aria&&i&&s.element.attr("aria-multiselectable",!0),s.userEvents=new r.UserEvents(s.element,{global:!0,allowSelection:!0,filter:(v?"":"."+u+" ")+s.options.filter,tap:a(s._tap,s)}),i&&s.userEvents.bind("start",a(s._start,s)).bind("move",a(s._move,s)).bind("end",a(s._end,s)).bind("select",a(s._select,s))},events:[h],options:{name:"Selectable",filter:">*",multiple:!1,relatedTarget:e.noop},_isElement:function(e){var t,n=this.element,i=n.length,r=!1;for(e=e[0],t=0;i>t;t++)if(n[t]===e){r=!0;break}return r},_tap:function(t){var n,i=e(t.target),r=this,o=t.event.ctrlKey||t.event.metaKey,a=r.options.multiple,s=a&&t.event.shiftKey,l=t.event.which,d=t.event.button;!r._isElement(i.closest("."+u))||l&&3==l||d&&2==d||this._allowSelection(t.event.target)&&(n=i.hasClass(c),a&&o||r.clear(),i=i.add(r.relatedTarget(i)),s?r.selectRange(r._firstSelectee(),i):(n&&o?(r._unselect(i),r._notify(h)):r.value(i),r._lastActive=r._downTarget=i))},_start:function(n){var i,r=this,o=e(n.target),a=o.hasClass(c),s=n.event.ctrlKey||n.event.metaKey;if(this._allowSelection(n.event.target)){if(r._downTarget=o,!r._isElement(o.closest("."+u)))return r.userEvents.cancel(),t;r.options.useAllItems?r._items=r.element.find(r.options.filter):(i=o.closest(r.element),r._items=i.find(r.options.filter)),n.sender.capture(),r._marquee.appendTo(document.body).css({left:n.x.client+1,top:n.y.client+1,width:0,height:0}),s||r.clear(),o=o.add(r.relatedTarget(o)),a&&(r._selectElement(o,!0),s&&o.addClass(f))}},_move:function(e){var t=this,n={left:e.x.startLocation>e.x.location?e.x.location:e.x.startLocation,top:e.y.startLocation>e.y.location?e.y.location:e.y.startLocation,width:s(e.x.initialDelta),height:s(e.y.initialDelta)};t._marquee.css(n),t._invalidateSelectables(n,e.event.ctrlKey||e.event.metaKey),e.preventDefault()},_end:function(){var e,t=this;t._marquee.remove(),t._unselect(t.element.find(t.options.filter+"."+f)).removeClass(f),e=t.element.find(t.options.filter+"."+d),e=e.add(t.relatedTarget(e)),t.value(e),t._lastActive=t._downTarget,t._items=null},_invalidateSelectables:function(e,t){var i,r,o,a,s=this._downTarget[0],l=this._items;for(i=0,r=l.length;r>i;i++)a=l.eq(i),o=a.add(this.relatedTarget(a)),n(a,e)?a.hasClass(c)?t&&s!==a[0]&&o.removeClass(c).addClass(f):a.hasClass(d)||a.hasClass(f)||o.addClass(d):a.hasClass(d)?o.removeClass(d):t&&a.hasClass(f)&&o.removeClass(f).addClass(c)},value:function(e){var n=this,i=a(n._selectElement,n);return e?(e.each(function(){i(this)}),n._notify(h),t):n.element.find(n.options.filter+"."+c)},_firstSelectee:function(){var e,t=this;return null!==t._lastActive?t._lastActive:(e=t.value(),e.length>0?e[0]:t.element.find(t.options.filter)[0])},_selectElement:function(t,n){var i=e(t),r=!n&&this._notify("select",{element:t});i.removeClass(d),r||(i.addClass(c),this.options.aria&&i.attr(l,!0))},_notify:function(e,t){return t=t||{},this.trigger(e,t)},_unselect:function(e){return e.removeClass(c),this.options.aria&&e.attr(l,!1),e},_select:function(t){this._allowSelection(t.event.target)&&(!m||m&&!e(r._activeElement()).is(g))&&t.preventDefault()},_allowSelection:function(t){return e(t).is(g)?(this.userEvents.cancel(),this._downTarget=null,!1):!0},resetTouchEvents:function(){this.userEvents.cancel()},clear:function(){var e=this.element.find(this.options.filter+"."+c);this._unselect(e)},selectRange:function(t,n){var i,r,o,a=this;for(a.clear(),a.element.length>1&&(o=a.options.continuousItems()),o&&o.length||(o=a.element.find(a.options.filter)),t=e.inArray(e(t)[0],o),n=e.inArray(e(n)[0],o),t>n&&(r=t,t=n,n=r),a.options.useAllItems||(n+=a.element.length-1),i=t;n>=i;i++)a._selectElement(o[i]);a._notify(h)},destroy:function(){var e=this;o.fn.destroy.call(e),e.element.off(p),e.userEvents.destroy(),e._marquee=e._lastActive=e.element=e.userEvents=null}}),i.parseOptions=function(e){var t="string"==typeof e&&e.toLowerCase();return{multiple:t&&t.indexOf("multiple")>-1,cell:t&&t.indexOf("cell")>-1}},r.ui.plugin(i)}(window.kendo.jQuery),function(e,t){var n=window.kendo,i=n.ui.Widget,r=e.proxy,o=n.keys,a="click",s="k-button",l="k-button-icon",c="k-button-icontext",d=".kendoButton",u="disabled",h="k-state-disabled",p="k-state-focused",f="k-state-selected",g=i.extend({init:function(e,t){var o=this;i.fn.init.call(o,e,t),e=o.wrapper=o.element,t=o.options,e.addClass(s).attr("role","button"),t.enable=t.enable&&!e.attr(u),o.enable(t.enable),o._tabindex(),o._graphics(),e.on(a+d,r(o._click,o)).on("focus"+d,r(o._focus,o)).on("blur"+d,r(o._blur,o)).on("keydown"+d,r(o._keydown,o)).on("keyup"+d,r(o._keyup,o)),n.notify(o)},destroy:function(){var e=this;e.wrapper.off(d),i.fn.destroy.call(e)},events:[a],options:{name:"Button",icon:"",spriteCssClass:"",imageUrl:"",enable:!0},_isNativeButton:function(){return"button"==this.element.prop("tagName").toLowerCase()},_click:function(e){this.options.enable&&this.trigger(a,{event:e})&&e.preventDefault()},_focus:function(){this.options.enable&&this.element.addClass(p)},_blur:function(){this.element.removeClass(p)},_keydown:function(e){var t=this;t._isNativeButton()||(e.keyCode==o.ENTER||e.keyCode==o.SPACEBAR)&&(e.keyCode==o.SPACEBAR&&(e.preventDefault(),t.options.enable&&t.element.addClass(f)),t._click(e))},_keyup:function(){this.element.removeClass(f)},_graphics:function(){var t,n,i,r=this,o=r.element,a=r.options,s=a.icon,d=a.spriteCssClass,u=a.imageUrl;(d||u||s)&&(i=!0,o.contents().not("span.k-sprite").not("span.k-icon").not("img.k-image").each(function(t,n){(1==n.nodeType||3==n.nodeType&&e.trim(n.nodeValue).length>0)&&(i=!1)}),o.addClass(i?l:c)),s?(t=o.children("span.k-icon").first(),t[0]||(t=e('').prependTo(o)),t.addClass("k-i-"+s)):d?(t=o.children("span.k-sprite").first(),t[0]||(t=e('').prependTo(o)),t.addClass(d)):u&&(n=o.children("img.k-image").first(),n[0]||(n=e('icon').prependTo(o)),n.attr("src",u))},enable:function(e){var n=this,i=n.element;e===t&&(e=!0),e=!!e,n.options.enable=e,i.toggleClass(h,!e).attr("aria-disabled",!e).attr(u,!e);try{i.blur()}catch(r){}}});n.ui.plugin(g)}(window.kendo.jQuery),function(e,t){function n(e,t,n,i,r){return e({idx:t,text:n,ns:c.ns,numeric:i,title:r||""})}function i(e,t,n){return k({className:e.substring(1),text:t,wrapClassName:n||""})}function r(e,t,n,i){e.find(t).parent().attr(c.attr("page"),n).attr("tabindex",-1).toggleClass("k-state-disabled",i)}function o(e,t){r(e,p,1,1>=t)}function a(e,t){r(e,g,Math.max(1,t-1),1>=t)}function s(e,t,n){r(e,m,Math.min(n,t+1),t>=n)}function l(e,t,n){r(e,f,n,t>=n)}var c=window.kendo,d=c.ui,u=d.Widget,h=e.proxy,p=".k-i-seek-w",f=".k-i-seek-e",g=".k-i-arrow-w",m=".k-i-arrow-e",v="change",_=".kendoPager",w="click",b="keydown",y="disabled",k=c.template('#=text#'),x=u.extend({init:function(t,n){var r,d,y,k,x=this;u.fn.init.call(x,t,n),n=x.options,x.dataSource=c.data.DataSource.create(n.dataSource),x.linkTemplate=c.template(x.options.linkTemplate),x.selectTemplate=c.template(x.options.selectTemplate),x.currentPageTemplate=c.template(x.options.currentPageTemplate),r=x.page(),d=x.totalPages(),x._refreshHandler=h(x.refresh,x),x.dataSource.bind(v,x._refreshHandler),n.previousNext&&(x.element.find(p).length||(x.element.append(i(p,n.messages.first,"k-pager-first")),o(x.element,r,d)),x.element.find(g).length||(x.element.append(i(g,n.messages.previous)),a(x.element,r,d))),n.numeric&&(x.list=x.element.find(".k-pager-numbers"),x.list.length||(x.list=e('
      ').appendTo(x.element))),n.input&&(x.element.find(".k-pager-input").length||x.element.append(''+n.messages.page+''+c.format(n.messages.of,d)+""),x.element.on(b+_,".k-pager-input input",h(x._keydown,x))),n.previousNext&&(x.element.find(m).length||(x.element.append(i(m,n.messages.next)),s(x.element,r,d)),x.element.find(f).length||(x.element.append(i(f,n.messages.last,"k-pager-last")),l(x.element,r,d))),n.pageSizes&&(x.element.find(".k-pager-sizes").length||(y=n.pageSizes.length?n.pageSizes:["all",5,10,20],k=e.map(y,function(e){return e.toLowerCase&&"all"===e.toLowerCase()?"":""}),e(''+c.format(v.messages.of,b)).find("input").val(g).attr(y,1>w).toggleClass("k-state-disabled",1>w),v.previousNext&&(o(p.element,g,b),a(p.element,g,b),s(p.element,g,b),l(p.element,g,b)),v.pageSizes&&(d=p.element.find(".k-pager-sizes option[value='all']").length>0,u=d&&_===this.dataSource.total(),h=_,u&&(_="all",h=v.messages.allPages),p.element.find(".k-pager-sizes select").val(_).filter("["+c.attr("role")+"=dropdownlist]").kendoDropDownList("value",_).kendoDropDownList("text",h)) -}},_keydown:function(e){if(e.keyCode===c.keys.ENTER){var t=this.element.find(".k-pager-input").find("input"),n=parseInt(t.val(),10);(isNaN(n)||1>n||n>this.totalPages())&&(n=this.page()),t.val(n),this.page(n)}},_refreshClick:function(e){e.preventDefault(),this.dataSource.read()},_change:function(e){var t=e.currentTarget.value,n=parseInt(t,10),i=this.dataSource;isNaN(n)?"all"==t&&i.pageSize(i.total()):i.pageSize(n)},_toggleActive:function(){this.list.toggleClass("k-state-expanded")},_click:function(t){var n=e(t.currentTarget);t.preventDefault(),n.is(".k-state-disabled")||this.page(n.attr(c.attr("page")))},totalPages:function(){return Math.ceil((this.dataSource.total()||0)/this.pageSize())},pageSize:function(){return this.dataSource.pageSize()||this.dataSource.total()},page:function(e){return e===t?this.dataSource.total()>0?this.dataSource.page():0:(this.dataSource.page(e),this.trigger(v,{index:e}),t)}});d.plugin(x)}(window.kendo.jQuery),function(e){function t(t,n){return t===n||e.contains(t,n)}var n=window.kendo,i=n.ui,r=i.Widget,o=n.support,a=n.getOffset,s="open",l="close",c="deactivate",d="activate",u="center",h="left",p="right",f="top",g="bottom",m="absolute",v="hidden",_="body",w="location",b="position",y="visible",k="effects",x="k-state-active",C="k-state-border",S=/k-state-border-(\w+)/,T=".k-picker-wrap, .k-dropdown-wrap, .k-link",D="down",A=e(document.documentElement),E=e(window),I="scroll",P="resize scroll",M=o.transitions.css,z=M+"transform",F=e.extend,R=".kendoPopup",H=["font-size","font-family","font-stretch","font-style","font-weight","line-height"],B=r.extend({init:function(t,i){var o,a=this;i=i||{},i.isRtl&&(i.origin=i.origin||g+" "+p,i.position=i.position||f+" "+p),r.fn.init.call(a,t,i),t=a.element,i=a.options,a.collisions=i.collision?i.collision.split(" "):[],a.downEvent=n.applyEventMap(D,n.guid()),1===a.collisions.length&&a.collisions.push(a.collisions[0]),o=e(a.options.anchor).closest(".k-popup,.k-group").filter(":not([class^=km-])"),i.appendTo=e(e(i.appendTo)[0]||o[0]||_),a.element.hide().addClass("k-popup k-group k-reset").toggleClass("k-rtl",!!i.isRtl).css({position:m}).appendTo(i.appendTo).on("mouseenter"+R,function(){a._hovered=!0}).on("mouseleave"+R,function(){a._hovered=!1}),a.wrapper=e(),i.animation===!1&&(i.animation={open:{effects:{}},close:{hide:!0,effects:{}}}),F(i.animation.open,{complete:function(){a.wrapper.css({overflow:y}),a._activated=!0,a._trigger(d)}}),F(i.animation.close,{complete:function(){a._animationClose()}}),a._mousedownProxy=function(e){a._mousedown(e)},a._resizeProxy=function(e){a._resize(e)},i.toggleTarget&&e(i.toggleTarget).on(i.toggleEvent+R,e.proxy(a.toggle,a))},events:[s,d,l,c],options:{name:"Popup",toggleEvent:"click",origin:g+" "+h,position:f+" "+h,anchor:_,appendTo:null,collision:"flip fit",viewport:window,copyAnchorStyles:!0,autosize:!1,modal:!1,adjustSize:{width:0,height:0},animation:{open:{effects:"slideIn:down",transition:!0,duration:200},close:{duration:100,hide:!0}}},_animationClose:function(){var t,i,r,o,a=this,s=a.options;a.wrapper.hide(),t=a.wrapper.data(w),i=e(s.anchor),t&&a.wrapper.css(t),s.anchor!=_&&(r=((i.attr("class")||"").match(S)||["","down"])[1],o=C+"-"+r,i.removeClass(o).children(T).removeClass(x).removeClass(o),a.element.removeClass(C+"-"+n.directions[r].reverse)),a._closing=!1,a._trigger(c)},destroy:function(){var t,i=this,o=i.options,a=i.element.off(R);r.fn.destroy.call(i),o.toggleTarget&&e(o.toggleTarget).off(R),o.modal||(A.unbind(i.downEvent,i._mousedownProxy),i._scrollableParents().unbind(I,i._resizeProxy),E.unbind(P,i._resizeProxy)),n.destroy(i.element.children()),a.removeData(),o.appendTo[0]===document.body&&(t=a.parent(".k-animation-container"),t[0]?t.remove():a.remove())},open:function(t,i){var r,a,l,c=this,d={isFixed:!isNaN(parseInt(i,10)),x:t,y:i},u=c.element,h=c.options,p="down",g=e(h.anchor),w=u[0]&&u.hasClass("km-widget");if(!c.visible()){if(h.copyAnchorStyles&&(w&&"font-size"==H[0]&&H.shift(),u.css(n.getComputedStyles(g[0],H))),u.data("animating")||c._trigger(s))return;c._activated=!1,h.modal||(A.unbind(c.downEvent,c._mousedownProxy).bind(c.downEvent,c._mousedownProxy),o.mobileOS.ios||o.mobileOS.android||(c._scrollableParents().unbind(I,c._resizeProxy).bind(I,c._resizeProxy),E.unbind(P,c._resizeProxy).bind(P,c._resizeProxy))),c.wrapper=a=n.wrap(u,h.autosize).css({overflow:v,display:"block",position:m}),o.mobileOS.android&&a.css(z,"translatez(0)"),a.css(b),e(h.appendTo)[0]==document.body&&a.css(f,"-10000px"),r=F(!0,{},h.animation.open),c.flipped=c._position(d),r.effects=n.parseEffects(r.effects,c.flipped),p=r.effects.slideIn?r.effects.slideIn.direction:p,h.anchor!=_&&(l=C+"-"+p,u.addClass(C+"-"+n.directions[p].reverse),g.addClass(l).children(T).addClass(x).addClass(l)),u.data(k,r.effects).kendoStop(!0).kendoAnimate(r)}},position:function(){this.visible()&&this._position()},toggle:function(){var e=this;e[e.visible()?l:s]()},visible:function(){return this.element.is(":"+y)},close:function(t){var i,r,o,a,s=this,c=s.options;if(s.visible()){if(i=s.wrapper[0]?s.wrapper:n.wrap(s.element).hide(),s._closing||s._trigger(l))return;s.element.find(".k-popup").each(function(){var n=e(this),i=n.data("kendoPopup");i&&i.close(t)}),A.unbind(s.downEvent,s._mousedownProxy),s._scrollableParents().unbind(I,s._resizeProxy),E.unbind(P,s._resizeProxy),t?r={hide:!0,effects:{}}:(r=F(!0,{},c.animation.close),o=s.element.data(k),a=r.effects,!a&&!n.size(a)&&o&&n.size(o)&&(r.effects=o,r.reverse=!0),s._closing=!0),s.element.kendoStop(!0),i.css({overflow:v}),s.element.kendoAnimate(r)}},_trigger:function(e){return this.trigger(e,{type:e})},_resize:function(e){var t=this;"resize"===e.type?(clearTimeout(t._resizeTimeout),t._resizeTimeout=setTimeout(function(){t._position(),t._resizeTimeout=null},50)):(!t._hovered||t._activated&&t.element.hasClass("k-list-container"))&&t.close()},_mousedown:function(i){var r=this,o=r.element[0],a=r.options,s=e(a.anchor)[0],l=a.toggleTarget,c=n.eventTarget(i),d=e(c).closest(".k-popup"),u=d.parent().parent(".km-shim").length;d=d[0],(u||!d||d===r.element[0])&&"popover"!==e(i.target).closest("a").data("rel")&&(t(o,c)||t(s,c)||l&&t(e(l)[0],c)||r.close())},_fit:function(e,t,n){var i=0;return e+t>n&&(i=n-(e+t)),0>e&&(i=-e),i},_flip:function(e,t,n,i,r,o,a){var s=0;return a=a||t,o!==r&&o!==u&&r!==u&&(e+a>i&&(s+=-(n+t)),0>e+s&&(s+=n+t)),s},_scrollableParents:function(){return e(this.options.anchor).parentsUntil("body").filter(function(e,t){return n.isScrollable(t)})},_position:function(t){var i,r,s,l,c,d,u,h,p,f,g,v=this,_=v.element,y=v.wrapper,k=v.options,x=e(k.viewport),C=x.offset(),S=e(k.anchor),T=k.origin.toLowerCase().split(" "),D=k.position.toLowerCase().split(" "),A=v.collisions,E=o.zoomLevel(),I=10002,P=!!(x[0]==window&&window.innerWidth&&1.02>=E),M=0,z=document.documentElement,R=P?window.innerWidth:x.width(),H=P?window.innerHeight:x.height();if(P&&z.scrollHeight-z.clientHeight>0&&(R-=n.support.scrollbar()),i=S.parents().filter(y.siblings()),i[0])if(s=Math.max(+i.css("zIndex"),0))I=s+10;else for(r=S.parentsUntil(i),l=r.length;l>M;M++)s=+e(r[M]).css("zIndex"),s&&s>I&&(I=s+10);return y.css("zIndex",I),y.css(t&&t.isFixed?{left:t.x,top:t.y}:v._align(T,D)),c=a(y,b,S[0]===y.offsetParent()[0]),d=a(y),u=S.offsetParent().parent(".k-animation-container,.k-popup,.k-group"),u.length&&(c=a(y,b,!0),d=a(y)),x[0]===window?(d.top-=window.pageYOffset||document.documentElement.scrollTop||0,d.left-=window.pageXOffset||document.documentElement.scrollLeft||0):(d.top-=C.top,d.left-=C.left),v.wrapper.data(w)||y.data(w,F({},c)),h=F({},d),p=F({},c),f=k.adjustSize,"fit"===A[0]&&(p.top+=v._fit(h.top,y.outerHeight()+f.height,H/E)),"fit"===A[1]&&(p.left+=v._fit(h.left,y.outerWidth()+f.width,R/E)),g=F({},p),"flip"===A[0]&&(p.top+=v._flip(h.top,_.outerHeight(),S.outerHeight(),H/E,T[0],D[0],y.outerHeight())),"flip"===A[1]&&(p.left+=v._flip(h.left,_.outerWidth(),S.outerWidth(),R/E,T[1],D[1],y.outerWidth())),_.css(b,m),y.css(p),p.left!=g.left||p.top!=g.top},_align:function(t,n){var i,r=this,o=r.wrapper,s=e(r.options.anchor),l=t[0],c=t[1],d=n[0],h=n[1],f=a(s),m=e(r.options.appendTo),v=o.outerWidth(),_=o.outerHeight(),w=s.outerWidth(),b=s.outerHeight(),y=f.top,k=f.left,x=Math.round;return m[0]!=document.body&&(i=a(m),y-=i.top,k-=i.left),l===g&&(y+=b),l===u&&(y+=x(b/2)),d===g&&(y-=_),d===u&&(y-=x(_/2)),c===p&&(k+=w),c===u&&(k+=x(w/2)),h===p&&(k-=v),h===u&&(k-=x(v/2)),{top:y,left:k}}});i.plugin(B)}(window.kendo.jQuery),function(e,t){var n=window.kendo,i=n.ui.Widget,r=e.proxy,o=e.extend,a=window.setTimeout,s="click",l="show",c="hide",d="k-notification",u=".k-notification-wrap .k-i-close",h="info",p="success",f="warning",g="error",m="top",v="left",_="bottom",w="right",b="up",y=".kendoNotification",k='
      ',x='
      #=typeIcon##=content#Hide
      ',C=i.extend({init:function(t,r){var o=this;i.fn.init.call(o,t,r),r=o.options,r.appendTo&&e(r.appendTo).is(t)||o.element.hide(),o._compileTemplates(r.templates),o._guid="_"+n.guid(),o._isRtl=n.support.isRtl(t),o._compileStacking(r.stacking,r.position.top),n.notify(o)},events:[l,c],options:{name:"Notification",position:{pinned:!0,top:null,left:null,bottom:20,right:20},stacking:"default",hideOnClick:!0,button:!1,allowHideAfter:0,autoHideAfter:5e3,appendTo:null,width:null,height:null,templates:[],animation:{open:{effects:"fade:in",duration:300},close:{effects:"fade:out",duration:600,hide:!0}}},_compileTemplates:function(t){var i=this,r=n.template;i._compiled={},e.each(t,function(t,n){i._compiled[n.type]=r(n.template||e("#"+n.templateId).html())}),i._defaultCompiled=r(x)},_getCompiled:function(e){var t=this,n=t._defaultCompiled;return e?t._compiled[e]||n:n},_compileStacking:function(e,t){var n,i,r=this,o={paddingTop:0,paddingRight:0,paddingBottom:0,paddingLeft:0};switch(e){case"down":n=_+" "+v,i=m+" "+v,delete o.paddingBottom;break;case w:n=m+" "+w,i=m+" "+v,delete o.paddingRight;break;case v:n=m+" "+v,i=m+" "+w,delete o.paddingLeft;break;case b:n=m+" "+v,i=_+" "+v,delete o.paddingTop;break;default:null!==t?(n=_+" "+v,i=m+" "+v,delete o.paddingBottom):(n=m+" "+v,i=_+" "+v,delete o.paddingTop)}r._popupOrigin=n,r._popupPosition=i,r._popupPaddings=o},_attachPopupEvents:function(e,t){function n(e){e.on(s+y,function(){t.close()})}var i,r=e.allowHideAfter,o=!isNaN(r)&&r>0;e.hideOnClick?t.bind("activate",function(){o?a(function(){n(t.element)},r):n(t.element)}):e.button&&(i=t.element.find(u),o?a(function(){n(i)},r):n(i))},_showPopup:function(t,i){var r,s,l=this,c=i.autoHideAfter,d=i.position.left,h=i.position.top;s=e("."+l._guid).last(),r=new n.ui.Popup(t,{anchor:s[0]?s:document.body,origin:l._popupOrigin,position:l._popupPosition,animation:i.animation,modal:!0,collision:"",isRtl:l._isRtl,close:function(){l._triggerHide(this.element)},deactivate:function(e){e.sender.element.off(y),e.sender.element.find(u).off(y),e.sender.destroy()}}),l._attachPopupEvents(i,r),s[0]?r.open():(null===d&&(d=e(window).width()-t.width()-i.position.right),null===h&&(h=e(window).height()-t.height()-i.position.bottom),r.open(d,h)),r.wrapper.addClass(l._guid).css(o({margin:0},l._popupPaddings)),i.position.pinned?(r.wrapper.css("position","fixed"),s[0]&&l._togglePin(r.wrapper,!0)):s[0]||l._togglePin(r.wrapper,!1),c>0&&a(function(){r.close()},c)},_togglePin:function(t,n){var i=e(window),r=n?-1:1;t.css({top:parseInt(t.css(m),10)+r*i.scrollTop(),left:parseInt(t.css(v),10)+r*i.scrollLeft()})},_attachStaticEvents:function(e,t){function n(e){e.on(s+y,r(i._hideStatic,i,t))}var i=this,o=e.allowHideAfter,l=!isNaN(o)&&o>0;e.hideOnClick?l?a(function(){n(t)},o):n(t):e.button&&(l?a(function(){n(t.find(u))},o):n(t.find(u)))},_showStatic:function(e,t){var n=this,i=t.autoHideAfter,r=t.animation,o=t.stacking==b||t.stacking==v?"prependTo":"appendTo";e.addClass(n._guid)[o](t.appendTo).hide().kendoAnimate(r.open||!1),n._attachStaticEvents(t,e),i>0&&a(function(){n._hideStatic(e)},i)},_hideStatic:function(e){e.kendoAnimate(o(this.options.animation.close||!1,{complete:function(){e.off(y).find(u).off(y),e.remove()}})),this._triggerHide(e)},_triggerHide:function(e){this.trigger(c,{element:e}),this.angular("cleanup",function(){return{elements:e}})},show:function(i,r){var a,s,c=this,u=c.options,p=e(k);return r||(r=h),null!==i&&i!==t&&""!==i&&(n.isFunction(i)&&(i=i()),s={typeIcon:r,content:""},a=e.isPlainObject(i)?o(s,i):o(s,{content:i}),p.addClass(d+"-"+r).toggleClass(d+"-button",u.button).attr("data-role","alert").css({width:u.width,height:u.height}).append(c._getCompiled(r)(a)),c.angular("compile",function(){return{elements:p,data:[{dataItem:a}]}}),e(u.appendTo)[0]?c._showStatic(p,u):c._showPopup(p,u),c.trigger(l,{element:p})),c},info:function(e){return this.show(e,h)},success:function(e){return this.show(e,p)},warning:function(e){return this.show(e,f)},error:function(e){return this.show(e,g)},hide:function(){var t=this,n=t.getNotifications();return n.each(t.options.appendTo?function(n,i){t._hideStatic(e(i))}:function(t,n){var i=e(n).data("kendoPopup");i&&i.close()}),t},getNotifications:function(){var t=this,n=e("."+t._guid);return t.options.appendTo?n:n.children("."+d)},setOptions:function(e){var n,r=this;i.fn.setOptions.call(r,e),n=r.options,e.templates!==t&&r._compileTemplates(n.templates),(e.stacking!==t||e.position!==t)&&r._compileStacking(n.stacking,n.position.top)},destroy:function(){i.fn.destroy.call(this),this.getNotifications().off(y).find(u).off(y)}});n.ui.plugin(C)}(window.kendo.jQuery),function(e){function t(e){for(;e.length;)n(e),e=e.parent()}function n(e){var t=e.data(o.ns+"title");t&&(e.attr("title",t),e.removeData(o.ns+"title"))}function i(e){var t=e.attr("title");t&&(e.data(o.ns+"title",t),e.attr("title",""))}function r(e){for(;e.length&&!e.is("body");)i(e),e=e.parent()}var o=window.kendo,a=o.ui.Widget,s=o.ui.Popup,l=o.isFunction,c=e.isPlainObject,d=e.extend,u=e.proxy,h=e(document),p=o.isLocalUrl,f="_tt_active",g="aria-describedby",m="show",v="hide",_="error",w="contentLoad",b="requestStart",y="k-content-frame",k='',x=o.template(""),C=".kendoTooltip",S={bottom:{origin:"bottom center",position:"top center"},top:{origin:"top center",position:"bottom center"},left:{origin:"center left",position:"center right",collision:"fit flip"},right:{origin:"center right",position:"center left",collision:"fit flip"},center:{position:"center center",origin:"center center"}},T={top:"bottom",bottom:"top",left:"right",right:"left",center:"center"},D={bottom:"n",top:"s",left:"e",right:"w",center:"n"},A={horizontal:{offset:"top",size:"outerHeight"},vertical:{offset:"left",size:"outerWidth"}},E=function(e){return e.target.data(o.ns+"title")},I=a.extend({init:function(e,t){var n,i=this;a.fn.init.call(i,e,t),n=i.options.position.match(/left|right/)?"horizontal":"vertical",i.dimensions=A[n],i._documentKeyDownHandler=u(i._documentKeyDown,i),i.element.on(i.options.showOn+C,i.options.filter,u(i._showOn,i)).on("mouseenter"+C,i.options.filter,u(i._mouseenter,i)),this.options.autoHide&&i.element.on("mouseleave"+C,i.options.filter,u(i._mouseleave,i))},options:{name:"Tooltip",filter:"",content:E,showAfter:100,callout:!0,position:"bottom",showOn:"mouseenter",autoHide:!0,width:null,height:null,animation:{open:{effects:"fade:in",duration:0},close:{effects:"fade:out",duration:40,hide:!0}}},events:[m,v,w,_,b],_mouseenter:function(t){r(e(t.currentTarget))},_showOn:function(t){var n=this,i=e(t.currentTarget);n.options.showOn&&n.options.showOn.match(/click|focus/)?n._show(i):(clearTimeout(n.timeout),n.timeout=setTimeout(function(){n._show(i)},n.options.showAfter))},_appendContent:function(e){var t,n=this,i=n.options.content,r=n.content,a=n.options.iframe;c(i)&&i.url?("iframe"in n.options||(a=!p(i.url)),n.trigger(b,{options:i,target:e}),a?(r.hide(),t=r.find("."+y)[0],t?t.src=i.url||t.src:r.html(x({content:i})),r.find("."+y).off("load"+C).on("load"+C,function(){n.trigger(w),r.show()})):(r.empty(),o.ui.progress(r,!0),n._ajaxRequest(i))):i&&l(i)?(i=i({sender:this,target:e}),r.html(i||"")):r.html(i),n.angular("compile",function(){return{elements:r}})},_ajaxRequest:function(e){var t=this;jQuery.ajax(d({type:"GET",dataType:"html",cache:!1,error:function(e,n){o.ui.progress(t.content,!1),t.trigger(_,{status:n,xhr:e})},success:u(function(e){o.ui.progress(t.content,!1),t.content.html(e),t.trigger(w)},t)},e))},_documentKeyDown:function(e){e.keyCode===o.keys.ESC&&this.hide()},refresh:function(){var e=this,t=e.popup;t&&t.options.anchor&&e._appendContent(t.options.anchor)},hide:function(){this.popup&&this.popup.close()},show:function(e){e=e||this.element,r(e),this._show(e)},_show:function(e){var n=this,i=n.target();n.popup||n._initPopup(),i&&i[0]!=e[0]&&(n.popup.close(),n.popup.element.kendoStop(!0,!0)),i&&i[0]==e[0]||(n._appendContent(e),n.popup.options.anchor=e),n.popup.one("deactivate",function(){t(e),e.removeAttr(g),this.element.removeAttr("id").attr("aria-hidden",!0),h.off("keydown"+C,n._documentKeyDownHandler)}),n.popup.open()},_initPopup:function(){var t=this,n=t.options,i=e(o.template(k)({callout:n.callout&&"center"!==n.position,dir:D[n.position],autoHide:n.autoHide}));t.popup=new s(i,d({activate:function(){var e=this.options.anchor,i=e[0].id||t.element[0].id;i&&(e.attr(g,i+f),this.element.attr("id",i+f)),n.callout&&t._positionCallout(),this.element.removeAttr("aria-hidden"),h.on("keydown"+C,t._documentKeyDownHandler),t.trigger(m)},close:function(){t.trigger(v)},copyAnchorStyles:!1,animation:n.animation},S[n.position])),i.css({width:n.width,height:n.height}),t.content=i.find(".k-tooltip-content"),t.arrow=i.find(".k-callout"),n.autoHide?i.on("mouseleave"+C,u(t._mouseleave,t)):i.on("click"+C,".k-tooltip-button",u(t._closeButtonClick,t))},_closeButtonClick:function(e){e.preventDefault(),this.hide()},_mouseleave:function(n){if(this.popup){var i=e(n.currentTarget),r=i.offset(),o=n.pageX,a=n.pageY;if(r.right=r.left+i.outerWidth(),r.bottom=r.top+i.outerHeight(),o>r.left&&r.right>o&&a>r.top&&r.bottom>a)return;this.popup.close()}else t(e(n.currentTarget));clearTimeout(this.timeout)},_positionCallout:function(){var t=this,n=t.options.position,i=t.dimensions,r=i.offset,o=t.popup,a=o.options.anchor,s=e(a).offset(),l=parseInt(t.arrow.css("border-top-width"),10),c=e(o.element).offset(),d=D[o.flipped?T[n]:n],u=s[r]-c[r]+e(a)[i.size]()/2-l;t.arrow.removeClass("k-callout-n k-callout-s k-callout-w k-callout-e").addClass("k-callout-"+d).css(r,u)},target:function(){return this.popup?this.popup.options.anchor:null},destroy:function(){var e=this.popup;e&&(e.element.off(C),e.destroy()),this.element.off(C),h.off("keydown"+C,this._documentKeyDownHandler),a.fn.destroy.call(this)}});o.ui.plugin(I)}(window.kendo.jQuery),function(e,t){function n(e,t){var n,i,r,o=t.length,a=[];for(i=0;e.length>i;i++)for(n=e[i],r=0;o>r;r++)n===t[r]&&a.push({index:i,item:n});return a}function i(t,n){var r,o=!1;return t.filters&&(r=e.grep(t.filters,function(e){return o=i(e,n),e.filters?e.filters.length:e.field!=n}),o||t.filters.length===r.length||(o=!0),t.filters=r),o}var r,o,a=window.kendo,s=a.ui,l=s.Widget,c=a.keys,d=a.support,u=a.htmlEncode,h=a._activeElement,p=a.data.ObservableArray,f="id",g="change",m="k-state-focused",v="k-state-hover",_="k-loading",w="open",b="close",y="select",k="selected",x="requestStart",C="requestEnd",S="width",T=e.extend,D=e.proxy,A=e.isArray,E=d.browser,I=E.msie&&9>E.version,P=/"/g,M={ComboBox:"DropDownList",DropDownList:"ComboBox"},z=a.ui.DataBoundWidget.extend({init:function(t,n){var i,r=this,o=r.ns;l.fn.init.call(r,t,n),t=r.element,n=r.options,r._isSelect=t.is(y),r._isSelect&&r.element[0].length&&(n.dataSource||(n.dataTextField=n.dataTextField||"text",n.dataValueField=n.dataValueField||"value")),r.ul=e('
        ').attr({tabIndex:-1,"aria-hidden":!0}),r.list=e("
        ").append(r.ul).on("mousedown"+o,D(r._listMousedown,r)),i=t.attr(f),i&&(r.list.attr(f,i+"-list"),r.ul.attr(f,i+"_listbox")),r._header(),r._accessors(),r._initValue()},options:{valuePrimitive:!1,headerTemplate:""},setOptions:function(e){l.fn.setOptions.call(this,e),e&&e.enable!==t&&(e.enabled=e.enable)},focus:function(){this._focused.focus()},readonly:function(e){this._editable({readonly:e===t?!0:e,disable:!1})},enable:function(e){this._editable({readonly:!1,disable:!(e=e===t?!0:e)})},_listOptions:function(e){var t=this.options;return e=e||{},e={height:e.height||t.height,dataValueField:e.dataValueField||t.dataValueField,dataTextField:e.dataTextField||t.dataTextField,groupTemplate:e.groupTemplate||t.groupTemplate,fixedGroupTemplate:e.fixedGroupTemplate||t.fixedGroupTemplate,template:e.template||t.template},e.template||(e.template="#:"+a.expr(e.dataTextField,"data")+"#"),e},_initList:function(){var n=this,i=n.options,r=i.virtual,o=!!r,s=i.value,l=D(n._listBound,n),c={autoBind:!1,selectable:!0,dataSource:n.dataSource,click:D(n._click,n),change:D(n._listChange,n),activate:D(n._activateItem,n),deactivate:D(n._deactivateItem,n),dataBinding:function(){n.trigger("dataBinding"),n._angularItems("cleanup")},dataBound:l,listBound:l,selectedItemChange:D(n._listChange,n)};c=e.extend(n._listOptions(),c,"object"==typeof r?r:{}),n.listView=o?new a.ui.VirtualList(n.ul,c):new a.ui.StaticList(n.ul,c),s!==t&&n.listView.value(s).done(function(){var e=i.text;!n.listView.filter()&&n.input&&(-1===n.selectedIndex?((e===t||null===e)&&(e=s),n._accessor(s),n.input.val(e)):-1===n._oldIndex&&(n._oldIndex=n.selectedIndex))})},_listMousedown:function(e){this.filterInput&&this.filterInput[0]===e.target||e.preventDefault()},_filterSource:function(e,t){var n=this,r=n.options,o=n.dataSource,a=T({},o.filter()||{}),s=i(a,r.dataTextField);(e||s)&&n.trigger("filtering",{filter:e})||(e&&(a=a.filters||[],a.push(e)),t?o.read(a):o.filter(a))},_header:function(){var t,n=this,i=n.options.headerTemplate;e.isFunction(i)&&(i=i({})),i&&(n.list.prepend(i),t=n.ul.prev(),n.header=t[0]?t:null,n.header&&n.angular("compile",function(){return{elements:n.header}}))},_initValue:function(){var e=this,t=e.options.value;null!==t?e.element.val(t):(t=e._accessor(),e.options.value=t),e._old=t},_ignoreCase:function(){var e,t=this,n=t.dataSource.reader.model;n&&n.fields&&(e=n.fields[t.options.dataTextField],e&&e.type&&"string"!==e.type&&(t.options.ignoreCase=!1))},_focus:function(e){return this.listView.focus(e)},current:function(e){return this._focus(e)},items:function(){return this.ul[0].children},destroy:function(){var e=this,t=e.ns;l.fn.destroy.call(e),e._unbindDataSource(),e.listView.destroy(),e.list.off(t),e.popup.destroy(),e._form&&e._form.off("reset",e._resetHandler)},dataItem:function(n){var i=this;return n===t?i.listView.selectedDataItems()[0]:("number"!=typeof n&&(n=e(i.items()).index(n)),i.dataSource.flatView()[n])},_activateItem:function(){var e=this.listView.focus();e&&this._focused.add(this.filterInput).attr("aria-activedescendant",e.attr("id"))},_deactivateItem:function(){this._focused.add(this.filterInput).removeAttr("aria-activedescendant")},_accessors:function(){var e=this,t=e.element,n=e.options,i=a.getter,r=t.attr(a.attr("text-field")),o=t.attr(a.attr("value-field"));!n.dataTextField&&r&&(n.dataTextField=r),!n.dataValueField&&o&&(n.dataValueField=o),e._text=i(n.dataTextField),e._value=i(n.dataValueField)},_aria:function(e){var n=this,i=n.options,r=n._focused.add(n.filterInput);i.suggest!==t&&r.attr("aria-autocomplete",i.suggest?"both":"list"),e=e?e+" "+n.ul[0].id:n.ul[0].id,r.attr("aria-owns",e),n.ul.attr("aria-live",i.filter&&"none"!==i.filter?"polite":"off")},_blur:function(){var e=this;e._change(),e.close()},_change:function(){var e,n=this,i=n.selectedIndex,r=n.options.value,o=n.value();n._isSelect&&!n.listView.isBound()&&r&&(o=r),o!==n._old?e=!0:i!==t&&i!==n._oldIndex&&(e=!0),e&&(n._old=o,n._oldIndex=i,n._typing||n.element.trigger(g),n.trigger(g)),n.typing=!1},_data:function(){return this.dataSource.view()},_enable:function(){var e=this,n=e.options,i=e.element.is("[disabled]");n.enable!==t&&(n.enabled=n.enable),!n.enabled||i?e.enable(!1):e.readonly(e.element.is("[readonly]"))},_dataValue:function(e){var n=this._value(e);return n===t&&(n=this._text(e)),n},_offsetHeight:function(){var t=0,n=this.listView.content.prevAll(":visible");return n.each(function(){var n=e(this);t+=n.hasClass("k-list-filter")?n.children().outerHeight():n.outerHeight()}),t},_height:function(e){var t,n,i=this,r=i.list,o=i.options.height,a=i.popup.visible();return e&&(n=r.add(r.parent(".k-animation-container")).show(),o=i.listView.content[0].scrollHeight>o?o:"auto",n.height(o),"auto"!==o&&(t=i._offsetHeight(),t&&(o-=t)),i.listView.content.height(o),a||n.hide()),o},_adjustListWidth:function(){var e,t,n=this.list,i=n[0].style.width,r=this.wrapper;if(n.data(S)||!i)return e=window.getComputedStyle?window.getComputedStyle(r[0],null):0,t=e?parseFloat(e.width):r.outerWidth(),e&&E.msie&&(t+=parseFloat(e.paddingLeft)+parseFloat(e.paddingRight)+parseFloat(e.borderLeftWidth)+parseFloat(e.borderRightWidth)),i="border-box"!==n.css("box-sizing")?t-(n.outerWidth()-n.width()):t,n.css({fontFamily:r.css("font-family"),width:i}).data(S,i),!0},_openHandler:function(e){this._adjustListWidth(),this.trigger(w)?e.preventDefault():(this._focused.attr("aria-expanded",!0),this.ul.attr("aria-hidden",!1))},_closeHandler:function(e){this.trigger(b)?e.preventDefault():(this._focused.attr("aria-expanded",!1),this.ul.attr("aria-hidden",!0))},_focusItem:function(){var e=this.listView,n=e.focus(),i=e.select();i=i[i.length-1],i===t&&this.options.highlightFirst&&!n&&(i=0),i!==t?e.focus(i):e.scrollToIndex(0)},_calculateGroupPadding:function(e){var t=this.ul.children(".k-first:first"),n=this.listView.content.prev(".k-group-header"),i=0;n[0]&&"none"!==n[0].style.display&&("auto"!==e&&(i=a.support.scrollbar()),i+=parseFloat(t.css("border-right-width"),10)+parseFloat(t.children(".k-group").css("padding-right"),10),n.css("padding-right",i))},_firstOpen:function(){var e=this._height(this.dataSource.flatView().length);this._calculateGroupPadding(e)},_popup:function(){var e=this;e.popup=new s.Popup(e.list,T({},e.options.popup,{anchor:e.wrapper,open:D(e._openHandler,e),close:D(e._closeHandler,e),animation:e.options.animation,isRtl:d.isRtl(e.wrapper)})),e.options.virtual||e.popup.one(w,D(e._firstOpen,e))},_makeUnselectable:function(){I&&this.list.find("*").not(".k-textbox").attr("unselectable","on")},_toggleHover:function(t){e(t.currentTarget).toggleClass(v,"mouseenter"===t.type)},_toggle:function(e,n){var i=this,r=d.mobileOS&&(d.touch||d.MSPointers||d.pointers);e=e!==t?e:!i.popup.visible(),n||r||i._focused[0]===h()||(i._prevent=!0,i._focused.focus(),i._prevent=!1),i[e?w:b]()},_triggerCascade:function(){var e=this;e._cascadeTriggered&&e._old===e.value()&&e._oldIndex===e.selectedIndex||(e._cascadeTriggered=!0,e.trigger("cascade",{userTriggered:e._userTriggered}))},_unbindDataSource:function(){var e=this;e.dataSource.unbind(x,e._requestStartHandler).unbind(C,e._requestEndHandler).unbind("error",e._errorHandler)}});T(z,{inArray:function(e,t){var n,i,r=t.children;if(!e||e.parentNode!==t)return-1;for(n=0,i=r.length;i>n;n++)if(e===r[n])return n;return-1}}),a.ui.List=z,s.Select=z.extend({init:function(e,t){z.fn.init.call(this,e,t),this._initial=this.element.val()},setDataSource:function(e){var t,n=this;n.options.dataSource=e,n._dataSource(),n.listView.setDataSource(n.dataSource),n.options.autoBind&&n.dataSource.fetch(),t=n._parentWidget(),t&&t.trigger("cascade")},close:function(){this.popup.close()},select:function(e){var n=this;return e===t?n.selectedIndex:(n._select(e),n._old=n._accessor(),n._oldIndex=n.selectedIndex,t)},search:function(e){var t,n,i,r,o,a;e="string"==typeof e?e:this.text(),t=this,n=e.length,i=t.options,r=i.ignoreCase,o=i.filter,a=i.dataTextField,clearTimeout(t._typingTimeout),(!n||n>=i.minLength)&&(t._state="filter",t.listView.filter(!0),"none"===o?t._filter(e):(t._open=!0,t._filterSource({value:r?e.toLowerCase():e,field:a,operator:o,ignoreCase:r})))},_accessor:function(e,t){return this[this._isSelect?"_accessorSelect":"_accessorInput"](e,t)},_accessorInput:function(e){var n=this.element[0];return e===t?n.value:(null===e&&(e=""),n.value=e,t)},_accessorSelect:function(e,n){var i,r=this.element[0],o=r.selectedIndex;return e===t?(o>-1&&(i=r.options[o]),i&&(e=i.value),e||""):(o>-1&&r.options[o].removeAttribute(k),n===t&&(n=-1),null!==e&&""!==e&&-1==n?this._custom(e):(e?r.value=e:r.selectedIndex=n,r.selectedIndex>-1&&(i=r.options[r.selectedIndex]),i&&i.setAttribute(k,k)),t)},_custom:function(t){var n=this,i=n.element,r=n._customOption;r||(r=e("