diff --git a/MAINTAIN.md b/MAINTAIN.md index a642ca3..9d0bb6b 100644 --- a/MAINTAIN.md +++ b/MAINTAIN.md @@ -1,11 +1,9 @@ ### Periodic Maintenance -1. Once a week or so, we should check for new .NET Core releases and update `sdk-catalog.json` +1. To avoid updates of `sdk-catalog.json` file a web service should be established to grep actual versions from pages below: a. [All](https://dotnet.microsoft.com/download/dotnet-core) b. [.NET Core 3.1.x](https://dotnet.microsoft.com/download/dotnet-core/3.1) - c. [.NET Core 5.0+](https://dotnet.microsoft.com/download/dotnet/5.0) + c. [.NET Core 6.0x](https://dotnet.microsoft.com/en-us/download/dotnet/6.0) -2. We should also check for new Rapberry Pi hardware releases and update `raspberry-catalog.json` - - https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md +`sdk-catalog.json` has to be actual at release date. If the web service isn't available the `sdk-catalog.json` gets taken from debugger. diff --git a/NuGet.Config b/NuGet.Config new file mode 100644 index 0000000..818b995 --- /dev/null +++ b/NuGet.Config @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index de86a0a..0063d0f 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,19 @@ -# Raspberry Debugger +# Raspberry Debugger forked from nforgeio/RaspberryDebugger _A Visual Studio Extension for debugging .NET Core applications remotely on a Raspberry Pi_ --- - -**IMPORTANT:** .NET 5.0 starting with the SDK 5.0.102 works now! - +**IMPORTANT:** Can be ONLY used in Visual Studio 2022! Actually the LTS .NET versions (3.1 + 6.0) and the STS 7.0 (version 3.3) are supported. + +For debugging set the runtime identifier project property to: + +``` + + ... + AnyCPU + linux-arm + +``` +https://docs.microsoft.com/de-de/dotnet/core/rid-catalog --- You can use Visual Studio Code to develop and debug .NET Core applications either directly on your Raspberry or remotely from another computer but until today, there's been no easy way to use regular Visual Studio to develop and debug applications for Raspberry. @@ -13,16 +22,17 @@ The new **Raspberry Debugger** Visual Studio extension allows you to code your a ### Requirements -* Windows 10 -* Visual Studio 2019 Community Edition (or better) -* Raspberry Pi running 32-bit Raspberry Pi OS +* Windows 10/11 +* Visual Studio 2022 Community Edition (or better) +* Raspberry Pi running 32-bit or 64-bit Raspberry Pi OS - grab this source and feel free to test, please * Raspberry user allowed to `sudo` * [Windows Open SSH Client](https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse) (installed automatically when required) ### Features -* Supports Raspberry Pi 3+ devices -* Raspberry Pi OS 32-bit (we haven't tested other operating systems) +* Supports Raspberry Pi 3+ devices and Zero 2 W +* Take a Pi 4 (4/8GB) for development work with large-scale solutions +* Raspberry Pi OS 32/64-bit (raspbian) * Console and ASPNET .NET applications supported * Configures SSH 2048-bit RSA key pair automatically * **F5/Run** debugging @@ -125,6 +135,15 @@ When debugging .NET Core Console projects, you can pass command line arguments a When debugging ASPNET projects, you can pass command line arguments and environment variables to the remote program and you also have the option to start a browser on your workstation and have it display a page from your application. +For Asp.NET debugging set the runtime identifier project property to: + +``` + + ... + linux-arm + +``` + Your web application will be deployed on your Raspberry on all network interfaces, using the port specified by the **App URL**. ![Screenshot](/Doc/Images/GettingStarted/AspNetProperties.png?raw=true) @@ -162,11 +181,11 @@ The **Project/Raspberry Debug Settings** menu persists the settings to the new ` ### Limitations * .NET Core is not supported on Raspberry 1, 2, or Zero cards -* 64-bit Raspberry Pi OS is not supported -* .NET Core SDKs older than 3.1 are not supported +* 64-bit Raspberry Pi OS (Raspbian) is supported now +* Only LTS .NET Core SDKs supported: LTS .NET versions (3.1 + 6.0) and latest STS 7.0 (debugger version 3.3) * **Start Without Debugging** or **Attach to Process...** are not supported (yet) * Raspberry debugging uses the default project debugging profile -* HTTPS is not currently supported for ASPNET debugging +* HTTPS is currently supported for ASPNET debugging (for reverse proxy and for Kestrel) * Program assembly names can't include spaces ### Disclosures diff --git a/RaspberryDebugger.sln b/RaspberryDebugger.sln index 8957f1b..1cf3839 100644 --- a/RaspberryDebugger.sln +++ b/RaspberryDebugger.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.30523.141 +# Visual Studio Version 17 +VisualStudioVersion = 17.2.32505.173 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GitHub", "GitHub", "{177F60A0-B1B9-45D1-9CB1-8F06A6ED2AB5}" ProjectSection(SolutionItems) = preProject @@ -13,8 +13,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "GitHub", "GitHub", "{177F60 EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RaspberryDebugger", "RaspberryDebugger\RaspberryDebugger.csproj", "{80D6A0E0-A145-488C-976D-CE34A16D8533}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SdkCatalogChecker", "SdkCatalogChecker\SdkCatalogChecker.csproj", "{003203EC-1955-47A8-8DEC-7483D1617528}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Doc", "Doc", "{5A14B2C0-0606-433A-AE9C-9E33C7B2BA27}" ProjectSection(SolutionItems) = preProject Doc\DEVELOPER.md = Doc\DEVELOPER.md @@ -40,9 +38,9 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ToolBin", "ToolBin", "{15A5 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Test", "Test", "{21D869D2-B357-485A-89C0-6A18B8886432}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Blinkie", "Blinkie", "{C7EA532F-BE47-4993-9599-66168340E980}" +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Blinky", "Blinky", "{C7EA532F-BE47-4993-9599-66168340E980}" ProjectSection(SolutionItems) = preProject - Test\Blinkie\Blinkie.sln = Test\Blinkie\Blinkie.sln + Test\Blinkie\Blinky.sln = Test\Blinkie\Blinky.sln EndProjectSection EndProject Global @@ -55,10 +53,6 @@ Global {80D6A0E0-A145-488C-976D-CE34A16D8533}.Debug|Any CPU.Build.0 = Debug|Any CPU {80D6A0E0-A145-488C-976D-CE34A16D8533}.Release|Any CPU.ActiveCfg = Release|Any CPU {80D6A0E0-A145-488C-976D-CE34A16D8533}.Release|Any CPU.Build.0 = Release|Any CPU - {003203EC-1955-47A8-8DEC-7483D1617528}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {003203EC-1955-47A8-8DEC-7483D1617528}.Debug|Any CPU.Build.0 = Debug|Any CPU - {003203EC-1955-47A8-8DEC-7483D1617528}.Release|Any CPU.ActiveCfg = Release|Any CPU - {003203EC-1955-47A8-8DEC-7483D1617528}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/RaspberryDebugger.sln.DotSettings b/RaspberryDebugger.sln.DotSettings new file mode 100644 index 0000000..905bafd --- /dev/null +++ b/RaspberryDebugger.sln.DotSettings @@ -0,0 +1,21 @@ + + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True + True \ No newline at end of file diff --git a/RaspberryDebugger/Commands/DebugAttachToProcessCommand.cs b/RaspberryDebugger/Commands/DebugAttachToProcessCommand.cs index 5c42ba1..1f9ba4e 100644 --- a/RaspberryDebugger/Commands/DebugAttachToProcessCommand.cs +++ b/RaspberryDebugger/Commands/DebugAttachToProcessCommand.cs @@ -16,39 +16,24 @@ // limitations under the License. using System; -using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics.Contracts; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; using System.Windows.Forms; - +using EnvDTE80; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; - -using EnvDTE; -using EnvDTE80; - -using Neon.Common; -using Neon.IO; -using Neon.Windows; - -using Newtonsoft.Json.Linq; - +using RaspberryDebugger.Dialogs; using Task = System.Threading.Tasks.Task; -namespace RaspberryDebugger +namespace RaspberryDebugger.Commands { /// /// Handles the Attach to Process... command for Raspberry enabled projects. /// internal sealed class DebugAttachToProcessCommand { - private DTE2 dte; + // ReSharper disable once NotAccessedField.Local + private readonly DTE2 dte; /// /// Command ID. @@ -81,21 +66,23 @@ private DebugAttachToProcessCommand(AsyncPackage package, OleMenuCommandService this.package = package; this.dte = (DTE2)Package.GetGlobalService(typeof(SDTE)); - var menuCommandID = new CommandID(CommandSet, CommandId); - var menuItem = new MenuCommand(this.Execute, menuCommandID); + var menuCommandId = new CommandID(CommandSet, CommandId); + var menuItem = new MenuCommand(this.Execute, menuCommandId); - commandService.AddCommand(menuItem); + commandService?.AddCommand(menuItem); } /// /// Returns the command instance. /// - public static DebugAttachToProcessCommand Instance { get; private set; } + // ReSharper disable once UnusedAutoPropertyAccessor.Local + private static DebugAttachToProcessCommand Instance { get; set; } /// /// Gets the service provider from the owner package. /// - private Microsoft.VisualStudio.Shell.IAsyncServiceProvider ServiceProvider => this.package; + // ReSharper disable once UnusedMember.Local + private IAsyncServiceProvider ServiceProvider => this.package; /// /// Initializes the singleton instance of the command. @@ -104,9 +91,7 @@ private DebugAttachToProcessCommand(AsyncPackage package, OleMenuCommandService public static async Task InitializeAsync(AsyncPackage package) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken); - var commandService = await package.GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService; - DebugAttachToProcessCommand.Instance = new DebugAttachToProcessCommand(package, commandService); } diff --git a/RaspberryDebugger/Commands/DebugStartCommand.cs b/RaspberryDebugger/Commands/DebugStartCommand.cs index 0583658..476c388 100644 --- a/RaspberryDebugger/Commands/DebugStartCommand.cs +++ b/RaspberryDebugger/Commands/DebugStartCommand.cs @@ -16,43 +16,34 @@ // limitations under the License. using System; -using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics.Contracts; -using System.Globalization; -using System.Net.Http; using System.IO; -using System.Net; using System.Linq; using System.Text; -using System.Threading; using System.Threading.Tasks; -using System.Windows.Forms; - -using Microsoft.VisualStudio.Debugger.Interop; -using Microsoft.VisualStudio.Shell; -using Microsoft.VisualStudio.Shell.Interop; - using EnvDTE; using EnvDTE80; - +using Microsoft.VisualStudio.Shell; +using Microsoft.VisualStudio.Shell.Interop; using Neon.Common; using Neon.IO; using Neon.SSH; -using Neon.Windows; - using Newtonsoft.Json.Linq; - +using RaspberryDebugger.Extensions; +using RaspberryDebugger.Models.Connection; +using RaspberryDebugger.Models.Project; +using RaspberryDebugger.Models.VisualStudio; using Task = System.Threading.Tasks.Task; -namespace RaspberryDebugger +namespace RaspberryDebugger.Commands { /// /// Handles the Start Debugging command for Raspberry enabled projects. /// internal sealed class DebugStartCommand { - private DTE2 dte; + private readonly DTE2 dte; /// /// Command ID. @@ -64,15 +55,8 @@ internal sealed class DebugStartCommand /// public static readonly Guid CommandSet = RaspberryDebuggerPackage.CommandSet; - /// - /// VS Package that provides this command, not null. - /// - private readonly AsyncPackage package; - - /// /// Initializes a new instance of the class. /// Adds our command handlers for menu (commands must exist in the command table file) - /// /// Owner package, not null. /// Command service to add command to, not null. private DebugStartCommand(AsyncPackage package, OleMenuCommandService commandService) @@ -82,24 +66,21 @@ private DebugStartCommand(AsyncPackage package, OleMenuCommandService commandSer ThreadHelper.ThrowIfNotOnUIThread(); - this.package = package; this.dte = (DTE2)Package.GetGlobalService(typeof(SDTE)); - var menuCommandID = new CommandID(CommandSet, CommandId); - var menuItem = new MenuCommand(this.Execute, menuCommandID); + var menuCommandId = new CommandID(CommandSet, CommandId); + var menuItem = new MenuCommand(Execute, menuCommandId); - commandService.AddCommand(menuItem); + commandService?.AddCommand(menuItem); } /// /// Returns the command instance. /// - public static DebugStartCommand Instance { get; private set; } - - /// - /// Gets the service provider from the owner package. - /// - private Microsoft.VisualStudio.Shell.IAsyncServiceProvider ServiceProvider => this.package; +#pragma warning disable IDE0052 // Remove unread private members + // ReSharper disable once UnusedAutoPropertyAccessor.Local + private static DebugStartCommand Instance { get; set; } +#pragma warning restore IDE0052 // Remove unread private members /// /// Initializes the singleton instance of the command. @@ -121,9 +102,9 @@ public static async Task InitializeAsync(AsyncPackage package) /// /// Event sender. /// Event args. -#pragma warning disable VSTHRD100 +#pragma warning disable VSTHRD100 // Avoid async void methods private async void Execute(object sender, EventArgs e) -#pragma warning restore VSTHRD100 +#pragma warning restore VSTHRD100 // Avoid async void methods { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); @@ -143,7 +124,7 @@ private async void Execute(object sender, EventArgs e) //----------------------------------------------------------------- - if (!await DebugHelper.PublishProjectWithUIAsync(dte, dte.Solution, project, projectProperties)) + if (!await DebugHelper.PublishProjectWithUiAsync(dte, dte.Solution, project, projectProperties)) { return; } @@ -155,20 +136,12 @@ private async void Execute(object sender, EventArgs e) return; } - // Identify the most recent SDK installed on the workstation that has the same - // major and minor version numbers as the project. We'll ensure that the same - // SDK is installed on the Raspberry (further below). - - var targetSdk = DebugHelper.GetTargetSdk(projectProperties); - - if (targetSdk == null) - { - return; - } - + var projectSettings = PackageHelper.GetProjectSettings(dte.Solution, project); // Establish a Raspberry connection to handle some things before we start the debugger. - - var connection = await DebugHelper.InitializeConnectionAsync(connectionInfo, targetSdk, projectProperties, PackageHelper.GetProjectSettings(dte.Solution, project)); + var connection = await DebugHelper.InitializeConnectionAsync( + connectionInfo, + projectProperties, + projectSettings); if (connection == null) { @@ -178,87 +151,142 @@ private async void Execute(object sender, EventArgs e) using (connection) { // Generate a temporary [launch.json] file and launch the debugger. - - using (var tempFile = await CreateLaunchSettingsAsync(connectionInfo, projectProperties)) + using (var tempFile = await CreateLaunchSettingsAsync(connectionInfo, projectProperties, projectSettings)) { - dte.ExecuteCommand("DebugAdapterHost.Launch", $"/LaunchJson:\"{tempFile.Path}\""); + try + { + dte.ExecuteCommand("DebugAdapterHost.Launch", $"/LaunchJson:\"{tempFile.Path}\""); + } + catch (Exception exception) + { + Console.WriteLine(exception); + } } // Launch the browser for ASPNET apps if requested. Note that we're going to do this // on a background task to poll the Raspberry, waiting for the app to create the create // the LISTENING socket. + if (!projectProperties.IsAspNet || !projectProperties.AspLaunchBrowser) + return; + + var launchReady = false; + var foundWebServer = WebServer.None; - if (projectProperties.IsAspNet && projectProperties.AspLaunchBrowser) - { - var baseUri = $"http://{connectionInfo.Host}:{projectProperties.AspPort}"; - var launchReady = false; + await NeonHelper.WaitForAsync(async () => + { + // The developer must have stopped debugging before the + // ASPNET application was able to begin servicing requests. + if (dte.Mode != vsIDEMode.vsIDEModeDebug) return true; - await NeonHelper.WaitForAsync( - async () => + using (new CursorWait()) { - if (dte.Mode != vsIDEMode.vsIDEModeDebug) - { - // The developer must have stopped debugging before the ASPNET - // application was able to begin servicing requests. - - return true; - } - try { - var appListeningScript = -$@" -if lsof -i -P -n | grep --quiet 'TCP \*:{projectProperties.AspPort} (LISTEN)' ; then - exit 0 -else - exit 1 -fi -"; - var response = connection.SudoCommand(CommandBundle.FromScript(appListeningScript)); - - if (response.ExitCode != 0) - { - return false; - } - - // Wait just a bit longer to give the application a chance to - // perform any additional initialization. - - await Task.Delay(TimeSpan.FromSeconds(1)); + var (found, webServer) = + await SearchForRunningWebServerAsync(projectProperties, projectSettings, connection); + // web server not found + if (!found) return false; + + // take the found web server + foundWebServer = webServer; launchReady = true; + return true; } catch { return false; } - }, - timeout: TimeSpan.FromSeconds(30), - pollInterval: TimeSpan.FromSeconds(0.5)); + } + }, + timeout: TimeSpan.FromSeconds(60), + pollInterval: TimeSpan.FromSeconds(0.5)); - if (launchReady) - { - NeonHelper.OpenBrowser($"{baseUri}{projectProperties.AspRelativeBrowserUri}"); - } - } + if (!launchReady) return; + + OpenWebBrowser(projectProperties, foundWebServer, connection); + } + } + + /// + /// Open web browser for debugging + /// + /// Related project properties + /// Active WebServer: Kestrel or Other (NGiNX, Apache, etc.) + /// LinuxSshProxy connection + private static void OpenWebBrowser( + ProjectProperties projectProperties, + WebServer foundWebServer, + LinuxSshProxy connection) + { + // only '/' present or full relative uri + const int fullRelativeUri = 2; + var baseUri = $"http://{connection.Name}.local"; + + var relativeBrowserUri = projectProperties.AspRelativeBrowserUri.FirstOrDefault() == '/' + ? projectProperties.AspRelativeBrowserUri + : $"/{projectProperties.AspRelativeBrowserUri}"; + + var port = projectProperties.AspPort; + + switch (foundWebServer) + { + // Apache, NGiNX, Kestrel and more... + case WebServer.Other: + case WebServer.Kestrel: + NeonHelper.OpenBrowser(relativeBrowserUri.Length < fullRelativeUri + ? foundWebServer == WebServer.Kestrel + ? $"{baseUri}:{port}" + : $"{baseUri}" + : foundWebServer == WebServer.Kestrel + ? $"{baseUri}:{port}{relativeBrowserUri}" + : $"{baseUri}{relativeBrowserUri}"); + break; + + // no running web server found + case WebServer.None: + default: + break; } } + /// + /// Search for running web server + /// + /// ProjectProperties + /// + /// LinuxSshProxy + /// true if running + private static async Task<(bool, WebServer)> SearchForRunningWebServerAsync(ProjectProperties projectProperties, + ProjectSettings projectSettings, + LinuxSshProxy connection) + { + // Wait just a bit longer to give the application a + // chance to perform any additional initialization. + await Task.Delay(TimeSpan.FromMilliseconds(125)); + + return projectSettings.UseWebServerProxy + ? ProxyWebServer.ListenFor(projectProperties.AspPort, connection, WebServer.Other) + : ProxyWebServer.ListenFor(projectProperties.AspPort, connection, WebServer.Kestrel); + } + /// /// Creates the temporary launch settings file we'll use starting vsdbg on /// the Raspberry for this command. /// /// The connection information. /// The project properties. + /// /// The referencing the created launch file. - private async Task CreateLaunchSettingsAsync(ConnectionInfo connectionInfo, ProjectProperties projectProperties) + private async Task CreateLaunchSettingsAsync(ConnectionInfo connectionInfo, + ProjectProperties projectProperties, ProjectSettings projectSettings) { Covenant.Requires(connectionInfo != null, nameof(connectionInfo)); Covenant.Requires(projectProperties != null, nameof(projectProperties)); var systemRoot = Environment.GetFolderPath(Environment.SpecialFolder.Windows); - var debugFolder = LinuxPath.Combine(PackageHelper.RemoteDebugBinaryRoot(connectionInfo.User), projectProperties.Name); + var debugFolder = LinuxPath.Combine(PackageHelper.RemoteDebugBinaryRoot(connectionInfo?.User), projectProperties?.Name); // NOTE: // @@ -274,31 +302,43 @@ private async Task CreateLaunchSettingsAsync(ConnectionInfo connection // // This means that we need add [program.dll] as the first argument, followed // by the program arguments. + var args = new JArray + { + LinuxPath.Combine(debugFolder, projectProperties?.AssemblyName + ".dll") + }; - var args = new JArray(); - - args.Add(LinuxPath.Combine(debugFolder, projectProperties.AssemblyName + ".dll")); - - foreach (var arg in projectProperties.CommandLineArgs) + if (projectProperties?.CommandLineArgs != null) { - args.Add(arg); + foreach (var arg in projectProperties.CommandLineArgs) + { + args.Add(arg); + } } var environmentVariables = new JObject(); - foreach (var variable in projectProperties.EnvironmentVariables) + if (projectProperties?.EnvironmentVariables != null) { - environmentVariables.Add(variable.Key, variable.Value); + foreach (var variable in projectProperties.EnvironmentVariables) + { + environmentVariables.Add(variable.Key, variable.Value); + } } // For ASPNET apps, set the [ASPNETCORE_URLS] environment variable // to [http://0.0.0.0:PORT] so that the app running on the Raspberry will // be reachable from the development workstation. Note that we don't // support HTTPS at this time. - - if (projectProperties.IsAspNet) + if (projectProperties?.IsAspNet == true) { - environmentVariables["ASPNETCORE_URLS"] = $"http://0.0.0.0:{projectProperties.AspPort}"; + if (projectSettings.UseWebServerProxy) + { + environmentVariables["ASPNETCORE_URLS"] = $"http://127.0.0.1:{projectProperties.AspPort}"; + } + else + { + environmentVariables["ASPNETCORE_URLS"] = $"http://0.0.0.0:{projectProperties.AspPort}"; + } } // Construct the debug launch JSON file. @@ -315,8 +355,8 @@ private async Task CreateLaunchSettingsAsync(ConnectionInfo connection new JObject ( new JProperty("version", "0.2.1"), - new JProperty("adapter", Path.Combine(systemRoot, "Sysnative", "OpenSSH", "ssh.exe")), - new JProperty("adapterArgs", $"-i \"{connectionInfo.PrivateKeyPath}\" -o \"StrictHostKeyChecking no\" {connectionInfo.User}@{connectionInfo.Host} {PackageHelper.RemoteDebuggerPath} --interpreter=vscode {engineLogging}"), + new JProperty("adapter", Path.Combine(systemRoot, "System32", "OpenSSH", "ssh.exe")), + new JProperty("adapterArgs", $"-i \"{connectionInfo?.PrivateKeyPath}\" -o \"StrictHostKeyChecking no\" {connectionInfo?.User}@{connectionInfo?.Host} {PackageHelper.RemoteDebuggerPath} --interpreter=vscode {engineLogging}"), new JProperty("configurations", new JArray ( @@ -338,10 +378,8 @@ private async Task CreateLaunchSettingsAsync(ConnectionInfo connection var tempFile = new TempFile(".launch.json"); - using (var stream = new FileStream(tempFile.Path, FileMode.CreateNew, FileAccess.ReadWrite)) - { - await stream.WriteAsync(Encoding.UTF8.GetBytes(settings.ToString())); - } + using var stream = new FileStream(tempFile.Path, FileMode.CreateNew, FileAccess.ReadWrite); + await stream.WriteAsync(Encoding.UTF8.GetBytes(settings.ToString())); return tempFile; } diff --git a/RaspberryDebugger/Commands/DebugStartWithoutDebuggingCommand.cs b/RaspberryDebugger/Commands/DebugStartWithoutDebuggingCommand.cs index 9d1a46f..35675dc 100644 --- a/RaspberryDebugger/Commands/DebugStartWithoutDebuggingCommand.cs +++ b/RaspberryDebugger/Commands/DebugStartWithoutDebuggingCommand.cs @@ -16,39 +16,24 @@ // limitations under the License. using System; -using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics.Contracts; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; using System.Windows.Forms; - +using EnvDTE80; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; +using RaspberryDebugger.Dialogs; +using System.Threading.Tasks; -using EnvDTE; -using EnvDTE80; - -using Neon.Common; -using Neon.IO; -using Neon.Windows; - -using Newtonsoft.Json.Linq; - -using Task = System.Threading.Tasks.Task; - -namespace RaspberryDebugger +namespace RaspberryDebugger.Commands { /// /// Handles the Start Without Debugging command for Raspberry enabled projects. /// internal sealed class DebugStartWithoutDebuggingCommand { - private DTE2 dte; + // ReSharper disable once MemberCanBePrivate.Global + internal DTE2 Dte; /// /// Command ID. @@ -60,11 +45,6 @@ internal sealed class DebugStartWithoutDebuggingCommand /// public static readonly Guid CommandSet = RaspberryDebuggerPackage.CommandSet; - /// - /// VS Package that provides this command, not null. - /// - private readonly AsyncPackage package; - /// /// Initializes a new instance of the class. /// Adds our command handlers for menu (commands must exist in the command table file) @@ -78,24 +58,19 @@ private DebugStartWithoutDebuggingCommand(AsyncPackage package, OleMenuCommandSe ThreadHelper.ThrowIfNotOnUIThread(); - this.package = package; - this.dte = (DTE2)Package.GetGlobalService(typeof(SDTE)); + this.Dte = (DTE2)Package.GetGlobalService(typeof(SDTE)); - var menuCommandID = new CommandID(CommandSet, CommandId); - var menuItem = new MenuCommand(this.Execute, menuCommandID); + var menuCommandId = new CommandID(CommandSet, CommandId); + var menuItem = new MenuCommand(this.Execute, menuCommandId); - commandService.AddCommand(menuItem); + commandService?.AddCommand(menuItem); } /// /// Returns the command instance. /// - public static DebugStartWithoutDebuggingCommand Instance { get; private set; } - - /// - /// Gets the service provider from the owner package. - /// - private Microsoft.VisualStudio.Shell.IAsyncServiceProvider ServiceProvider => this.package; + // ReSharper disable once UnusedAutoPropertyAccessor.Local + private static DebugStartWithoutDebuggingCommand Instance { get; set; } /// /// Initializes the singleton instance of the command. diff --git a/RaspberryDebugger/Commands/ProxyWebServer.cs b/RaspberryDebugger/Commands/ProxyWebServer.cs new file mode 100644 index 0000000..155c032 --- /dev/null +++ b/RaspberryDebugger/Commands/ProxyWebServer.cs @@ -0,0 +1,96 @@ +using Neon.SSH; +using Polly; +using System; + +namespace RaspberryDebugger.Commands +{ + internal enum WebServer + { + None, + Kestrel, + Other + } + + internal static class ProxyWebServer + { + /// + /// Listen for proxy server or krestel + /// + /// Given ASP port number + /// SSH proxy connection + /// Which web server to listen for + /// true if found and which web server detected + public static (bool, WebServer) ListenFor(int aspPort, LinuxSshProxy connection, WebServer webServer) + { + return webServer == WebServer.Kestrel + ? SearchKrestel(aspPort, connection) + : SearchReverseProxy(aspPort, connection); + } + + /// + /// Search for Krestel + /// + /// Given ASP Port number + /// SSH proxy connection + /// true if found and which one detected + private static (bool, WebServer) SearchKrestel(int aspPort, LinuxSshProxy connection) + { + // search for dotnet kestrel web server + var appKestrelListeningScript = + $@" + if lsof -i -P -n | grep --quiet 'dotnet\|TCP\|:{aspPort}' ; then + exit 0 + else + exit 1 + fi + "; + + var response = ExecSudoCmd(appKestrelListeningScript, connection); + + return response.ExitCode == 0 + ? (true, WebServer.Kestrel) + : (false, WebServer.None); + } + + /// + /// Search for reverse proxy: Apache, NGiNX, etc. + /// + /// Given ASP port number + /// SSH proxy connection + /// true if found and which one detected + private static (bool, WebServer) SearchReverseProxy(int aspPort, LinuxSshProxy connection) + { + // search for web server running as reverse proxy + var appWebServerListeningScript = + $@" + if lsof -i -P -n | grep --quiet 'TCP 127.0.0.1:{aspPort}' ; then + exit 0 + else + exit 1 + fi + "; + + var response = ExecSudoCmd(appWebServerListeningScript, connection); + + return response.ExitCode == 0 + ? (true, WebServer.Other) + : (false, WebServer.None); + } + + /// + /// Execute command with sudo and retries + /// + /// Execute this command + /// Linux ssh + /// Command response + private static CommandResponse ExecSudoCmd(string cmd, LinuxSshProxy connection) + { + var retryPolicy = Policy + .HandleResult(ret => ret.ExitCode != 0) + .WaitAndRetry(3, _ => TimeSpan.FromMilliseconds(200)); + + return retryPolicy.Execute(() => + connection.SudoCommand(CommandBundle.FromScript(cmd))); + } + } +} diff --git a/RaspberryDebugger/Commands/SettingsCommand.cs b/RaspberryDebugger/Commands/SettingsCommand.cs index 66f1146..1578214 100644 --- a/RaspberryDebugger/Commands/SettingsCommand.cs +++ b/RaspberryDebugger/Commands/SettingsCommand.cs @@ -16,30 +16,17 @@ // limitations under the License. using System; -using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics.Contracts; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; using System.Windows.Forms; - +using EnvDTE80; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; - -using EnvDTE; -using EnvDTE80; - using Neon.Common; -using Neon.IO; -using Neon.Windows; - -using Task = System.Threading.Tasks.Task; +using RaspberryDebugger.Dialogs; +using System.Threading.Tasks; -namespace RaspberryDebugger +namespace RaspberryDebugger.Commands { /// /// Handles the Project/Raspberry Debug Settings... command. @@ -49,19 +36,14 @@ internal sealed class SettingsCommand /// /// Command ID. /// - public const int CommandId = RaspberryDebuggerPackage.SettingsCommandId; + private const int CommandId = RaspberryDebuggerPackage.SettingsCommandId; /// /// Package command set ID. /// - public static readonly Guid CommandSet = RaspberryDebuggerPackage.CommandSet; - - /// - /// VS Package that provides this command, not null. - /// - private readonly AsyncPackage package; + private static readonly Guid CommandSet = RaspberryDebuggerPackage.CommandSet; - private DTE2 dte; + private readonly DTE2 dte; /// /// Initializes a new instance of the class. @@ -76,13 +58,13 @@ private SettingsCommand(AsyncPackage package, OleMenuCommandService commandServi ThreadHelper.ThrowIfNotOnUIThread(); - this.package = package; this.dte = (DTE2)Package.GetGlobalService(typeof(SDTE)); - var menuCommandID = new CommandID(CommandSet, CommandId); - var menuItem = new OleMenuCommand(this.Execute, menuCommandID); + var menuCommandId = new CommandID(CommandSet, CommandId); + var menuItem = new OleMenuCommand(this.Execute, menuCommandId); menuItem.BeforeQueryStatus += + // ReSharper disable once UnusedParameter.Local (s, a) => { var command = (OleMenuCommand)s; @@ -90,18 +72,14 @@ private SettingsCommand(AsyncPackage package, OleMenuCommandService commandServi command.Visible = PackageHelper.IsActiveProjectRaspberryCompatible(dte); }; - commandService.AddCommand(menuItem); + commandService?.AddCommand(menuItem); } /// /// Gets the instance of the command. /// - public static SettingsCommand Instance { get; private set; } - - /// - /// Gets the service provider from the owner package. - /// - private Microsoft.VisualStudio.Shell.IAsyncServiceProvider ServiceProvider => this.package; + // ReSharper disable once UnusedAutoPropertyAccessor.Local + private static SettingsCommand Instance { get; set; } /// /// Initializes the singleton instance of the command. @@ -139,7 +117,9 @@ private async void Execute(object sender, EventArgs e) if (project == null) { MessageBoxEx.Show( - "Please select a startup project using the Project/Set as Startup project menu or by right clicking a project in the Solution Explorer and enabling this.", + "Please select a startup project using the Project/Set as " + + "Startup project menu or by right clicking a project in " + + "the Solution Explorer and enabling this.", "Startup Project not found", MessageBoxButtons.OK, MessageBoxIcon.Error); diff --git a/RaspberryDebugger/Connection/Connection.cs b/RaspberryDebugger/Connection/Connection.cs index 7bec822..aef2060 100644 --- a/RaspberryDebugger/Connection/Connection.cs +++ b/RaspberryDebugger/Connection/Connection.cs @@ -14,23 +14,27 @@ // 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. - using System; using System.Collections.Generic; -using System.ComponentModel; using System.Diagnostics.Contracts; using System.IO; using System.Linq; using System.Net; +using System.Runtime.Serialization; using System.Threading.Tasks; - -using Neon.Common; using Neon.IO; using Neon.Net; using Neon.SSH; +using RaspberryDebugger.Extensions; +using RaspberryDebugger.Models.Connection; +using RaspberryDebugger.Models.Project; +using RaspberryDebugger.Models.Sdk; using Renci.SshNet.Common; +using OperatingSystem = RaspberryDebugger.Models.Sdk.OperatingSystem; -namespace RaspberryDebugger +// ReSharper disable StringLiteralTypo + +namespace RaspberryDebugger.Connection { /// /// Implements a SSH connection to the remote Raspberry Pi. @@ -59,25 +63,26 @@ public static async Task ConnectAsync(ConnectionInfo connectionInfo, try { - if (!NetHelper.TryParseIPv4Address(connectionInfo.Host, out var address)) + if (!NetHelper.TryParseIPv4Address(connectionInfo?.Host, out var address)) { - Log($"DNS lookup for: {connectionInfo.Host}"); + Log($"DNS lookup for: {connectionInfo?.Host}"); - address = (await Dns.GetHostAddressesAsync(connectionInfo.Host)).FirstOrDefault(); + var hosts = (await Dns.GetHostAddressesAsync(connectionInfo?.Host)); + address = hosts?.FirstOrDefault(); } if (address == null) { - throw new ConnectionException(connectionInfo.Host, "DNS lookup failed."); + throw new ConnectionException(connectionInfo?.Host, "DNS lookup failed."); } SshCredentials credentials; - if (string.IsNullOrEmpty(connectionInfo.PrivateKeyPath) || usePassword) + if (string.IsNullOrEmpty(connectionInfo?.PrivateKeyPath) || usePassword) { - Log($"[{connectionInfo.Host}]: Auth via username/password"); + Log($"[{connectionInfo?.Host}]: Auth via username/password"); - credentials = SshCredentials.FromUserPassword(connectionInfo.User, connectionInfo.Password); + credentials = SshCredentials.FromUserPassword(connectionInfo?.User, connectionInfo?.Password); } else { @@ -86,7 +91,7 @@ public static async Task ConnectAsync(ConnectionInfo connectionInfo, credentials = SshCredentials.FromPrivateKey(connectionInfo.User, File.ReadAllText(connectionInfo.PrivateKeyPath)); } - var connection = new Connection(connectionInfo.Host, address, connectionInfo, credentials, projectSettings); + var connection = new Connection(connectionInfo?.Host, address, connectionInfo, credentials, projectSettings); connection.Connect(TimeSpan.Zero); await connection.InitializeAsync(); @@ -99,21 +104,21 @@ public static async Task ConnectAsync(ConnectionInfo connectionInfo, e.InnerException == null || e.InnerException.GetType() != typeof(SshAuthenticationException)) { - RaspberryDebugger.Log.Exception(e, $"[{connectionInfo.Host}]"); + RaspberryDebugger.Log.Exception(e, $"[{connectionInfo?.Host}]"); throw; } - if (string.IsNullOrEmpty(connectionInfo.PrivateKeyPath) || + if (string.IsNullOrEmpty(connectionInfo?.PrivateKeyPath) || string.IsNullOrEmpty(connectionInfo.Password)) { - RaspberryDebugger.Log.Exception(e, $"[{connectionInfo.Host}]: The connection must have a password or SSH private key."); + RaspberryDebugger.Log.Exception(e, $"[{connectionInfo?.Host}]: The connection must have a password or SSH private key."); throw; } RaspberryDebugger.Log.Warning($"[{connectionInfo.Host}]: SSH auth failed: Try using the password and reauthorizing the public key"); // SSH private key authentication didn't work. This commonly happens - // after the user has reimaged the Raspberry. It's likely that the + // after the user has re-imaged the Raspberry. It's likely that the // user has setup the same username/password, so we'll try logging in // with those and just configure the current public key to be accepted // on the Raspberry. @@ -130,32 +135,34 @@ public static async Task ConnectAsync(ConnectionInfo connectionInfo, var homeFolder = LinuxPath.Combine("/", "home", connectionInfo.User); var publicKey = File.ReadAllText(connectionInfo.PublicKeyPath).Trim(); var keyScript = -$@" -mkdir -p {homeFolder}/.ssh -touch {homeFolder}/.ssh/authorized_keys + $@" + mkdir -p {homeFolder}/.ssh + touch {homeFolder}/.ssh/authorized_keys + + if ! grep --quiet '{publicKey}' {homeFolder}/.ssh/authorized_keys ; then + echo '{publicKey}' >> {homeFolder}/.ssh/authorized_keys + exit $? + fi -if ! grep --quiet '{publicKey}' {homeFolder}/.ssh/authorized_keys ; then - echo '{publicKey}' >> {homeFolder}/.ssh/authorized_keys - exit $? -fi + exit 0 + "; -exit 0 -"; connection.ThrowOnError(connection.RunCommand(CommandBundle.FromScript(keyScript))); return connection; } catch (Exception e2) { // We've done all we can. - RaspberryDebugger.Log.Exception(e2, $"[{connectionInfo.Host}]"); throw; } } catch (Exception e) { - RaspberryDebugger.Log.Exception(e, $"[{connectionInfo.Host}]"); - throw; + RaspberryDebugger.Log.Exception(e, $"[{connectionInfo?.Host}]"); + Log($"[{connectionInfo?.Host}]: Cannot reach device."); + + return null; } } @@ -178,8 +185,8 @@ exit 0 //--------------------------------------------------------------------- // Instance members - private ConnectionInfo connectionInfo; - private ProjectSettings projectSettings; + private readonly ConnectionInfo connectionInfo; + private readonly ProjectSettings projectSettings; /// /// Constructs a connection using a password. @@ -256,9 +263,9 @@ private CommandResponse ThrowOnError(CommandResponse commandResponse) { Covenant.Requires(commandResponse != null, nameof(commandResponse)); - if (commandResponse.ExitCode != 0) + if (commandResponse?.ExitCode != 0) { - throw new ConnectionException(this, commandResponse.ErrorText); + throw new ConnectionException(this, commandResponse?.ErrorText); } return commandResponse; @@ -277,7 +284,7 @@ await PackageHelper.ExecuteWithProgressAsync( $"Connecting to [{Name}]...", async () => { - // Disabling this because it looks like SUDO passwork prompting is disabled + // Disabling this because it looks like SUDO password prompting is disabled // by default for Raspberry Pi OS. #if DISABLED // This call ensures that SUDO password prompting is disabled and the @@ -287,7 +294,6 @@ await PackageHelper.ExecuteWithProgressAsync( #endif // We need to ensure that [unzip] is installed so that [LinuxSshProxy] command // bundles will work. - Log($"[{Name}]: Checking for: [unzip]"); var response = SudoCommand("which unzip"); @@ -301,105 +307,95 @@ await PackageHelper.ExecuteWithProgressAsync( } // We're going to execute a script the gathers everything in a single operation for speed. - Log($"[{Name}]: Retrieving status"); var statusScript = -$@" -# This script will return the status information via STDOUT line-by-line -# in this order: -# -# Chip Architecture -# PATH environment variable -# Unzip Installed (""unzip"" or ""unzip-missing"") -# Debugger Installed (""debugger-installed"" or ""debugger-missing"") -# List of installed SDKs names (e.g. 3.1.108) separated by commas -# Raspberry Model like: Raspberry Pi 4 Model B Rev 1.2 -# Raspberry Revision like: c03112 -# -# This script also ensures that the [/lib/dotnet] directory exists, that -# it has reasonable permissions, and that the folder exists on the system -# PATH and that DOTNET_ROOT points to the folder. - -# Set the SDK and debugger installation paths. - -DOTNET_ROOT={PackageHelper.RemoteDotnetFolder} -DEBUGFOLDER={PackageHelper.RemoteDebuggerFolder} - -# Get the chip architecture - -uname -m - -# Get the current PATH - -echo $PATH - -# Detect whether [unzip] is installed. - -if which unzip &> /dev/nul ; then - echo 'unzip' -else - echo 'unzip-missing' -fi - -# Detect whether the [vsdbg] debugger is installed. - -if [ -d $DEBUGFOLDER ] ; then - echo 'debugger-installed' -else - echo 'debugger-missing' -fi - -# List the SDK folders. These folder names are the same as the -# corresponding SDK name. We'll list the files on one line -# with the SDK names separated by commas. We'll return a blank -# line if the SDK directory doesn't exist. - -if [ -d $DOTNET_ROOT/sdk ] ; then - ls -m $DOTNET_ROOT/sdk -else - echo '' -fi - -# Output the Raspberry board model. - -cat /proc/cpuinfo | grep '^Model\s' | grep -o 'Raspberry.*$' - -# Output the Raspberry board revision. - -cat /proc/cpuinfo | grep 'Revision\s' | grep -o '[0-9a-fA-F]*$' - -# Ensure that the [/lib/dotnet] folder exists, that it's on the -# PATH and that DOTNET_ROOT are defined. - -mkdir -p /lib/dotnet -chown root:root /lib/dotnet -chmod 755 /lib/dotnet - -# Set these for the current session: - -export DOTNET_ROOT={PackageHelper.RemoteDotnetFolder} -export PATH=$PATH:$DOTNET_ROOT - -# and for future sessions too: + $@" + # This script will return the status information via STDOUT line-by-line + # in this order: + # + # Chip Architecture + # PATH environment variable + # Unzip Installed (""unzip"" or ""unzip-missing"") + # Debugger Installed (""debugger-installed"" or ""debugger-missing"") + # List of installed SDKs names (e.g. 3.1.108) separated by commas + # Raspberry Model like: Raspberry Pi 4 Model B Rev 1.2 + # Raspberry Revision like: c03112 + # + # This script also ensures that the [/lib/dotnet] directory exists, that + # it has reasonable permissions, and that the folder exists on the system + # PATH and that DOTNET_ROOT points to the folder. + + # Set the SDK and debugger installation paths. + + DOTNET_ROOT={PackageHelper.RemoteDotnetFolder} + DEBUGFOLDER={PackageHelper.RemoteDebuggerFolder} + + # Get the chip architecture + uname -m + + # Get the current PATH + echo $PATH + + # Detect whether [unzip] is installed. + if which unzip &> /dev/nul ; then + echo 'unzip' + else + echo 'unzip-missing' + fi -if ! grep --quiet DOTNET_ROOT /etc/profile ; then + # Detect whether the [vsdbg] debugger is installed. + if [ -d $DEBUGFOLDER ] ; then + echo 'debugger-installed' + else + echo 'debugger-missing' + fi + + # List the SDK folders. These folder names are the same as the + # corresponding SDK name. We'll list the files on one line + # with the SDK names separated by commas. We'll return a blank + # line if the SDK directory doesn't exist. + if [ -d $DOTNET_ROOT/sdk ] ; then + ls -m $DOTNET_ROOT/sdk + else + echo '' + fi + + # Output the Raspberry board model. + cat /proc/cpuinfo | grep '^Model\s' | grep -o 'Raspberry.*$' + + # Output the Raspberry board revision. + cat /proc/cpuinfo | grep 'Revision\s' | grep -o '[0-9a-fA-F]*$' + + # Ensure that the [/lib/dotnet] folder exists, that it's on the + # PATH and that DOTNET_ROOT are defined. + mkdir -p /lib/dotnet + chown root:root /lib/dotnet + chmod 755 /lib/dotnet + + # Set these for the current session: + export DOTNET_ROOT={PackageHelper.RemoteDotnetFolder} + export PATH=$PATH:$DOTNET_ROOT + + # and for future sessions too: + if ! grep --quiet DOTNET_ROOT /etc/profile ; then + echo """" >> /etc/profile + echo ""#------------------------------"" >> /etc/profile + echo ""# Raspberry Debugger:"" >> /etc/profile + echo ""export DOTNET_ROOT=$DOTNET_ROOT"" >> /etc/profile + echo ""export PATH=$PATH"" >> /etc/profile + echo ""#------------------------------"" >> /etc/profile + fi + "; - echo """" >> /etc/profile - echo ""#------------------------------"" >> /etc/profile - echo ""# Raspberry Debugger:"" >> /etc/profile - echo ""export DOTNET_ROOT=$DOTNET_ROOT"" >> /etc/profile - echo ""export PATH=$PATH"" >> /etc/profile - echo ""#------------------------------"" >> /etc/profile -fi -"; Log($"[{Name}]: Fetching status"); response = ThrowOnError(SudoCommand(CommandBundle.FromScript(statusScript))); + // ReSharper disable once ConvertToUsingDeclaration using (var reader = new StringReader(response.OutputText)) { - var architecture = await reader.ReadLineAsync(); + var processor = await reader.ReadLineAsync(); var path = await reader.ReadLineAsync(); var hasUnzip = await reader.ReadLineAsync() == "unzip"; var hasDebugger = await reader.ReadLineAsync() == "debugger-installed"; @@ -409,54 +405,66 @@ chmod 755 /lib/dotnet revision = revision.Trim(); // Remove any whitespace at the end. - Log($"[{Name}]: architecture: {architecture}"); - Log($"[{Name}]: path: {path}"); - Log($"[{Name}]: unzip: {hasUnzip}"); - Log($"[{Name}]: debugger: {hasDebugger}"); - Log($"[{Name}]: sdks: {sdkLine}"); - Log($"[{Name}]: model: {model}"); - Log($"[{Name}]: revision: {revision}"); + Log($"[{Name}]: processor: {processor}"); + Log($"[{Name}]: path: {path}"); + Log($"[{Name}]: unzip: {hasUnzip}"); + Log($"[{Name}]: debugger: {hasDebugger}"); + Log($"[{Name}]: sdks: {sdkLine}"); + Log($"[{Name}]: model: {model}"); + Log($"[{Name}]: revision: {revision}"); - // Convert the comma separated SDK names into a [PiSdk] list. + var osBitness = SdkArchitecture.Unknown; - var sdks = new List(); + if (OperatingSystem.Bitness32.Any(bitness => processor.Contains(bitness))) + { + osBitness = SdkArchitecture.Arm32; + } - foreach (var sdkName in sdkLine.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(sdk => sdk.Trim())) + if (OperatingSystem.Bitness64.Any(bitness => processor.Contains(bitness))) { - // $todo(jefflill): We're only supporting 32-bit SDKs at this time. + osBitness = SdkArchitecture.Arm64; + } - var sdkCatalogItem = PackageHelper.SdkCatalog.Items.SingleOrDefault(item => item.Name == sdkName && item.Architecture == SdkArchitecture.ARM32); + // Convert the comma separated SDK names into a [PiSdk] list. + var sdks = new List(); + + foreach (var sdkName in sdkLine + .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) + .Select(sdk => sdk.Trim())) + { + var sdkCatalogItem = PackageHelper.SdkCatalog.Items + .SingleOrDefault(item => item.Link.Contains(sdkName) && item.Architecture == osBitness); if (sdkCatalogItem != null) { - sdks.Add(new Sdk(sdkName, sdkCatalogItem.Version)); + sdks.Add(new Sdk(sdkName, osBitness)); } else { - LogWarning($".NET SDK [{sdkName}] is present on [{Name}] but is not known to the RaspberryDebugger extension. Consider updating the extension."); + LogWarning($".NET SDK [{sdkName}] is present on [{Name}] but is not known to the RaspberryDebugger extension. Consider updating the extension."); } } PiStatus = new Status( - architecture: architecture, + processor: processor, path: path, hasUnzip: hasUnzip, hasDebugger: hasDebugger, installedSdks: sdks, model: model, - revision: revision + revision: revision, + architecture: osBitness ); } }); // Create and configure an SSH key for this connection if one doesn't already exist. - if (string.IsNullOrEmpty(connectionInfo.PrivateKeyPath) || !File.Exists(connectionInfo.PrivateKeyPath)) { await PackageHelper.ExecuteWithProgressAsync("Creating SSH keys...", async () => { - // Create a 2048-bit private key with no passphrase on the Raspberry + // Create a 2048-bit private key with no pass-phrase on the Raspberry // and then download it to our keys folder. The key file name will // be the host name of the Raspberry. @@ -472,26 +480,24 @@ await PackageHelper.ExecuteWithProgressAsync("Creating SSH keys...", try { var createKeyScript = -$@" -# Create the key pair - -if ! ssh-keygen -t rsa -b 2048 -P '' -C '{workstationUser}@{workstationName}' -f {tempPrivateKeyPath} -m pem ; then - exit 1 -fi + $@" + # Create the key pair + if ! ssh-keygen -t rsa -b 2048 -P '' -C '{workstationUser}@{workstationName}' -f {tempPrivateKeyPath} -m pem ; then + exit 1 + fi -# Append the public key to the user's [authorized_keys] file to enable it. + # Append the public key to the user's [authorized_keys] file to enable it. + mkdir -p {homeFolder}/.ssh + touch {homeFolder}/.ssh/authorized_keys + cat {tempPublicKeyPath} >> {homeFolder}/.ssh/authorized_keys -mkdir -p {homeFolder}/.ssh -touch {homeFolder}/.ssh/authorized_keys -cat {tempPublicKeyPath} >> {homeFolder}/.ssh/authorized_keys + exit 0 + "; -exit 0 -"; ThrowOnError(RunCommand(CommandBundle.FromScript(createKeyScript))); // Download the public and private keys, persist them to the workstation // and then update the connection info. - var connections = PackageHelper.ReadConnections(); var existingConnectionInfo = connections.SingleOrDefault(c => c.Name == connectionInfo.Name); var publicKeyPath = Path.Combine(PackageHelper.KeysFolder, $"{connectionInfo.Name}.pub"); @@ -514,12 +520,12 @@ exit 0 finally { // Delete the temporary key files on the Raspberry. - var removeKeyScript = -$@" -rm -f {tempPrivateKeyPath} -rm -f {tempPublicKeyPath} -"; + $@" + rm -f {tempPrivateKeyPath} + rm -f {tempPublicKeyPath} + "; + ThrowOnError(SudoCommand(CommandBundle.FromScript(removeKeyScript))); } @@ -529,120 +535,147 @@ exit 0 } /// - /// Installs the specified .NET Core SDK on the Raspberry if it's not already installed. + /// Download and install actual (latest) SDK /// - /// The SDK version. - /// true on success. - public async Task InstallSdkAsync(string sdkVersion) + /// true if successful + public async Task SetupSdkAsync() { - Covenant.Requires(!string.IsNullOrEmpty(sdkVersion), nameof(sdkVersion)); - - // $todo(jefflill): - // - // Note that we're going to install that standalone SDK for the SDK - // version rather than the SDK that shipped with Visual Studio. I'm - // assuming that the Visual Studio SDKs might have extra stuff we don't - // need and it's also possible that the Visual Studio SDK for the SDK - // version may not have shipped yet. - // - // We may want to re-evaluate this in the future. - - if (PiStatus.InstalledSdks.Any(sdk => sdk.Version == sdkVersion)) - { - return await Task.FromResult(true); // Already installed - } - - LogInfo($".NET Core SDK [v{sdkVersion}] is not installed."); + if (IsSdkPresent()) return true; - // Locate the standalone SDK for the request .NET version. + var targetSdk = ReadActualSdkCatalogItem(); - var targetSdk = PackageHelper.SdkGoodCatalog.Items.SingleOrDefault(item => item.IsStandalone && item.Version == sdkVersion && item.Architecture == SdkArchitecture.ARM32); + return await DownloadSdkAsync(targetSdk) && + await InstallSdkAsync(targetSdk); + } + /// + /// Downloads the .NET Core SDK on the Raspberry. + /// The Raspberry architecture is driving the installation - the newest .NET Core version is taken + /// + /// true on success. + private async Task DownloadSdkAsync(SdkCatalogItem targetSdk) + { if (targetSdk == null) { - // Fall back to the Visual Studio SDK, if there is one. + LogError("RasberryDebug is unaware of .NET Core SDK."); + LogError("Try updating the RasberryDebug extension or report this issue at:"); + LogError("https://github.com/nforgeio/RaspberryDebugger/issues"); - targetSdk = PackageHelper.SdkGoodCatalog.Items.SingleOrDefault(item => item.Version == sdkVersion); - LogInfo($"Cannot find standalone SDK for [{sdkVersion}] for falling back to [{targetSdk.Name}], version [v{targetSdk.Version}]."); + return await Task.FromResult(false); } - - if (targetSdk == null) + else { - LogError($"RasberryDebug is unaware of .NET Core SDK [v{sdkVersion}]."); - LogError($"Try updating the RasberryDebug extension or report this issue at:"); - LogError($"https://github.com/nforgeio/RaspberryDebugger/issues"); - - return await Task.FromResult(false); + LogInfo($".NET Core SDK [v{targetSdk.Release}] is not installed."); } // Install the SDK. + LogInfo($"Downlaoding SDK v{targetSdk.Release}"); + + var downloadSdkInfo = + $"Download SDK for .NET v{targetSdk.Release} " + + $"({targetSdk.Architecture.GetAttributeOfType().Value}) on Raspberry..."; - LogInfo($"Installing SDK v{targetSdk.Version}"); - - return await PackageHelper.ExecuteWithProgressAsync($"Download and install SDK for .NET v{targetSdk.Version} on Raspberry...", + return await PackageHelper.ExecuteWithProgressAsync(downloadSdkInfo, async () => { - var installScript = -$@" -export DOTNET_ROOT={PackageHelper.RemoteDotnetFolder} - -# Ensure that the packages required by .NET Core are installed: -# -# https://docs.microsoft.com/en-us/dotnet/core/install/linux-debian#dependencies - -if ! apt-get update ; then - exit 1 -fi - -if ! apt-get install -yq libc6 libgcc1 libgssapi-krb5-2 libicu-dev libssl1.1 libstdc++6 zlib1g libgdiplus ; then - exit 1 -fi - -# Remove any existing SDK download. This might be present if a -# previous installation attempt failed. - -if ! rm -f /tmp/dotnet-sdk.tar.gz ; then - exit 1 -fi + var downloadScript = + $@" + # Ensure that the packages required by .NET Core are installed: + # https://docs.microsoft.com/en-us/dotnet/core/install/linux-debian#dependencies + if ! apt-get update ; then + exit 1 + fi + + if ! apt-get install -yq libc6 libgcc1 libgssapi-krb5-2 libicu-dev libssl1.1 libstdc++6 zlib1g libgdiplus ; then + exit 1 + fi + + # Remove any existing SDK download. This might be + # present if a previous installation attempt failed. + if ! rm -f /tmp/dotnet-sdk.tar.gz ; then + exit 1 + fi + + # Download the SDK installation file to a temporary file. + if ! wget --quiet -O /tmp/dotnet-sdk.tar.gz {targetSdk.Link} ; then + exit 1 + fi + + exit 0 + "; -# Download the SDK installation file to a temporary file. - -if ! wget --quiet -O /tmp/dotnet-sdk.tar.gz {targetSdk.Link} ; then - exit 1 -fi + try + { + var response = SudoCommand(CommandBundle.FromScript(downloadScript)); -# Verify the SHA512. + if (response.ExitCode == 0) + { + return await Task.FromResult(true); + } + else + { + LogError(response.AllText); + return await Task.FromResult(false); + } + } + catch (Exception e) + { + LogException(e); + return await Task.FromResult(false); + } + }); + } -orgDir=$cwd -cd /tmp + /// + /// Installs the .NET Core SDK on the Raspberry if it's not already installed. + /// The Raspberry architecture is driving the installation - the newest .NET Core version is taken + /// + /// true on success. + private async Task InstallSdkAsync(SdkCatalogItem targetSdk) + { + // Install the SDK. + LogInfo($"Installing SDK v{targetSdk.Release}"); + + var installSdkInfo = + $"Install SDK for .NET v{targetSdk.Release} " + + $"({targetSdk.Architecture.GetAttributeOfType().Value}) on Raspberry..."; -if ! echo '{targetSdk.SHA512} dotnet-sdk.tar.gz' | sha512sum --check - ; then - cd $orgDir - exit 1 -fi + return await PackageHelper.ExecuteWithProgressAsync(installSdkInfo, + async () => + { + var installScript = + $@" + export DOTNET_ROOT={PackageHelper.RemoteDotnetFolder} -cd $orgDir + # Verify the SHA512. + orgDir=$cwd + cd /tmp -# Make sure the installation directory exists. + if ! echo '{targetSdk.Sha512} dotnet-sdk.tar.gz' | sha512sum --check - ; then + cd $orgDir + exit 1 + fi -if ! mkdir -p $DOTNET_ROOT ; then - exit 1 -fi + cd $orgDir -# Unpack the SDK to the installation directory. + # Make sure the installation directory exists. + if ! mkdir -p $DOTNET_ROOT ; then + exit 1 + fi -if ! tar -zxf /tmp/dotnet-sdk.tar.gz -C $DOTNET_ROOT --no-same-owner ; then - exit 1 -fi + # Unpack the SDK to the installation directory. + if ! tar -zxf /tmp/dotnet-sdk.tar.gz -C $DOTNET_ROOT --no-same-owner ; then + exit 1 + fi -# Remove the temporary installation file. + # Remove the temporary installation file. + if ! rm /tmp/dotnet-sdk.tar.gz ; then + exit 1 + fi -if ! rm /tmp/dotnet-sdk.tar.gz ; then - exit 1 -fi + exit 0 + "; -exit 0 -"; try { var response = SudoCommand(CommandBundle.FromScript(installScript)); @@ -650,8 +683,7 @@ exit 0 if (response.ExitCode == 0) { // Add the newly installed SDK to the list of installed SDKs. - - PiStatus.InstalledSdks.Add(new Sdk(targetSdk.Name, targetSdk.Version)); + PiStatus.InstalledSdks.Add(new Sdk(targetSdk.Name, targetSdk.Architecture)); return await Task.FromResult(true); } else @@ -668,11 +700,44 @@ exit 0 }); } + /// + /// Is any .NET Core SDK installed on the Raspberry Pi. + /// The Raspberry architecture is driving the installation - the newest .NET Core version is taken + /// + /// true on success. + private bool IsSdkPresent() + { + var sdkOnPi = PiStatus.InstalledSdks + .OrderByDescending(name => name.Name) + .FirstOrDefault(); + + var sdkOnPiVersion = sdkOnPi?.Name ?? string.Empty; + var sdkOnPiArchitecture = sdkOnPi?.Architecture ?? PiStatus.Architecture; + + return PiStatus.InstalledSdks.Any(sdk => sdk.Name == sdkOnPiVersion && + sdk.Architecture == sdkOnPiArchitecture); + } + + /// + /// Read actual (latest) SDK from catalog + /// + /// Latest target SDK + private SdkCatalogItem ReadActualSdkCatalogItem() + { + // Locate the standalone SDK for the request .NET version. + // Figure out the latest SDK version - Microsoft versioning: the highest number + var targetSdk = PackageHelper.SdkCatalog.Items + .OrderByDescending(item => item.Name) + .FirstOrDefault(item => item.Architecture == PiStatus.Architecture); + + return targetSdk; + } + /// /// Installs the vsdbg debugger on the Raspberry if it's not already installed. /// /// true on success. - public async Task InstallDebuggerAsync() + public async Task SetupDebuggerAsync() { if (PiStatus.HasDebugger) { @@ -681,17 +746,18 @@ public async Task InstallDebuggerAsync() LogInfo($"Installing VSDBG to: [{PackageHelper.RemoteDebuggerFolder}]"); - return await PackageHelper.ExecuteWithProgressAsync($"Installing [vsdbg] debugger...", + return await PackageHelper.ExecuteWithProgressAsync("Installing [vsdbg] debugger...", async () => { var installScript = -$@" -if ! curl -sSL https://aka.ms/getvsdbgsh | /bin/sh /dev/stdin -v latest -l {PackageHelper.RemoteDebuggerFolder} ; then - exit 1 -fi + $@" + if ! curl -sSL https://aka.ms/getvsdbgsh | /bin/sh /dev/stdin -v latest -l {PackageHelper.RemoteDebuggerFolder} ; then + exit 1 + fi + + exit 0 + "; -exit 0 -"; try { var response = SudoCommand(CommandBundle.FromScript(installScript)); @@ -722,15 +788,15 @@ exit 0 /// any existing files. /// /// The program name - /// The addembly name. + /// The assembly name. /// Path to the workstation folder holding the program files. /// true on success. public async Task UploadProgramAsync(string programName, string assemblyName, string publishedBinaryFolder) { Covenant.Requires(!string.IsNullOrEmpty(programName), nameof(programName)); - Covenant.Requires(!programName.Contains(' '), nameof(programName)); + Covenant.Requires(!(programName ?? string.Empty).Contains(' '), nameof(programName)); Covenant.Requires(!string.IsNullOrEmpty(assemblyName), nameof(assemblyName)); - Covenant.Requires(!assemblyName.Contains(' '), nameof(assemblyName)); + Covenant.Requires(!(assemblyName ?? string.Empty).Contains(' '), nameof(assemblyName)); Covenant.Requires(!string.IsNullOrEmpty(publishedBinaryFolder), nameof(publishedBinaryFolder)); Covenant.Requires(Directory.Exists(publishedBinaryFolder), nameof(publishedBinaryFolder)); @@ -743,47 +809,41 @@ public async Task UploadProgramAsync(string programName, string assemblyNa if (!string.IsNullOrEmpty(projectSettings.TargetGroup)) { groupScript = -$@" -# Add the program assembly to the user specified target group (if any). This -# defaults to [gpio] so users will be able to access the GPIO pins. - -if ! chgrp {projectSettings.TargetGroup} {debugFolder}/{assemblyName} ; then - exit 1 -fi -"; + $@" + # Add the program assembly to the user specified target group (if any). + # This defaults to [gpio] so users will be able to access the GPIO pins. + if ! chgrp {projectSettings.TargetGroup} {debugFolder}/{assemblyName} ; then + exit 1 + fi + "; } var uploadScript = -$@" - -# Ensure that the debug folder exists. + $@" + # Ensure that the debug folder exists. + if ! mkdir -p {debugFolder} ; then + exit 1 + fi + + # Clear all existing program files. + if ! rm -rf {debugFolder}/* ; then + exit 1 + fi + + # Unzip the binary and other files to the debug folder. + if ! unzip program.zip -d {debugFolder} ; then + exit 1 + fi + + # The program assembly needs execute permissions. + if ! chmod 770 {debugFolder}/{assemblyName} ; then + exit 1 + fi + {groupScript} + exit 0 + "; -if ! mkdir -p {debugFolder} ; then - exit 1 -fi - -# Clear all existing program files. - -if ! rm -rf {debugFolder}/* ; then - exit 1 -fi - -# Unzip the binary and other files to the debug folder. - -if ! unzip program.zip -d {debugFolder} ; then - exit 1 -fi - -# The program assembly needs execute permissions. - -if ! chmod 770 {debugFolder}/{assemblyName} ; then - exit 1 -fi -{groupScript} -exit 0 -"; // I'm not going to do a progress dialog because this should be fast. - try { LogInfo($"Uploading program to: [{debugFolder}]"); @@ -796,7 +856,7 @@ exit 0 if (response.ExitCode == 0) { - LogInfo($"Program uploaded"); + LogInfo("Program uploaded"); return await Task.FromResult(true); } else diff --git a/RaspberryDebugger/Connection/ConnectionException.cs b/RaspberryDebugger/Connection/ConnectionException.cs index a2cf469..1d8715a 100644 --- a/RaspberryDebugger/Connection/ConnectionException.cs +++ b/RaspberryDebugger/Connection/ConnectionException.cs @@ -14,21 +14,10 @@ // 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. - using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics.Contracts; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Sockets; - -using Neon.Common; -using Neon.Net; using Neon.SSH; -namespace RaspberryDebugger +namespace RaspberryDebugger.Connection { /// /// Used to report connection issues. @@ -44,10 +33,9 @@ internal class ConnectionException : Exception /// The offending connection. /// The error message. /// The exception message. - private static string GetMessage(Connection connection, string error) + private static string GetMessage(LinuxSshProxy connection, string error) { var name = connection?.Name ?? "????"; - error = error ?? "unspecified error"; return $"[{name}]: {error}"; diff --git a/RaspberryDebugger/Connection/Sdk.cs b/RaspberryDebugger/Connection/Sdk.cs index a4d8a4f..fd2aba5 100644 --- a/RaspberryDebugger/Connection/Sdk.cs +++ b/RaspberryDebugger/Connection/Sdk.cs @@ -14,22 +14,11 @@ // 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. - using System; -using System.Collections.Generic; -using System.ComponentModel; using System.Diagnostics.Contracts; -using System.IO; -using System.Linq; -using System.Net; - -using Neon.Common; -using Neon.Net; -using Neon.SSH; - -using Newtonsoft.Json; +using RaspberryDebugger.Models.Sdk; -namespace RaspberryDebugger +namespace RaspberryDebugger.Connection { /// /// Holds information about a .NET Core SDK installed on a Raspberry Pi. @@ -40,23 +29,23 @@ internal class Sdk /// Constructor. /// /// The SDK name. - /// The SDK version. - public Sdk(string name, string version) + /// The SDK bitness architecture. + public Sdk(string name, SdkArchitecture architecture = SdkArchitecture.Arm32) { Covenant.Requires(!string.IsNullOrEmpty(name), nameof(name)); this.Name = name; - this.Version = version; + this.Architecture = architecture; } /// /// Returns the name of the SDK (like 3.1.402). /// - public string Name { get; private set; } + public string Name { get; } /// - /// Returns thge version of the SDK (like 3.1.8). + /// The raspberry pi architecture /// - public string Version { get; private set; } + public SdkArchitecture Architecture { get; } } } diff --git a/RaspberryDebugger/Connection/Status.cs b/RaspberryDebugger/Connection/Status.cs index 126a0d3..4e8e834 100644 --- a/RaspberryDebugger/Connection/Status.cs +++ b/RaspberryDebugger/Connection/Status.cs @@ -14,21 +14,14 @@ // 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. - +// ReSharper disable UnusedAutoPropertyAccessor.Local using System; using System.Collections.Generic; -using System.ComponentModel; using System.Diagnostics.Contracts; -using System.IO; using System.Linq; -using System.Net; -using Neon.Common; -using Neon.Net; -using Neon.SSH; - -using Newtonsoft.Json; +using RaspberryDebugger.Models.Sdk; -namespace RaspberryDebugger +namespace RaspberryDebugger.Connection { /// /// Describes the current status of a remote Raspberry Pi. @@ -38,51 +31,53 @@ internal class Status /// /// Constructor. /// - /// The chip architecture. + /// The chip architecture. /// Indicates whether unzip is installed. /// Indicates whether the debugger is installed. /// The installed .NET Core SDKs. /// The current value of the PATH environment variable. /// The Raspberry board model. /// The Raspberry board revision. + /// The Core SDK architecture public Status( - string architecture, + string processor, string path, bool hasUnzip, bool hasDebugger, IEnumerable installedSdks, string model, - string revision) + string revision, + SdkArchitecture architecture) { - Covenant.Requires(!string.IsNullOrEmpty(architecture), nameof(architecture)); + Covenant.Requires(!string.IsNullOrEmpty(processor), nameof(processor)); Covenant.Requires(path != null, nameof(path)); Covenant.Requires(installedSdks != null, nameof(installedSdks)); - this.Architecture = architecture; - this.PATH = path; + this.Processor = processor; + this.Path = path; this.HasUnzip = hasUnzip; this.HasDebugger = hasDebugger; - this.InstalledSdks = installedSdks.ToList(); + this.InstalledSdks = installedSdks?.ToList(); this.RaspberryModel = model; this.RaspberryRevision = revision; + this.Architecture = architecture; } - /// /// /// Returns the chip architecture (like armv71). /// - public string Architecture { get; private set; } + private string Processor { get; set; } /// /// Returns the current value of the PATH environment variable. /// - public string PATH { get; private set; } + private string Path { get; set; } /// /// Returns true if unzip is installed on the Raspberry Pi. /// This is required and will be installed automatically. /// - public bool HasUnzip { get; private set; } + private bool HasUnzip { get; set; } /// /// Indicates whether the vsdbg debugger is installed. @@ -92,16 +87,21 @@ public Status( /// /// Returns information about the .NET Core SDKs installed. /// - public List InstalledSdks { get; private set; } + public List InstalledSdks { get; } /// /// Returns the Raspberry board model. /// - public string RaspberryModel { get; private set; } + public string RaspberryModel { get; } /// /// Returns the Raspberry board revision. /// - public string RaspberryRevision { get; private set; } + private string RaspberryRevision { get; set; } + + /// + /// Returns the Raspberry architecture. + /// + public SdkArchitecture Architecture { get; } } } diff --git a/RaspberryDebugger/DebugHelper.cs b/RaspberryDebugger/DebugHelper.cs index f2dbb78..c46cb3d 100644 --- a/RaspberryDebugger/DebugHelper.cs +++ b/RaspberryDebugger/DebugHelper.cs @@ -14,41 +14,38 @@ // 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. - +// ReSharper disable StringLiteralTypo using System; using System.Collections.Generic; -using System.ComponentModel.Design; using System.Diagnostics.Contracts; -using System.Globalization; using System.IO; using System.Linq; -using System.Text; -using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; -using Microsoft.VisualStudio.Threading; - using EnvDTE; using EnvDTE80; using Neon.Common; -using Neon.IO; using Neon.Windows; - -using Newtonsoft.Json.Linq; - +using RaspberryDebugger.Connection; +using RaspberryDebugger.Dialogs; +using RaspberryDebugger.Models.Connection; +using RaspberryDebugger.Models.Project; +using RaspberryDebugger.Models.Raspberry; +using RaspberryDebugger.Models.VisualStudio; using Task = System.Threading.Tasks.Task; namespace RaspberryDebugger { /// - /// Remote debugger related utilties. + /// Remote debugger related utilities. /// internal static class DebugHelper { + private const string SupportedVersions = ".NET Core 3.1 or .NET 5 + 6"; /// /// Ensures that the native Windows OpenSSH client is installed, prompting /// the user to install it if necessary. @@ -60,7 +57,7 @@ public static async Task EnsureOpenSshAsync() Log.Info("Checking for native Windows OpenSSH client"); - var openSshPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Sysnative", "OpenSSH", "ssh.exe"); + var openSshPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "OpenSSH", "ssh.exe"); if (!File.Exists(openSshPath)) { @@ -68,8 +65,9 @@ public static async Task EnsureOpenSshAsync() Log.WriteLine("https://techcommunity.microsoft.com/t5/itops-talk-blog/installing-and-configuring-openssh-on-windows-server-2019/ba-p/309540"); var button = MessageBox.Show( - "Raspberry debugging requires the Windows OpenSSH client.\r\n\r\nWould you like to install this now (restart required)?", - "Windows OpenSSH Client Required", + @"Raspberry debugging requires the Windows OpenSSH client. + Would you like to install this now (restart required)?", + @"Windows OpenSSH Client Required", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); @@ -94,8 +92,8 @@ await PackageHelper.ExecuteWithProgressAsync("Installing OpenSSH Client", }); MessageBox.Show( - "Restart Windows to complete the OpenSSH Client installation.", - "Restart Required", + @"Restart Windows to complete the OpenSSH Client installation.", + @"Restart Required", MessageBoxButtons.OK); return false; @@ -121,8 +119,8 @@ public static Project GetTargetProject(DTE2 dte) if (dte.Solution == null) { MessageBox.Show( - "Please open a Visual Studio solution.", - "Solution Required", + @"Please open a Visual Studio solution.", + @"Solution Required", MessageBoxButtons.OK, MessageBoxIcon.Information); @@ -134,8 +132,8 @@ public static Project GetTargetProject(DTE2 dte) if (project == null) { MessageBox.Show( - "Please select a startup project for your solution.", - "Startup Project Required", + @"Please select a startup project for your solution.", + @"Startup Project Required", MessageBoxButtons.OK, MessageBoxIcon.Information); @@ -150,8 +148,8 @@ public static Project GetTargetProject(DTE2 dte) if (!projectProperties.IsNetCore) { MessageBox.Show( - "Only .NET Core 3.1 or .NET 5 projects are supported for Raspberry debugging.", - "Invalid Project Type", + $@"Only {SupportedVersions} projects are supported for Raspberry debugging.", + @"Invalid Project Type", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -161,8 +159,8 @@ public static Project GetTargetProject(DTE2 dte) if (!projectProperties.IsExecutable) { MessageBox.Show( - "Only projects types that generate an executable program are supported for Raspberry debugging.", - "Invalid Project Type", + @"Only projects types that generate an executable program are supported for Raspberry debugging.", + @"Invalid Project Type", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -172,8 +170,8 @@ public static Project GetTargetProject(DTE2 dte) if (string.IsNullOrEmpty(projectProperties.SdkVersion)) { MessageBox.Show( - "The .NET Core SDK version could not be identified.", - "Invalid Project Type", + @"The .NET Core SDK version could not be identified.", + @"Invalid Project Type", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -185,26 +183,27 @@ public static Project GetTargetProject(DTE2 dte) if (!projectProperties.IsSupportedSdkVersion) { MessageBox.Show( - $"The .NET Core SDK [{sdkVersion}] is not currently supported. Only .NET Core versions [v3.1] or later will ever be supported\r\n\r\nNote that we currently support only offical SDKs (not previews or release candidates) and we check for new .NET Core SDKs every week or two. Submit an issue if you really need support for a new SDK ASAP:\r\n\t\nhttps://github.com/nforgeio/RaspberryDebugger/issues", - "SDK Not Supported", + $@"The .NET Core SDK [{sdkVersion}] is not currently supported. Only .NET Core versions [v3.1] or later will ever be supported + Note that we currently support only official SDKs (not previews or release candidates) and we check for new .NET Core SDKs every week or two. + Submit an issue if you really need support for a new SDK ASAP: + https://github.com/nforgeio/RaspberryDebugger/issues", + @"SDK Not Supported", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } - if (projectProperties.AssemblyName.Contains(' ')) - { - MessageBox.Show( - $"Your assembly name [{projectProperties.AssemblyName}] includes a space. This isn't supported.", - "Unsupported Assembly Name", - MessageBoxButtons.OK, - MessageBoxIcon.Error); + if (!projectProperties.AssemblyName.Contains(' ')) return project; - return null; - } + MessageBox.Show( + $@"Your assembly name [{projectProperties.AssemblyName}] includes a space. This isn't supported.", + @"Unsupported Assembly Name", + MessageBoxButtons.OK, + MessageBoxIcon.Error); + + return null; - return project; } /// @@ -216,7 +215,7 @@ public static Project GetTargetProject(DTE2 dte) /// /// /// - public static async Task PublishProjectWithUIAsync(DTE2 dte, Solution solution, Project project, ProjectProperties projectProperties) + public static async Task PublishProjectWithUiAsync(DTE2 dte, Solution solution, Project project, ProjectProperties projectProperties) { Covenant.Requires(dte != null, nameof(dte)); Covenant.Requires(solution != null, nameof(solution)); @@ -228,8 +227,9 @@ public static async Task PublishProjectWithUIAsync(DTE2 dte, Solution solu if (!await PublishProjectAsync(dte, solution, project, projectProperties)) { MessageBox.Show( - "[dotnet publish] failed for the project.\r\n\r\nLook at the Output/Debug panel for more details.", - "Publish Failed", + @"[dotnet publish] failed for the project. + Look at the Output/Debug panel for more details.", + @"Publish Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -250,7 +250,7 @@ public static async Task PublishProjectWithUIAsync(DTE2 dte, Solution solu /// The project. /// The project properties. /// true on success. - public static async Task PublishProjectAsync(DTE2 dte, Solution solution, Project project, ProjectProperties projectProperties) + private static async Task PublishProjectAsync(DTE2 dte, Solution solution, Project project, ProjectProperties projectProperties) { Covenant.Requires(dte != null, nameof(dte)); Covenant.Requires(solution != null, nameof(solution)); @@ -267,35 +267,32 @@ public static async Task PublishProjectAsync(DTE2 dte, Solution solution, // random crashes when building or publishing projects when VS is still loading // projects. - var projectGuid = projectProperties.Guid; var solutionService4 = (IVsSolution4)await RaspberryDebuggerPackage.Instance.GetServiceAsync(typeof(SVsSolution)); if (solutionService4 == null) { - Covenant.Assert(solutionService4 != null, $"Service [{typeof(SVsSolution).Name}] is not available."); + // ReSharper disable once ConditionIsAlwaysTrueOrFalse + Covenant.Assert(solutionService4 != null, $"Service [{nameof(SVsSolution)}] is not available."); } - solutionService4.EnsureProjectIsLoaded(ref projectGuid, (uint)__VSBSLFLAGS.VSBSLFLAGS_LoadAllPendingProjects); - // Build the project to ensure that there are no compile-time errors. - Log.Info($"Building: {projectProperties.FullPath}"); + Log.Info($"Building: {projectProperties?.FullPath}"); - solution.SolutionBuild.BuildProject(solution.SolutionBuild.ActiveConfiguration.Name, project.UniqueName, WaitForBuildToFinish: true); + solution?.SolutionBuild.BuildProject(solution.SolutionBuild.ActiveConfiguration.Name, project?.UniqueName, WaitForBuildToFinish: true); - var errorList = dte.ToolWindows.ErrorList.ErrorItems; + var errorList = dte?.ToolWindows.ErrorList.ErrorItems; - if (errorList.Count > 0) + if (errorList?.Count > 0) { - for (int i = 1; i <= errorList.Count; i++) + for (var i = 1; i <= errorList.Count; i++) { var error = errorList.Item(i); - Log.Error($"{error.FileName}({error.Line},{error.Column}: {error.Description})"); } Log.Error($"Build failed: [{errorList.Count}] errors"); - Log.Error($"See the Build/Output panel for more information"); + Log.Error("See the Build/Output panel for more information"); return false; } @@ -310,51 +307,52 @@ public static async Task PublishProjectAsync(DTE2 dte, Solution solution, // these can cause conflicts when we invoke [dotnet] below to // publish the project. - Log.Info($"Publishing: {projectProperties.FullPath}"); + Log.Info($"Publishing: {projectProperties?.FullPath}"); await Task.Yield(); - var allowedVariableNames = -@" -ALLUSERSPROFILE -APPDATA -architecture -architecture_bits -CommonProgramFiles -CommonProgramFiles(x86) -CommonProgramW6432 -COMPUTERNAME -ComSpec -DOTNETPATH -DOTNET_CLI_TELEMETRY_OPTOUT -DriverData -HOME -HOMEDRIVE -HOMEPATH -LOCALAPPDATA -NUMBER_OF_PROCESSORS -OS -Path -PATHEXT -POWERSHELL_DISTRIBUTION_CHANNEL -PROCESSOR_ARCHITECTURE -PROCESSOR_IDENTIFIER -PROCESSOR_LEVEL -PROCESSOR_REVISION -ProgramData -ProgramFiles -ProgramFiles(x86) -ProgramW6432 -PUBLIC -SystemDrive -SystemRoot -TEMP -USERDOMAIN -USERDOMAIN_ROAMINGPROFILE -USERNAME -USERPROFILE -windir -"; + const string allowedVariableNames = + @" + ALLUSERSPROFILE + APPDATA + architecture + architecture_bits + CommonProgramFiles + CommonProgramFiles(x86) + CommonProgramW6432 + COMPUTERNAME + ComSpec + DOTNETPATH + DOTNET_CLI_TELEMETRY_OPTOUT + DriverData + HOME + HOMEDRIVE + HOMEPATH + LOCALAPPDATA + NUMBER_OF_PROCESSORS + OS + Path + PATHEXT + POWERSHELL_DISTRIBUTION_CHANNEL + PROCESSOR_ARCHITECTURE + PROCESSOR_IDENTIFIER + PROCESSOR_LEVEL + PROCESSOR_REVISION + ProgramData + ProgramFiles + ProgramFiles(x86) + ProgramW6432 + PUBLIC + SystemDrive + SystemRoot + TEMP + USERDOMAIN + USERDOMAIN_ROAMINGPROFILE + USERNAME + USERPROFILE + windir + "; + var allowedVariables = new HashSet(StringComparer.InvariantCultureIgnoreCase); var environmentVariables = new Dictionary(); @@ -381,24 +379,45 @@ public static async Task PublishProjectAsync(DTE2 dte, Solution solution, try { - var response = await NeonHelper.ExecuteCaptureAsync( - "dotnet", - new object[] - { + ExecuteResponse response; + + if (!string.IsNullOrEmpty(projectProperties?.Framework)) + { + response = await NeonHelper.ExecuteCaptureAsync( + "dotnet", + new object[] + { "publish", "--configuration", projectProperties.Configuration, + "--framework", projectProperties.Framework, "--runtime", projectProperties.Runtime, "--no-self-contained", "--output", projectProperties.PublishFolder, projectProperties.FullPath - }, - environmentVariables: environmentVariables); + }, + environmentVariables: environmentVariables).ConfigureAwait(false); + } + else + { + response = await NeonHelper.ExecuteCaptureAsync( + "dotnet", + new object[] + { + "publish", + "--configuration", projectProperties?.Configuration, + "--runtime", projectProperties?.Runtime, + "--no-self-contained", + "--output", projectProperties?.PublishFolder, + projectProperties?.FullPath + }, + environmentVariables: environmentVariables).ConfigureAwait(false); + } await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); if (response.ExitCode == 0) { - Log.Error("Publish succeeded"); + Log.Info("Publish succeeded"); return true; } @@ -426,18 +445,18 @@ public static async Task PublishProjectAsync(DTE2 dte, Solution solution, public static ConnectionInfo GetDebugConnectionInfo(ProjectProperties projectProperties) { Covenant.Requires(projectProperties != null, nameof(projectProperties)); - var existingConnections = PackageHelper.ReadConnections(); - var connectionInfo = (ConnectionInfo)null; + ConnectionInfo connectionInfo; - if (string.IsNullOrEmpty(projectProperties.DebugConnectionName)) + if (string.IsNullOrEmpty(projectProperties?.DebugConnectionName)) { connectionInfo = existingConnections.SingleOrDefault(info => info.IsDefault); + // ReSharper disable once InvertIf if (connectionInfo == null) { if (MessageBoxEx.Show( - $"Raspberry connection information required. Would you like to create a connection now?", + "Raspberry connection information required. Would you like to create a connection now?", "Raspberry Connection Required", MessageBoxButtons.YesNo, MessageBoxIcon.Error, @@ -480,131 +499,96 @@ public static ConnectionInfo GetDebugConnectionInfo(ProjectProperties projectPro return connectionInfo; } - /// - /// Determine which .NET SDK we should target for the project. - /// - /// The project properties. - /// The target or null when one could not be located. - public static Sdk GetTargetSdk(ProjectProperties projectProperties) - { - Covenant.Requires(projectProperties != null, nameof(projectProperties)); - - // We're just going to return a matching SDK from the catalog (if it exists). - // Note that there be maore than one match a standalone SDK or one that ships - // with Visual Studio. We'll favor the standalone one if possible. - - var sdkItem = PackageHelper.SdkGoodCatalog.Items.SingleOrDefault(item => item.Version == projectProperties.SdkVersion && - item.IsStandalone && - item.Architecture == SdkArchitecture.ARM32); - if (sdkItem == null) - { - // Look for a Visual Studio SDK instead. - - sdkItem = PackageHelper.SdkGoodCatalog.Items.SingleOrDefault(item => item.Version == projectProperties.SdkVersion && - item.Architecture == SdkArchitecture.ARM32); - } - - if (sdkItem == null) - { - MessageBoxEx.Show( - $".NET Core SDK [v{projectProperties.SdkVersion}] is unknown to the Raspberry Debugger. Please submit an issue at:\r\n\r\n{PackageHelper.GitHubIssuesUri}", - "Unknown .NET Core SDK", - MessageBoxButtons.OK, - MessageBoxIcon.Error); - - return null; - } - else - { - return new Sdk(sdkItem.Name, sdkItem.Version); - } - } - /// /// Establishes a connection to the Raspberry and ensures that the Raspberry has /// the target SDK, vsdbg installed and also handles uploading of the project /// binaries. /// /// The connection info. - /// The target SDK. /// The project properties. /// The project's Raspberry debug settings. /// The or null if there was an error. - public static async Task InitializeConnectionAsync(ConnectionInfo connectionInfo, Sdk targetSdk, ProjectProperties projectProperties, ProjectSettings projectSettings) + public static async Task InitializeConnectionAsync(ConnectionInfo connectionInfo, ProjectProperties projectProperties, ProjectSettings projectSettings) { Covenant.Requires(connectionInfo != null, nameof(connectionInfo)); - Covenant.Requires(targetSdk != null, nameof(targetSdk)); Covenant.Requires(projectProperties != null, nameof(projectProperties)); Covenant.Requires(projectSettings != null, nameof(projectSettings)); - var connection = await Connection.ConnectAsync(connectionInfo, projectSettings: projectSettings); + var connection = await Connection.Connection.ConnectAsync(connectionInfo, projectSettings: projectSettings); - // .NET Core only supports Raspberry models 3 and 4. + // device not found + if(connection == null) return null; - if (!connection.PiStatus.RaspberryModel.StartsWith("Raspberry Pi 3 Model") && - !connection.PiStatus.RaspberryModel.StartsWith("Raspberry Pi 4 Model")) + var raspberryModel = new RaspberryModelCheck(); + + // .NET Core only supports Raspberry models 3 and 4. + if(raspberryModel.IsNotSupported(connection.PiStatus.RaspberryModel)) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); MessageBoxEx.Show( - $"Your [{connection.PiStatus.RaspberryModel}] is not supported. .NET Core requires a Raspberry Model 3 or 4.", - $"Raspberry Not Supported", + $"Your [{raspberryModel.ActualType}] is not supported." + + $" This .NET version requires a {string.Join(" or ", raspberryModel.Supported)}.", + "Raspberry Not Supported", MessageBoxButtons.OK, MessageBoxIcon.Error); connection.Dispose(); + return null; } // Ensure that the SDK is installed. - - if (!await connection.InstallSdkAsync(targetSdk.Version)) + if (!await connection.SetupSdkAsync()) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); MessageBoxEx.Show( - $"Cannot install the .NET SDK [v{targetSdk.Version}] on the Raspberry.\r\n\r\nCheck the Debug Output for more details.", + $"Cannot install the .NET SDK [v{connection.PiStatus}] on the Raspberry.\r\n\r\nCheck the Debug Output for more details.", "SDK Installation Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); connection.Dispose(); + return null; } // Ensure that the debugger is installed. - - if (!await connection.InstallDebuggerAsync()) + if (!await connection.SetupDebuggerAsync()) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); MessageBoxEx.Show( - $"Cannot install the VSDBG debugger on the Raspberry.\r\n\r\nCheck the Debug Output for more details.", + "Cannot install the VSDBG debugger on the Raspberry.\r\n\r\nCheck the Debug Output for more details.", "Debugger Installation Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); connection.Dispose(); + return null; } // Upload the program binaries. + if (await connection.UploadProgramAsync( + projectProperties?.Name, + projectProperties?.AssemblyName, + projectProperties?.PublishFolder)) - if (!await connection.UploadProgramAsync(projectProperties.Name, projectProperties.AssemblyName, projectProperties.PublishFolder)) - { - await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); + return connection; - MessageBoxEx.Show( - $"Cannot upload the program binaries to the Raspberry.\r\n\r\nCheck the Debug Output for more details.", - "Debugger Installation Failed", - MessageBoxButtons.OK, - MessageBoxIcon.Error); + await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - connection.Dispose(); - return null; - } + MessageBoxEx.Show( + "Cannot upload the program binaries to the Raspberry.\r\n\r\nCheck the Debug Output for more details.", + "Debugger Installation Failed", + MessageBoxButtons.OK, + MessageBoxIcon.Error); + + connection.Dispose(); - return connection; + return null; } } } diff --git a/RaspberryDebugger/Dialogs/ConnectionDialog.Designer.cs b/RaspberryDebugger/Dialogs/ConnectionDialog.Designer.cs index 4c67738..f773ca0 100644 --- a/RaspberryDebugger/Dialogs/ConnectionDialog.Designer.cs +++ b/RaspberryDebugger/Dialogs/ConnectionDialog.Designer.cs @@ -15,20 +15,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Data; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; -using Neon.Common; -using BrightIdeasSoftware; - -namespace RaspberryDebugger +namespace RaspberryDebugger.Dialogs { partial class ConnectionDialog { diff --git a/RaspberryDebugger/Dialogs/ConnectionDialog.cs b/RaspberryDebugger/Dialogs/ConnectionDialog.cs index c30a10f..b7827be 100644 --- a/RaspberryDebugger/Dialogs/ConnectionDialog.cs +++ b/RaspberryDebugger/Dialogs/ConnectionDialog.cs @@ -17,28 +17,22 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Data; using System.Linq; using System.Net; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; - -using Neon.Common; using Neon.Net; +using RaspberryDebugger.Models.Connection; -namespace RaspberryDebugger +namespace RaspberryDebugger.Dialogs { /// /// Implements the Add/Remove connection dialogs. /// internal partial class ConnectionDialog : Form { - private const char passwordChar = '•'; + private const char PasswordChar = '•'; - private List existingConnections; + private readonly List existingConnections; /// /// Constructor. @@ -55,23 +49,28 @@ public ConnectionDialog(ConnectionInfo connectionInfo, bool edit, List { hostTextBox.Text = connectionInfo.Host; portTextBox.Text = connectionInfo.Port.ToString(); userTextBox.Text = connectionInfo.User; passwordTextBox.Text = connectionInfo.Password; - passwordTextBox.PasswordChar = passwordChar; + passwordTextBox.PasswordChar = PasswordChar; showPasswordCheckBox.Checked = false; instructionsTextBox.Visible = string.IsNullOrEmpty(connectionInfo.PrivateKeyPath); }; } + public sealed override string Text + { + get => base.Text; + set => base.Text = value; + } + /// /// Returns the connection being created or edited. /// - internal ConnectionInfo ConnectionInfo { get; private set; } + private ConnectionInfo ConnectionInfo { get; } /// /// Handles the OK button. @@ -95,7 +94,7 @@ private async void okButton_Click(object sender, EventArgs args) return; } - if (!IPAddress.TryParse(hostText, out var address) && !NetHelper.IsValidHost(hostText)) + if (!IPAddress.TryParse(hostText, out _) && !NetHelper.IsValidHost(hostText)) { portTextBox.Focus(); portTextBox.SelectAll(); @@ -183,9 +182,6 @@ private async void okButton_Click(object sender, EventArgs args) return; } - hasWhitespace = false; - hasQuote = false; - foreach (var ch in passwordText) { if (char.IsWhiteSpace(ch)) @@ -244,9 +240,7 @@ private async void okButton_Click(object sender, EventArgs args) try { - using (await Connection.ConnectAsync(testConnectionInfo)) - { - } + using (await Connection.Connection.ConnectAsync(testConnectionInfo)) { } } catch { @@ -290,7 +284,7 @@ private void cancelButton_Click(object sender, EventArgs args) /// The arguments. private void showPasswordCheckBox_CheckedChanged(object sender, EventArgs args) { - passwordTextBox.PasswordChar = showPasswordCheckBox.Checked ? (char)0 : passwordChar; + passwordTextBox.PasswordChar = showPasswordCheckBox.Checked ? (char)0 : PasswordChar; } } } diff --git a/RaspberryDebugger/Dialogs/KeysDialog.Designer.cs b/RaspberryDebugger/Dialogs/KeysDialog.Designer.cs index 568e371..0b8db22 100644 --- a/RaspberryDebugger/Dialogs/KeysDialog.Designer.cs +++ b/RaspberryDebugger/Dialogs/KeysDialog.Designer.cs @@ -1,4 +1,4 @@ -namespace RaspberryDebugger +namespace RaspberryDebugger.Dialogs { partial class KeysDialog { diff --git a/RaspberryDebugger/Dialogs/KeysDialog.cs b/RaspberryDebugger/Dialogs/KeysDialog.cs index 8d0af99..555e501 100644 --- a/RaspberryDebugger/Dialogs/KeysDialog.cs +++ b/RaspberryDebugger/Dialogs/KeysDialog.cs @@ -16,20 +16,9 @@ // limitations under the License. using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Data; -using System.Linq; -using System.Net; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; -using Neon.Common; -using Neon.Net; - -namespace RaspberryDebugger +namespace RaspberryDebugger.Dialogs { /// /// Edits a connection's SSH key pair. diff --git a/RaspberryDebugger/Dialogs/MessageBoxEx.cs b/RaspberryDebugger/Dialogs/MessageBoxEx.cs index fe2c806..d253b18 100644 --- a/RaspberryDebugger/Dialogs/MessageBoxEx.cs +++ b/RaspberryDebugger/Dialogs/MessageBoxEx.cs @@ -16,12 +16,13 @@ // limitations under the License. using System; -using System.Windows.Forms; -using System.Text; using System.Drawing; using System.Runtime.InteropServices; +using System.Text; +using System.Windows.Forms; +// ReSharper disable IdentifierTypo -namespace RaspberryDebugger +namespace RaspberryDebugger.Dialogs { // This class was adapted from: // @@ -117,11 +118,11 @@ public static DialogResult Show(IWin32Window owner, string text, string caption, public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam); - public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime); + public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIdEvent, uint dwTime); - public const int WH_CALLWNDPROCRET = 12; + public const int WhCallwndprocret = 12; - public enum CbtHookAction : int + public enum CbtHookAction { HCBT_MOVESIZE = 0, HCBT_MINMAX = 1, @@ -139,13 +140,13 @@ public enum CbtHookAction : int private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect); [DllImport("user32.dll")] - private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint); + private static extern int MoveWindow(IntPtr hWnd, int x, int y, int nWidth, int nHeight, bool bRepaint); [DllImport("User32.dll")] - public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc); + public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIdEvent, uint uElapse, TimerProc lpTimerFunc); [DllImport("User32.dll")] - public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId); @@ -166,7 +167,7 @@ public enum CbtHookAction : int public static extern int EndDialog(IntPtr hDlg, IntPtr nResult); [StructLayout(LayoutKind.Sequential)] - public struct CWPRETSTRUCT + public struct Cwpretstruct { public IntPtr lResult; public IntPtr lParam; @@ -177,7 +178,7 @@ public struct CWPRETSTRUCT static MessageBoxEx() { - _hookProc = new HookProc(MessageBoxHookProc); + _hookProc = MessageBoxHookProc; _hHook = IntPtr.Zero; } @@ -191,7 +192,7 @@ private static void Initialize() if (_owner != null) { #pragma warning disable CS0618 - _hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, _hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId()); + _hHook = SetWindowsHookEx(WhCallwndprocret, _hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId()); #pragma warning restore CS0618 } } @@ -203,7 +204,7 @@ private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam return CallNextHookEx(_hHook, nCode, wParam, lParam); } - CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT)); + Cwpretstruct msg = (Cwpretstruct)Marshal.PtrToStructure(lParam, typeof(Cwpretstruct)); IntPtr hook = _hHook; if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE) diff --git a/RaspberryDebugger/Dialogs/SettingsDialog.Designer.cs b/RaspberryDebugger/Dialogs/SettingsDialog.Designer.cs index 53f5993..31a9315 100644 --- a/RaspberryDebugger/Dialogs/SettingsDialog.Designer.cs +++ b/RaspberryDebugger/Dialogs/SettingsDialog.Designer.cs @@ -1,4 +1,4 @@ -namespace RaspberryDebugger +namespace RaspberryDebugger.Dialogs { partial class SettingsDialog { @@ -28,6 +28,7 @@ protected override void Dispose(bool disposing) /// private void InitializeComponent() { + this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SettingsDialog)); this.targetLabel = new System.Windows.Forms.Label(); this.targetComboBox = new System.Windows.Forms.ComboBox(); @@ -36,12 +37,16 @@ private void InitializeComponent() this.instructionsTextBox = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.targetGroup = new System.Windows.Forms.TextBox(); + this.webServerProxyLabel = new System.Windows.Forms.Label(); + this.webServerProxyCheck = new System.Windows.Forms.CheckBox(); + this.toolTip = new System.Windows.Forms.ToolTip(this.components); + this.groupBox = new System.Windows.Forms.GroupBox(); this.SuspendLayout(); // // targetLabel // this.targetLabel.AutoSize = true; - this.targetLabel.Location = new System.Drawing.Point(12, 17); + this.targetLabel.Location = new System.Drawing.Point(13, 17); this.targetLabel.Name = "targetLabel"; this.targetLabel.Size = new System.Drawing.Size(92, 13); this.targetLabel.TabIndex = 1; @@ -50,14 +55,14 @@ private void InitializeComponent() // targetComboBox // this.targetComboBox.FormattingEnabled = true; - this.targetComboBox.Location = new System.Drawing.Point(106, 14); + this.targetComboBox.Location = new System.Drawing.Point(110, 14); this.targetComboBox.Name = "targetComboBox"; - this.targetComboBox.Size = new System.Drawing.Size(239, 21); + this.targetComboBox.Size = new System.Drawing.Size(267, 21); this.targetComboBox.TabIndex = 2; // // okButton // - this.okButton.Location = new System.Drawing.Point(363, 13); + this.okButton.Location = new System.Drawing.Point(395, 13); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 6; @@ -68,7 +73,7 @@ private void InitializeComponent() // cancelButton // this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.cancelButton.Location = new System.Drawing.Point(363, 44); + this.cancelButton.Location = new System.Drawing.Point(395, 44); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 7; @@ -78,18 +83,18 @@ private void InitializeComponent() // // instructionsTextBox // - this.instructionsTextBox.Location = new System.Drawing.Point(15, 86); + this.instructionsTextBox.Location = new System.Drawing.Point(16, 121); this.instructionsTextBox.Multiline = true; this.instructionsTextBox.Name = "instructionsTextBox"; this.instructionsTextBox.ReadOnly = true; - this.instructionsTextBox.Size = new System.Drawing.Size(330, 85); + this.instructionsTextBox.Size = new System.Drawing.Size(454, 102); this.instructionsTextBox.TabIndex = 5; this.instructionsTextBox.Text = resources.GetString("instructionsTextBox.Text"); // // label1 // this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(30, 49); + this.label1.Location = new System.Drawing.Point(32, 48); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(73, 13); this.label1.TabIndex = 3; @@ -97,18 +102,52 @@ private void InitializeComponent() // // targetGroup // - this.targetGroup.Location = new System.Drawing.Point(106, 46); + this.targetGroup.Location = new System.Drawing.Point(110, 44); this.targetGroup.Name = "targetGroup"; this.targetGroup.Size = new System.Drawing.Size(100, 20); this.targetGroup.TabIndex = 4; // + // webServerProxyLabel + // + this.webServerProxyLabel.AutoSize = true; + this.webServerProxyLabel.Location = new System.Drawing.Point(46, 91); + this.webServerProxyLabel.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); + this.webServerProxyLabel.Name = "webServerProxyLabel"; + this.webServerProxyLabel.Size = new System.Drawing.Size(58, 13); + this.webServerProxyLabel.TabIndex = 8; + this.webServerProxyLabel.Text = "Use Proxy:"; + this.toolTip.SetToolTip(this.webServerProxyLabel, "Use an own configured proxy for Asp.NET"); + // + // webServerProxyCheck + // + this.webServerProxyCheck.AutoSize = true; + this.webServerProxyCheck.Location = new System.Drawing.Point(110, 92); + this.webServerProxyCheck.Margin = new System.Windows.Forms.Padding(2); + this.webServerProxyCheck.Name = "webServerProxyCheck"; + this.webServerProxyCheck.RightToLeft = System.Windows.Forms.RightToLeft.No; + this.webServerProxyCheck.Size = new System.Drawing.Size(15, 14); + this.webServerProxyCheck.TabIndex = 9; + this.toolTip.SetToolTip(this.webServerProxyCheck, "Use an own configured proxy for Asp.NET"); + this.webServerProxyCheck.UseVisualStyleBackColor = true; + // + // groupBox + // + this.groupBox.Location = new System.Drawing.Point(15, 71); + this.groupBox.Name = "groupBox"; + this.groupBox.Size = new System.Drawing.Size(455, 44); + this.groupBox.TabIndex = 10; + this.groupBox.TabStop = false; + this.groupBox.Text = "Asp.NET solution/project only setting"; + // // SettingsDialog // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.cancelButton; - this.ClientSize = new System.Drawing.Size(450, 187); + this.ClientSize = new System.Drawing.Size(482, 235); + this.Controls.Add(this.webServerProxyCheck); + this.Controls.Add(this.webServerProxyLabel); this.Controls.Add(this.targetGroup); this.Controls.Add(this.label1); this.Controls.Add(this.instructionsTextBox); @@ -116,6 +155,7 @@ private void InitializeComponent() this.Controls.Add(this.okButton); this.Controls.Add(this.targetComboBox); this.Controls.Add(this.targetLabel); + this.Controls.Add(this.groupBox); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; @@ -137,5 +177,9 @@ private void InitializeComponent() private System.Windows.Forms.TextBox instructionsTextBox; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox targetGroup; + private System.Windows.Forms.Label webServerProxyLabel; + private System.Windows.Forms.CheckBox webServerProxyCheck; + private System.Windows.Forms.ToolTip toolTip; + private System.Windows.Forms.GroupBox groupBox; } } \ No newline at end of file diff --git a/RaspberryDebugger/Dialogs/SettingsDialog.cs b/RaspberryDebugger/Dialogs/SettingsDialog.cs index 22cd776..bbb90d6 100644 --- a/RaspberryDebugger/Dialogs/SettingsDialog.cs +++ b/RaspberryDebugger/Dialogs/SettingsDialog.cs @@ -14,32 +14,22 @@ // 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. - +using RaspberryDebugger.Models.Project; using System; using System.Collections.Generic; -using System.ComponentModel; using System.Diagnostics.Contracts; -using System.Drawing; -using System.Data; using System.Linq; -using System.Net; -using System.Text; using System.Text.RegularExpressions; -using System.Threading.Tasks; using System.Windows.Forms; -using Neon.Common; -using Neon.Net; - -namespace RaspberryDebugger +namespace RaspberryDebugger.Dialogs { /// - /// Allows the user to edit the Rasparry related settings for a project. + /// Allows the user to edit the Raspberry related settings for a project. /// internal partial class SettingsDialog : Form { - private ProjectSettings projectSettings; - private Dictionary connectionNameToIndex; + private readonly ProjectSettings projectSettings; /// /// Constructor. @@ -48,23 +38,20 @@ internal partial class SettingsDialog : Form public SettingsDialog(ProjectSettings projectSettings) { Covenant.Requires(projectSettings != null); - this.projectSettings = projectSettings; InitializeComponent(); // The instructions include "\r\n" sequences that need to be replaced with // actual CR/LF characters. - instructionsTextBox.Text = Regex.Unescape(instructionsTextBox.Text); // Initialize the combo box with the available connections and select // the current one. - - connectionNameToIndex = new Dictionary(StringComparer.InvariantCultureIgnoreCase); + var connectionNameToIndex = new Dictionary(StringComparer.InvariantCultureIgnoreCase); var connections = PackageHelper.ReadConnections(disableLogging: true); - var index = 0; + var index = 0; targetComboBox.Items.Clear(); @@ -80,7 +67,7 @@ public SettingsDialog(ProjectSettings projectSettings) connectionNameToIndex.Add(connection.Name, index++); } - if (!projectSettings.EnableRemoteDebugging) + if (projectSettings is { EnableRemoteDebugging: false }) { targetComboBox.SelectedIndex = connectionNameToIndex[ProjectSettings.DisabledConnectionName]; } @@ -88,27 +75,32 @@ public SettingsDialog(ProjectSettings projectSettings) { // If the connection named in the settings exists select it, // otherwise select the default. + var selectedConnection = connections.FirstOrDefault(connection => projectSettings != null + && connection.Name.Equals(projectSettings.RemoteDebugTarget, StringComparison.InvariantCultureIgnoreCase)); - var selectedConnection = connections.FirstOrDefault(connection => connection.Name.Equals(projectSettings.RemoteDebugTarget, StringComparison.InvariantCultureIgnoreCase)); - - if (projectSettings.RemoteDebugTarget == null || selectedConnection == null) + if (projectSettings != null && (projectSettings.RemoteDebugTarget == null || selectedConnection == null)) { targetComboBox.SelectedIndex = connectionNameToIndex[ProjectSettings.DefaultConnectionName]; } else { - targetComboBox.SelectedIndex = connectionNameToIndex[selectedConnection.Name]; + if (selectedConnection != null) + { + targetComboBox.SelectedIndex = connectionNameToIndex[selectedConnection.Name]; + } } } + if (projectSettings == null) return; targetGroup.Text = projectSettings.TargetGroup; + webServerProxyCheck.Checked = projectSettings.UseWebServerProxy; } /// /// Handles OK button clicks. /// /// The sender - /// + /// Event arguments private void okButton_Click(object sender, EventArgs args) { var selectedItem = (string)(targetComboBox.SelectedItem); @@ -123,13 +115,13 @@ private void okButton_Click(object sender, EventArgs args) case ProjectSettings.DefaultConnectionName: projectSettings.EnableRemoteDebugging = true; - projectSettings.RemoteDebugTarget = null; // NULL means default + projectSettings.RemoteDebugTarget = null; // NULL means default break; default: projectSettings.EnableRemoteDebugging = true; - projectSettings.RemoteDebugTarget = selectedItem; + projectSettings.RemoteDebugTarget = selectedItem; break; } @@ -141,8 +133,8 @@ private void okButton_Click(object sender, EventArgs args) targetGroup.SelectAll(); MessageBoxEx.Show( - $"Invalid Linux group name: group names should not include spaces.", - $"Target Group Error", + "Invalid Linux group name: group names should not include spaces.", + "Target Group Error", MessageBoxButtons.OK, MessageBoxIcon.Error); @@ -150,6 +142,7 @@ private void okButton_Click(object sender, EventArgs args) } projectSettings.TargetGroup = targetGroup.Text; + projectSettings.UseWebServerProxy = webServerProxyCheck.Checked; DialogResult = DialogResult.OK; } @@ -158,7 +151,7 @@ private void okButton_Click(object sender, EventArgs args) /// Handles Cancel button clicks. /// /// The sender - /// + /// Event arguments private void cancelButton_Click(object sender, EventArgs args) { DialogResult = DialogResult.Cancel; diff --git a/RaspberryDebugger/Dialogs/SettingsDialog.resx b/RaspberryDebugger/Dialogs/SettingsDialog.resx index e76546c..15f86eb 100644 --- a/RaspberryDebugger/Dialogs/SettingsDialog.resx +++ b/RaspberryDebugger/Dialogs/SettingsDialog.resx @@ -120,6 +120,9 @@ Raspberry connections are managed via [Tools/Options] on the [Raspberry Debugger] page.\r\n\r\nTo disable Raspberry debugging, select [debugging disabled] above otherwise, select [default connection] or the specific connection you want to use. + + 17, 17 + diff --git a/RaspberryDebugger/Extensions/CursorWait.cs b/RaspberryDebugger/Extensions/CursorWait.cs new file mode 100644 index 0000000..1be08cb --- /dev/null +++ b/RaspberryDebugger/Extensions/CursorWait.cs @@ -0,0 +1,25 @@ +using System; +using System.Windows.Forms; + +namespace RaspberryDebugger.Extensions +{ + public class CursorWait : IDisposable + { + public CursorWait(bool appStarting = false, bool applicationCursor = false) + { + // Wait + Cursor.Current = appStarting + ? Cursors.AppStarting + : Cursors.WaitCursor; + + if (applicationCursor) Application.UseWaitCursor = true; + } + + public void Dispose() + { + // Reset + Cursor.Current = Cursors.Default; + Application.UseWaitCursor = false; + } + } +} \ No newline at end of file diff --git a/RaspberryDebugger/Extensions/Extension.cs b/RaspberryDebugger/Extensions/Extension.cs new file mode 100644 index 0000000..169bc90 --- /dev/null +++ b/RaspberryDebugger/Extensions/Extension.cs @@ -0,0 +1,23 @@ +using System; + +namespace RaspberryDebugger.Extensions +{ + public static class EnumMemberAttributeExtension + { + /// + /// Gets the type of the attribute of. + /// + /// + /// The enum value. + /// value + public static T GetAttributeOfType(this Enum enumVal) where T : Attribute + { + var memInfo = enumVal.GetType().GetMember(enumVal.ToString()); + var attributes = memInfo[0].GetCustomAttributes(typeof(T), false); + + return (attributes.Length > 0) + ? (T)attributes[0] + : null; + } + } +} diff --git a/RaspberryDebugger/Models/Connection/AuthenticationType.cs b/RaspberryDebugger/Models/Connection/AuthenticationType.cs index f5b7405..ac7d34e 100644 --- a/RaspberryDebugger/Models/Connection/AuthenticationType.cs +++ b/RaspberryDebugger/Models/Connection/AuthenticationType.cs @@ -15,11 +15,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; -using System.Collections.Generic; using System.Runtime.Serialization; -namespace RaspberryDebugger +namespace RaspberryDebugger.Models.Connection { /// /// Enumerates the supported SSH authentication types. @@ -30,12 +28,12 @@ internal enum AuthenticationType /// Password based authentication. /// [EnumMember(Value = "password")] - Password = 0, + PASSWORD = 0, /// /// Public SSH key based authentication. /// [EnumMember(Value = "public-key")] - PublicKey + PUBLIC_KEY } } diff --git a/RaspberryDebugger/Models/Connection/ConnectionInfo.cs b/RaspberryDebugger/Models/Connection/ConnectionInfo.cs index 9aa34fa..415b226 100644 --- a/RaspberryDebugger/Models/Connection/ConnectionInfo.cs +++ b/RaspberryDebugger/Models/Connection/ConnectionInfo.cs @@ -14,18 +14,13 @@ // 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. - -using System; -using System.Collections.Generic; using System.ComponentModel; -using System.Configuration; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; - +using System.Diagnostics.CodeAnalysis; using Neon.Net; using Newtonsoft.Json; +using RaspberryDebugger.OptionsPages; -namespace RaspberryDebugger +namespace RaspberryDebugger.Models.Connection { /// /// Describes a Raspberry Pi connection's network details and credentials. @@ -70,11 +65,10 @@ public bool IsDefault set { - if (isDefault != value) - { - isDefault = value; - ConnectionsPanel?.ConnectionIsDefaultChanged(this); - } + if (isDefault == value) return; + + isDefault = value; + ConnectionsPanel?.ConnectionIsDefaultChanged(this); } } @@ -127,7 +121,7 @@ public string User /// [JsonProperty(PropertyName = "PrivateKeyPath", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue(null)] - public string PrivateKeyPath { get; set; } = null; + public string PrivateKeyPath { get; set; } /// /// Path to the public key for this connection or null when one @@ -135,7 +129,7 @@ public string User /// [JsonProperty(PropertyName = "PublicKeyPath", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue(null)] - public string PublicKeyPath { get; set; } = null; + public string PublicKeyPath { get; set; } /// /// Describes the authentication method. @@ -154,6 +148,7 @@ public string User /// appear to have a check box changed event. /// /// + [SuppressMessage("ReSharper", "InvalidXmlDocComment")] internal ConnectionsPanel ConnectionsPanel { get; set; } } } diff --git a/RaspberryDebugger/Models/Project/ProjectSettings.cs b/RaspberryDebugger/Models/Project/ProjectSettings.cs index 11cdb79..5754b56 100644 --- a/RaspberryDebugger/Models/Project/ProjectSettings.cs +++ b/RaspberryDebugger/Models/Project/ProjectSettings.cs @@ -14,16 +14,10 @@ // 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. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; - using Newtonsoft.Json; +using System.ComponentModel; -namespace RaspberryDebugger +namespace RaspberryDebugger.Models.Project { /// /// Holds the Raspberry related settings for a project. @@ -38,7 +32,7 @@ internal class ProjectSettings /// /// Connection combo box item indicating that the default Raspberry connection should be used. /// - public const string DefaultConnectionName = "[DEFAULT]"; + public const string DefaultConnectionName = "[DEFAULT]"; /// /// Default constructor that returns settings with remote debugging disabled. @@ -46,7 +40,8 @@ internal class ProjectSettings public ProjectSettings() { EnableRemoteDebugging = false; - RemoteDebugTarget = null; + RemoteDebugTarget = null; + UseWebServerProxy = true; } /// @@ -56,7 +51,7 @@ public ProjectSettings() public bool EnableRemoteDebugging { get; set; } /// - /// Specifes the name of the specific remote Raspberry connection to use or + /// Specifies the name of the specific remote Raspberry connection to use or /// null for the default connection. /// [JsonProperty(PropertyName = "RemoteDebugTarget", Required = Required.AllowNull)] @@ -69,5 +64,9 @@ public ProjectSettings() [JsonProperty(PropertyName = "TargetGroup", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] [DefaultValue("gpio")] public string TargetGroup { get; set; } = "gpio"; + + [JsonProperty(PropertyName = "UseWebServerProxy", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] + [DefaultValue(true)] + public bool UseWebServerProxy { get; set; } } } diff --git a/RaspberryDebugger/Models/Project/RaspberryProjects.cs b/RaspberryDebugger/Models/Project/RaspberryProjects.cs index 6dad06f..ecfe1e0 100644 --- a/RaspberryDebugger/Models/Project/RaspberryProjects.cs +++ b/RaspberryDebugger/Models/Project/RaspberryProjects.cs @@ -14,17 +14,9 @@ // 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. - -using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -using System.Runtime.Serialization; - -using Newtonsoft.Json; -namespace RaspberryDebugger +namespace RaspberryDebugger.Models.Project { /// /// Holds the Raspberry related settings for projects in a solution. This is @@ -39,30 +31,29 @@ internal class RaspberryProjects : Dictionary /// /// Accesses the project settings for a project based on its GUID. /// - /// The project's unique name. + /// The project's unique name. /// /// The for the project, initializing default /// (disabled) settings if when the project doesn't exist. /// - public new ProjectSettings this[string projectUnqueName] + public new ProjectSettings this[string projectUniqueName] { get { - if (base.TryGetValue(projectUnqueName, out var settings)) + if (TryGetValue(projectUniqueName, out var settings)) { return settings; } else { settings = new ProjectSettings(); - - this[projectUnqueName] = settings; + this[projectUniqueName] = settings; return settings; } } - set => base[projectUnqueName] = value; + set => base[projectUniqueName] = value; } } } diff --git a/RaspberryDebugger/Models/Raspberry/RaspberryCatalog.cs b/RaspberryDebugger/Models/Raspberry/RaspberryCatalog.cs index f633da6..4132396 100644 --- a/RaspberryDebugger/Models/Raspberry/RaspberryCatalog.cs +++ b/RaspberryDebugger/Models/Raspberry/RaspberryCatalog.cs @@ -14,15 +14,10 @@ // 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. - -using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.InteropServices; - using Newtonsoft.Json; -namespace RaspberryDebugger +namespace RaspberryDebugger.Models.Raspberry { /// /// Describes the known Raspberry boards as described here. diff --git a/RaspberryDebugger/Models/Raspberry/RaspberryModel.cs b/RaspberryDebugger/Models/Raspberry/RaspberryModel.cs index 627ebc6..efaeed0 100644 --- a/RaspberryDebugger/Models/Raspberry/RaspberryModel.cs +++ b/RaspberryDebugger/Models/Raspberry/RaspberryModel.cs @@ -14,18 +14,13 @@ // 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. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.InteropServices; - using Newtonsoft.Json; -namespace RaspberryDebugger +namespace RaspberryDebugger.Models.Raspberry { /// - /// Describes a specific Raspberry board as described here. + /// Describes a specific Raspberry board as described + /// here. /// internal class RaspberryModel { diff --git a/RaspberryDebugger/Models/Raspberry/RaspberryModelCheck.cs b/RaspberryDebugger/Models/Raspberry/RaspberryModelCheck.cs new file mode 100644 index 0000000..d836187 --- /dev/null +++ b/RaspberryDebugger/Models/Raspberry/RaspberryModelCheck.cs @@ -0,0 +1,30 @@ +using System.Linq; +using System.Collections.Generic; + +namespace RaspberryDebugger.Models.Raspberry +{ + public class RaspberryModelCheck + { + public string ActualType { get; private set; } + + public List Supported { get; } + + public RaspberryModelCheck() + { + Supported = new List() + { + "Raspberry Pi 3 Model", + "Raspberry Pi 4 Model", + "Raspberry Pi Compute Module 4", + "Raspberry Pi Zero 2" + }; + } + + public bool IsNotSupported(string raspberryType) + { + ActualType = raspberryType; + + return !Supported.Any(raspberryType.StartsWith); + } + } +} diff --git a/RaspberryDebugger/Models/Sdk/SdkArchitecture.cs b/RaspberryDebugger/Models/Sdk/SdkArchitecture.cs index c5796eb..513f6df 100644 --- a/RaspberryDebugger/Models/Sdk/SdkArchitecture.cs +++ b/RaspberryDebugger/Models/Sdk/SdkArchitecture.cs @@ -15,31 +15,62 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.InteropServices; using System.Runtime.Serialization; -using Newtonsoft.Json; - -namespace RaspberryDebugger +namespace RaspberryDebugger.Models.Sdk { /// /// Enumerates the supported ARM architectures. /// - internal enum SdkArchitecture + public enum SdkArchitecture + { + /// + /// 32-bit ARM + /// + [EnumMember(Value = "Arm32")] + Arm32, + + /// + /// 64-bit ARM + /// + [EnumMember(Value = "Arm64")] + Arm64, + + /// + /// unknown + /// + [EnumMember(Value = "Unknown")] + Unknown + } + + /// + /// Enumerates the supported architecture bitness. + /// + public enum Platform { /// /// 32-bit ARM /// - [EnumMember(Value = "ARM32")] - ARM32, + [EnumMember(Value = "32")] + Bitness32, /// /// 64-bit ARM /// - [EnumMember(Value = "ARM64")] - ARM64 + [EnumMember(Value = "64")] + Bitness64 + } + + /// + /// OperatingSystem bitness + /// + public static class OperatingSystem + { + public static List Bitness32 { get; private set; } = + new List(new []{"armv3", "armv7"}); + + public static List Bitness64 { get; private set; } = + new List(new []{"armv8", "aarch64"}); } } diff --git a/RaspberryDebugger/Models/Sdk/SdkCatalog.cs b/RaspberryDebugger/Models/Sdk/SdkCatalog.cs index ddc477d..a79d8a3 100644 --- a/RaspberryDebugger/Models/Sdk/SdkCatalog.cs +++ b/RaspberryDebugger/Models/Sdk/SdkCatalog.cs @@ -14,15 +14,10 @@ // 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. - -using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.InteropServices; - using Newtonsoft.Json; -namespace RaspberryDebugger +namespace RaspberryDebugger.Models.Sdk { /// /// Describes the available .NET Core SDK binary downloads for ARM. @@ -33,6 +28,6 @@ internal class SdkCatalog /// The list of SDK catalog items. /// [JsonProperty(PropertyName = "Items", Required = Required.Always)] - public List Items { get; set; } + public List Items { get; set; } = new List(); } } diff --git a/RaspberryDebugger/Models/Sdk/SdkCatalogItem.cs b/RaspberryDebugger/Models/Sdk/SdkCatalogItem.cs index 4208f9e..9a305f6 100644 --- a/RaspberryDebugger/Models/Sdk/SdkCatalogItem.cs +++ b/RaspberryDebugger/Models/Sdk/SdkCatalogItem.cs @@ -14,25 +14,15 @@ // 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. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Runtime.InteropServices; - -using Neon.Common; - using Newtonsoft.Json; -namespace RaspberryDebugger +namespace RaspberryDebugger.Models.Sdk { /// /// Describes an .NET Core SDK download. /// internal class SdkCatalogItem { - private bool? isStandAlone; - /// /// The SDK name (like "3.1.402"). /// @@ -40,10 +30,10 @@ internal class SdkCatalogItem public string Name { get; set; } /// - /// The SDK Version (like "3.1.8"). + /// The SDK Release (like "6.0.301"). /// - [JsonProperty(PropertyName = "Version", Required = Required.Always)] - public string Version { get; set; } + [JsonProperty(PropertyName = "Release", Required = Required.Always)] + public string Release { get; set; } /// /// Specifies the 32-bit or 64-bit version of the SDK. @@ -61,42 +51,23 @@ internal class SdkCatalogItem /// The SHA512 hash expected for the download.z /// [JsonProperty(PropertyName = "SHA512", Required = Required.Always)] - public string SHA512 { get; set; } - - /// - /// Indicates whether the SDK is actually usable or not. This defaults - /// to false. This is set for some early .NET 5.0 releases - /// that didn't work on ARM64. - /// - [JsonProperty(PropertyName = "Unusable", Required = Required.Default, DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)] - [DefaultValue(false)] - public bool IsUnusable { get; set; } + public string Sha512 { get; set; } /// - /// Indicates that the SDK is usable. + /// SdkCatalog Item Constructor /// - [JsonIgnore] - public bool IsUsable => !IsUnusable; - - /// - /// Indicates that this is a standaloneg SDK vs. one integrated into Visual Studio; - /// - [JsonIgnore] - public bool IsStandalone + /// SDK Name + /// SDK Release number + /// SDK type + /// Link for download + /// Checksum for download + public SdkCatalogItem(string name, string release, SdkArchitecture sdk, string link, string sha512) { - get - { - if (isStandAlone.HasValue) - { - return isStandAlone.Value; - } - - // Standalone SDKs seem to have name patch versions < 200. - - isStandAlone = SemanticVersion.Parse(Name).Patch < 200; - - return isStandAlone.Value; - } + Name = name; + Architecture = sdk; + Release = release; + Link = link; + Sha512 = sha512; } } } diff --git a/RaspberryDebugger/Models/VisualStudio/ProjectProperties.cs b/RaspberryDebugger/Models/VisualStudio/ProjectProperties.cs index 89a261c..13a3149 100644 --- a/RaspberryDebugger/Models/VisualStudio/ProjectProperties.cs +++ b/RaspberryDebugger/Models/VisualStudio/ProjectProperties.cs @@ -1,582 +1,557 @@ -//----------------------------------------------------------------------------- -// FILE: ProjectProperties.cs -// CONTRIBUTOR: Jeff Lill -// COPYRIGHT: Copyright (c) 2021 by neonFORGE, LLC. 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. - -using System; -using System.Collections.Generic; -using System.ComponentModel.Design; -using System.Diagnostics.Contracts; -using System.Drawing.Imaging; -using System.Drawing.Text; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; -using System.Windows.Forms; - -using EnvDTE; -using EnvDTE80; -using Microsoft.VisualStudio; -using Microsoft.VisualStudio.Shell; -using Microsoft.VisualStudio.Shell.Interop; - -using Neon.Common; -using Neon.Net; - -using Newtonsoft.Json.Linq; - -using Task = System.Threading.Tasks.Task; - -namespace RaspberryDebugger -{ - /// - /// The Visual Studio class properties can only be - /// accessed from the UI thread, so we'll use this class to capture the - /// properties we need on a UI thread so we can use them later on other - /// threads. - /// - internal class ProjectProperties - { - //-------------------------------------------------------------------- - // Static members - - /// - /// Creates a instance holding the - /// necessary properties from a . This must - /// be called on a UI thread. - /// - /// The current solution. - /// The source project. - /// The cloned . - public static ProjectProperties CopyFrom(Solution solution, Project project) - { - Covenant.Requires(solution != null, nameof(solution)); - Covenant.Requires(project != null, nameof(project)); - - ThreadHelper.ThrowIfNotOnUIThread(); - - if (string.IsNullOrEmpty(project.FullName)) - { - // We'll see this for unsupported Visual Studio projects and will just - // return project properties indicating this. - - return new ProjectProperties() - { - Name = project.Name, - FullPath = project.FullName, - Configuration = null, - IsNetCore = false, - SdkVersion = null, - OutputFolder = null, - OutputFileName = null, - IsExecutable = false, - AssemblyName = null, - DebugEnabled = false, - DebugConnectionName = null, - CommandLineArgs = new List(), - EnvironmentVariables = new Dictionary(), - IsSupportedSdkVersion = false, - IsRaspberryCompatible = false, - IsAspNet = false, - AspPort = 0, - AspLaunchBrowser = false, - AspRelativeBrowserUri = null - }; - } - - var projectFolder = Path.GetDirectoryName(project.FullName); - var isNetCore = true; - var netVersion = (SemanticVersion)null; - var sdkName = (string)null; - - // Read the properties we care about from the project. - - var targetFrameworkMonikers = (string)project.Properties.Item("TargetFrameworkMoniker").Value; - var outputType = (int)project.Properties.Item("OutputType").Value; - - var monikers = targetFrameworkMonikers.Split(','); - - isNetCore = monikers[0] == ".NETCoreApp"; - - // Extract the version from the moniker. This looks like: "Version=v5.0" - - var versionRegex = new Regex(@"(?[0-9\.]+)$"); - - netVersion = SemanticVersion.Parse(versionRegex.Match(monikers[1]).Groups["version"].Value); - - // The [dotnet --info] command doesn't work as I expected because it doesn't - // appear to examine the project file when determining the SDK version. - // - // https://github.com/nforgeio/RaspberryDebugger/issues/16 - // - // So, we're just going to use the latest known SDK from our catalog instead. - // This isn't ideal but should work fine for the vast majority of people. - - var targetSdk = (Sdk)null; - var targetSdkVersion = (SemanticVersion)null; - - foreach (var sdkItem in PackageHelper.SdkGoodCatalog.Items - .Where(item => item.IsStandalone && item.Architecture == SdkArchitecture.ARM32)) - { - var sdkVersion = SemanticVersion.Parse(sdkItem.Version); - - if (sdkVersion.Major != netVersion.Major || sdkVersion.Minor != netVersion.Minor) - { - continue; - } - - if (targetSdkVersion == null || sdkVersion > targetSdkVersion) - { - targetSdkVersion = sdkVersion; - targetSdk = new Sdk(sdkItem.Name, sdkItem.Version);; - } - } - - sdkName = targetSdk?.Name; - - // Load [Properties/launchSettings.json] if present to obtain the command line - // arguments and environment variables as well as the target connection. Note - // that we're going to use the profile named for the project and ignore any others. - // - // The launch settings for Console vs. WebApps are a bit different. WebApps include - // a top-level "iisSettings"" property and two profiles: "IIS Express" and the - // profile with the project name. We're going to use the presence of the "iisSettings" - // property to determine that we're dealing with a WebApp and we'll do some additional - // processing based off of the project profile: - // - // 1. Launch the browser if [launchBrowser=true] - // 2. Extract the site port number from [applicationUrl] - // 3. Have the app listen on all IP addresses by adding this environment - // variable when we : - // - // ASPNETCORE_SERVER.URLS=http://0.0.0.0: - - var launchSettingsPath = Path.Combine(projectFolder, "Properties", "launchSettings.json"); - var commandLineArgs = new List(); - var environmentVariables = new Dictionary(); - var isAspNet = false; - var aspPort = 0; - var aspLaunchBrowser = false; - var aspRelativeBrowserUri = "/"; - - if (File.Exists(launchSettingsPath)) - { - var settings = JObject.Parse(File.ReadAllText(launchSettingsPath)); - var profiles = settings.Property("profiles"); - - if (profiles != null) - { - foreach (var profile in ((JObject)profiles.Value).Properties()) - { - if (profile.Name == project.Name) - { - var profileObject = (JObject)profile.Value; - var environmentVariablesObject = (JObject)profileObject.Property("environmentVariables")?.Value; - - commandLineArgs = ParseArgs((string)profileObject.Property("commandLineArgs")?.Value); - - if (environmentVariablesObject != null) - { - foreach (var variable in environmentVariablesObject.Properties()) - { - environmentVariables[variable.Name] = (string)variable.Value; - } - } - - // Extract additional settings for ASPNET projects. - - if (settings.Property("iisSettings") != null) - { - isAspNet = true; - - // Note that we're going to fall back to port 5000 if there are any - // issues parsing the application URL. - - const int fallbackPort = 5000; - - var jProperty = profileObject.Property("applicationUrl"); - - if (jProperty != null && jProperty.Value.Type == JTokenType.String) - { - try - { - var uri = new Uri((string)jProperty.Value); - - aspPort = uri.Port; - - if (!NetHelper.IsValidPort(aspPort)) - { - aspPort = fallbackPort; - } - } - catch - { - aspPort = fallbackPort; - } - } - else - { - aspPort = fallbackPort; - } - - jProperty = profileObject.Property("launchBrowser"); - - if (jProperty != null && jProperty.Value.Type == JTokenType.Boolean) - { - aspLaunchBrowser = (bool)jProperty.Value; - } - } - } - else if (profile.Name == "IIS Express") - { - // For ASPNET apps, this profile may include a "launchUrl" which - // specifies the absolute or relative URI to display in a debug - // browser launched during debugging. - // - // We're going to normalize this as a relative URI and save it - // so we'll be able to launch the browser on the correct page. - - var profileObject = (JObject)profile.Value; - var jProperty = profileObject.Property("launchUrl"); - - if (jProperty != null && jProperty.Value.Type == JTokenType.String) - { - var launchUri = (string)jProperty.Value; - - if (!string.IsNullOrEmpty(launchUri)) - { - try - { - var uri = new Uri(launchUri, UriKind.RelativeOrAbsolute); - - if (uri.IsAbsoluteUri) - { - aspRelativeBrowserUri = uri.PathAndQuery; - } - else - { - aspRelativeBrowserUri = launchUri; - } - } - catch - { - // We'll fall back to "/" for any URI parsing errors. - - aspRelativeBrowserUri = "/"; - } - } - } - } - } - } - } - - // Get the target Raspberry from the debug settings. - - var projects = PackageHelper.ReadRaspberryProjects(solution); - var projectSettings = projects[project.UniqueName]; - var debugEnabled = projectSettings.EnableRemoteDebugging; - var debugConnectionName = projectSettings.RemoteDebugTarget; - - // Determine whether the referenced .NET Core SDK is currently supported. - - var sdk = sdkName == null ? null : PackageHelper.SdkGoodCatalog.Items.SingleOrDefault(item => SemanticVersion.Parse(item.Name) == SemanticVersion.Parse(sdkName) && item.Architecture == SdkArchitecture.ARM32); - - var isSupportedSdkVersion = sdk != null; - - // Determine whether the project is Raspberry compatible. - - var isRaspberryCompatible = isNetCore && - outputType == 1 && // 1=EXE - isSupportedSdkVersion; - - // We need to jump through some hoops to obtain the project GUID. - - var solutionService = RaspberryDebuggerPackage.Instance.SolutionService; - - Covenant.Assert(solutionService.GetProjectOfUniqueName(project.UniqueName, out var hierarchy) == VSConstants.S_OK); - Covenant.Assert(solutionService.GetGuidOfProject(hierarchy, out var projectGuid) == VSConstants.S_OK); - - // Return the properties. - - return new ProjectProperties() - { - Name = project.Name, - FullPath = project.FullName, - Guid = projectGuid, - Configuration = project.ConfigurationManager.ActiveConfiguration.ConfigurationName, - IsNetCore = isNetCore, - SdkVersion = sdk?.Version, - OutputFolder = Path.Combine(projectFolder, project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString()), - OutputFileName = (string)project.Properties.Item("OutputFileName").Value, - IsExecutable = outputType == 1, // 1=EXE - AssemblyName = project.Properties.Item("AssemblyName").Value.ToString(), - DebugEnabled = debugEnabled, - DebugConnectionName = debugConnectionName, - CommandLineArgs = commandLineArgs, - EnvironmentVariables = environmentVariables, - IsSupportedSdkVersion = isSupportedSdkVersion, - IsRaspberryCompatible = isRaspberryCompatible, - IsAspNet = isAspNet, - AspPort = aspPort, - AspLaunchBrowser = aspLaunchBrowser, - AspRelativeBrowserUri = aspRelativeBrowserUri - }; - } - - /// - /// Parses command line arguments from a string, trying to handle things like - /// double and single quotes as well as escaped characters. - /// - /// The source command line or null. - /// The list of parsed arguments. - private static List ParseArgs(string commandLine) - { - commandLine = commandLine ?? string.Empty; - commandLine = commandLine.Trim(); - - var args = new List(); - - if (string.IsNullOrWhiteSpace(commandLine)) - { - return args; - } - - var pos = 0; - - while (pos < commandLine.Length) - { - // Skip past any whitespace. - - if (char.IsWhiteSpace(commandLine[pos])) - { - while (pos < commandLine.Length && char.IsWhiteSpace(commandLine[pos])) - { - pos++; - } - - continue; - } - - var arg = string.Empty; - - switch (commandLine[pos]) - { - case '\'': - - // Single quoted string argument: scan for the terminating single quote. - - pos++; - - while (pos < commandLine.Length && commandLine[pos] != '\'') - { - if (commandLine[pos] == '\\') - { - // Escaped character - - arg += commandLine[pos++]; - - if (pos >= commandLine.Length) - { - throw new ArgumentException($"Invalid escape in: [{commandLine}]"); - } - - arg += commandLine[pos++]; - } - else - { - arg += commandLine[pos++]; - } - } - - pos++; - break; - - case '"': - - // Double quoted string argument: scan for the terminating double quote. - - pos++; - - while (pos < commandLine.Length && commandLine[pos] != '"') - { - if (commandLine[pos] == '\\') - { - // Escaped character - - arg += commandLine[pos++]; - - if (pos >= commandLine.Length) - { - throw new ArgumentException($"Invalid escape in: [{commandLine}]"); - } - - arg += commandLine[pos++]; - } - else - { - arg += commandLine[pos++]; - } - } - - pos++; - break; - - default: - - // Space delimited argument: scan for the terminating whitespace. - - while (pos < commandLine.Length && !char.IsWhiteSpace(commandLine[pos])) - { - arg += commandLine[pos++]; - } - - pos++; - break; - } - - if (arg.Length > 0) - { - args.Add(Regex.Unescape(arg)); - } - } - - return args; - } - - //-------------------------------------------------------------------- - // Instance members - - /// - /// Returns the project's friendly name. - /// - public string Name { get; private set; } - - /// - /// Returns the fullly qualfied path to the project file. - /// - public string FullPath { get; private set; } - - /// - /// Returns the project's GUID. - /// - public Guid Guid { get; private set; } - - /// - /// Indicates that the project targets .NET Core rather than the .NET Framework. - /// - public bool IsNetCore { get; private set; } - - /// - /// Returns the projects .NET Core SDK version. Note that this will probably include - /// just the major and minor versions of the SDK. This may also return null - /// if the SDK version could not be identified. - /// - public string SdkVersion { get; private set; } - - /// - /// Returns true if the project references a supported .NET Core SDK version. - /// - public bool IsSupportedSdkVersion { get; private set; } - - /// - /// Returns the project's build configuration. - /// - public string Configuration { get; private set; } - - /// - /// Returns the fully qualified path to the project's output directory. - /// - public string OutputFolder { get; private set; } - - /// - /// Indicates that the program is an execuable as opposed to something - /// else, like a DLL. - /// - public bool IsExecutable { get; private set; } - - /// - /// Returns the publish runtime. - /// - public string Runtime => "linux-arm"; - - /// - /// Returns the publication folder. - /// - public string PublishFolder => Path.Combine(OutputFolder, Runtime); - - /// - /// Returns the name of the output assembly. - /// - public string AssemblyName { get; private set; } - - /// - /// Returns the name of the output binary file. - /// - public string OutputFileName { get; private set; } - - /// - /// Indicates whether Raspberry debugging is enabled for this project. - /// - public bool DebugEnabled { get; private set; } - - /// - /// Returns the connection name identifying the target Raspberry or null - /// when the default Raspberry connection should be used. - /// - public string DebugConnectionName { get; private set; } - - /// - /// Returns the command line arguments to be passed to the debugged program. - /// - public List CommandLineArgs { get; private set; } - - /// - /// Returns the environment variables to be passed to the debugged program. - /// - public Dictionary EnvironmentVariables { get; private set; } - - /// - /// Indicates whether the project is capable of being deployed and debugged - /// on a Raspberry. - /// - public bool IsRaspberryCompatible { get; private set; } - - /// - /// Indicates that this is an ASPNET project. - /// - public bool IsAspNet { get; private set; } - - /// - /// Returns the port number to expose for the ASPNET apps. - /// - public int AspPort { get; private set; } - - /// - /// Indicates whether a browser should be launched for ASPNET apps. - /// - public bool AspLaunchBrowser { get; private set; } - - /// - /// Returns the relative URI to be displayed in the browser when - /// is true. - /// - public string AspRelativeBrowserUri { get; private set; } - } -} +//----------------------------------------------------------------------------- +// FILE: ProjectProperties.cs +// CONTRIBUTOR: Jeff Lill +// COPYRIGHT: Copyright (c) 2021 by neonFORGE, LLC. 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. +// ReSharper disable UnusedAutoPropertyAccessor.Local +using EnvDTE; +using Microsoft.VisualStudio; +using Microsoft.VisualStudio.Shell; +using Neon.Common; +using Neon.Net; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Diagnostics.Contracts; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; + +namespace RaspberryDebugger.Models.VisualStudio +{ + /// + /// The Visual Studio class properties can only be + /// accessed from the UI thread, so we'll use this class to capture the + /// properties we need on a UI thread so we can use them later on other + /// threads. + /// + internal class ProjectProperties + { + //-------------------------------------------------------------------- + // Static members + + /// + /// Creates a instance holding the + /// necessary properties from a . This must + /// be called on a UI thread. + /// + /// The current solution. + /// The source project. + /// The cloned . + public static ProjectProperties CopyFrom(Solution solution, EnvDTE.Project project) + { + Covenant.Requires(solution != null, nameof(solution)); + Covenant.Requires(project != null, nameof(project)); + + ThreadHelper.ThrowIfNotOnUIThread(); + + if (string.IsNullOrEmpty(project?.FullName)) + { + // We'll see this for unsupported Visual Studio projects and will just + // return project properties indicating this. + + return new ProjectProperties() + { + Name = project?.Name, + FullPath = project?.FullName, + Configuration = null, + IsNetCore = false, + SdkVersion = null, + OutputFolder = null, + OutputFileName = null, + IsExecutable = false, + AssemblyName = null, + DebugEnabled = false, + DebugConnectionName = null, + CommandLineArgs = new List(), + EnvironmentVariables = new Dictionary(), + IsSupportedSdkVersion = false, + IsRaspberryCompatible = false, + IsAspNet = false, + AspPort = 0, + AspLaunchBrowser = false, + AspRelativeBrowserUri = null + }; + } + + var projectFolder = Path.GetDirectoryName(project.FullName); + + // Read the properties we care about from the project. + var targetFrameworkMonikers = (string)project.Properties.Item("TargetFrameworkMoniker").Value; + var outputType = (int)project.Properties.Item("OutputType").Value; + + var monikers = targetFrameworkMonikers.Split(','); + + var isNetCore = monikers[0] == ".NETCoreApp"; + + // Extract the version from the moniker. This looks like: "Version=v5.0" + var versionRegex = new Regex(@"(?[0-9\.]+)$"); + var netVersion = SemanticVersion.Parse(versionRegex.Match(monikers[1]).Groups["version"].Value); + + var targetSdk = (RaspberryDebugger.Connection.Sdk)null; + var targetSdkVersion = (SemanticVersion)null; + + foreach (var sdkItem in PackageHelper.SdkCatalog.Items) + { + var sdkVersion = SemanticVersion.Parse(sdkItem.Name); + + if (sdkVersion.Major != netVersion.Major || + sdkVersion.Minor != netVersion.Minor) + continue; + + if (targetSdkVersion != null && + sdkVersion <= targetSdkVersion) + continue; + + targetSdkVersion = sdkVersion; + targetSdk = new RaspberryDebugger.Connection.Sdk(sdkItem.Name, sdkItem.Architecture); + } + + var sdkName = targetSdk?.Name; + + // Load [Properties/launchSettings.json] if present to obtain the command line + // arguments and environment variables as well as the target connection. Note + // that we're going to use the profile named for the project and ignore any others. + // + // The launch settings for Console vs. WebApps are a bit different. WebApps include + // a top-level "iisSettings"" property and two profiles: "IIS Express" and the + // profile with the project name. We're going to use the presence of the "iisSettings" + // property to determine that we're dealing with a WebApp and we'll do some additional + // processing based off of the project profile: + // + // 1. Launch the browser if [launchBrowser=true] + // 2. Extract the site port number from [applicationUrl] + // 3. Have the app listen on all IP addresses by adding this environment + // variable when we : + // + // ASPNETCORE_SERVER.URLS=http://0.0.0.0: + + var launchSettingsPath = Path.Combine(projectFolder ?? string.Empty, "Properties", "launchSettings.json"); + var commandLineArgs = new List(); + var environmentVariables = new Dictionary(); + var isAspNet = false; + var aspPort = 0; + var aspLaunchBrowser = false; + var aspRelativeBrowserUri = "/"; + + if (File.Exists(launchSettingsPath)) + { + var settings = JObject.Parse(File.ReadAllText(launchSettingsPath)); + var profiles = settings.Property("profiles"); + + if (profiles != null) + { + foreach (var profile in ((JObject)profiles.Value).Properties()) + { + if (profile.Name == project.Name) + { + var profileObject = (JObject)profile.Value; + var environmentVariablesObject = (JObject)profileObject.Property("environmentVariables")?.Value; + + commandLineArgs = ParseArgs((string)profileObject.Property("commandLineArgs")?.Value); + + if (environmentVariablesObject != null) + { + foreach (var variable in environmentVariablesObject.Properties()) + { + environmentVariables[variable.Name] = (string)variable.Value; + } + } + + // Extract additional settings for ASPNET projects. + if (!profileObject.ContainsKey("applicationUrl")) continue; + + isAspNet = true; + + // Note that we're going to fall back to port 5000 if there are any + // issues parsing the application URL. + const int fallbackPort = 5000; + + var jProperty = profileObject.Property("applicationUrl"); + + if (jProperty != null && jProperty.Value.Type == JTokenType.String) + { + try + { + var values = ((string)jProperty.Value).Split(';'); + var uri = new Uri(values.First(s => s.StartsWith("http:"))); + + aspPort = uri.Port; + + if (!NetHelper.IsValidPort(aspPort)) + { + aspPort = fallbackPort; + } + } + catch + { + aspPort = fallbackPort; + } + } + else + { + aspPort = fallbackPort; + } + + jProperty = profileObject.Property("launchBrowser"); + + if (jProperty != null && jProperty.Value.Type == JTokenType.Boolean) + { + aspLaunchBrowser = (bool)jProperty.Value; + } + + aspRelativeBrowserUri = SetLaunchUrl(profileObject); + } + else if (profile.Name == "IIS Express" && aspRelativeBrowserUri == "/") + { + // For ASPNET apps, this profile may include a "launchUrl" which + // specifies the absolute or relative URI to display in a debug + // browser launched during debugging. + // + // We're going to normalize this as a relative URI and save it + // so we'll be able to launch the browser on the correct page. + + var profileObject = (JObject)profile.Value; + aspRelativeBrowserUri = SetLaunchUrl(profileObject); + } + } + + string SetLaunchUrl(JObject profileObject) + { + var jProperty = profileObject.Property("launchUrl"); + + if (jProperty == null || + jProperty.Value.Type != JTokenType.String) + return aspRelativeBrowserUri; + + var launchUri = (string)jProperty.Value; + + if (string.IsNullOrEmpty(launchUri)) return aspRelativeBrowserUri; + + try + { + var uri = new Uri(launchUri, UriKind.RelativeOrAbsolute); + + aspRelativeBrowserUri = uri.IsAbsoluteUri + ? uri.PathAndQuery + : launchUri; + } + catch + { + // We'll fall back to "/" for any URI parsing errors. + aspRelativeBrowserUri = "/"; + } + + return aspRelativeBrowserUri; + } + } + } + + // Get the target Raspberry from the debug settings. + var projects = PackageHelper.ReadRaspberryProjects(solution); + var projectSettings = projects[project.UniqueName]; + var debugEnabled = projectSettings.EnableRemoteDebugging; + var debugConnectionName = projectSettings.RemoteDebugTarget; + + // Determine whether the referenced .NET Core SDK is currently supported. + // The bitness is not important for this - we need only the SDK version + var sdk = sdkName == null + ? null + : PackageHelper.SdkCatalog.Items.Find(item => + SemanticVersion.Parse(item.Name) == SemanticVersion.Parse(sdkName)); + + var isSupportedSdkVersion = sdk != null; + + // Determine whether the project is Raspberry compatible. + var isRaspberryCompatible = isNetCore && + outputType == 1 && // 1=EXE + isSupportedSdkVersion; + + // We need to jump through some hoops to obtain the project GUID. + var solutionService = RaspberryDebuggerPackage.Instance.SolutionService; + + Covenant.Assert(solutionService.GetProjectOfUniqueName(project.UniqueName, out var hierarchy) == VSConstants.S_OK); + Covenant.Assert(solutionService.GetGuidOfProject(hierarchy, out var projectGuid) == VSConstants.S_OK); + + // Return the properties. + return new ProjectProperties() + { + Name = project.Name, + FullPath = project.FullName, + Guid = projectGuid, + Configuration = project.ConfigurationManager.ActiveConfiguration.ConfigurationName, + IsNetCore = isNetCore, + SdkVersion = sdk?.Name, + OutputFolder = Path.Combine(projectFolder, project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString()), + OutputFileName = (string)project.Properties.Item("OutputFileName").Value, + IsExecutable = outputType == 1, // 1=EXE + AssemblyName = project.Properties.Item("AssemblyName").Value.ToString(), + DebugEnabled = debugEnabled, + DebugConnectionName = debugConnectionName, + CommandLineArgs = commandLineArgs, + EnvironmentVariables = environmentVariables, + IsSupportedSdkVersion = isSupportedSdkVersion, + IsRaspberryCompatible = isRaspberryCompatible, + IsAspNet = isAspNet, + AspPort = aspPort, + AspLaunchBrowser = aspLaunchBrowser, + AspRelativeBrowserUri = aspRelativeBrowserUri + }; + } + + /// + /// Parses command line arguments from a string, trying to handle things like + /// double and single quotes as well as escaped characters. + /// + /// The source command line or null. + /// The list of parsed arguments. + private static List ParseArgs(string commandLine) + { + commandLine = commandLine ?? string.Empty; + commandLine = commandLine.Trim(); + + var args = new List(); + + if (string.IsNullOrWhiteSpace(commandLine)) + { + return args; + } + + var pos = 0; + + while (pos < commandLine.Length) + { + // Skip past any whitespace. + + if (char.IsWhiteSpace(commandLine[pos])) + { + while (pos < commandLine.Length && char.IsWhiteSpace(commandLine[pos])) + { + pos++; + } + + continue; + } + + var arg = string.Empty; + + switch (commandLine[pos]) + { + case '\'': + + // Single quoted string argument: scan for the terminating single quote. + + pos++; + + while (pos < commandLine.Length && commandLine[pos] != '\'') + { + if (commandLine[pos] == '\\') + { + // Escaped character + + arg += commandLine[pos++]; + + if (pos >= commandLine.Length) + { + throw new ArgumentException($"Invalid escape in: [{commandLine}]"); + } + + arg += commandLine[pos++]; + } + else + { + arg += commandLine[pos++]; + } + } + + pos++; + break; + + case '"': + + // Double quoted string argument: scan for the terminating double quote. + + pos++; + + while (pos < commandLine.Length && commandLine[pos] != '"') + { + if (commandLine[pos] == '\\') + { + // Escaped character + + arg += commandLine[pos++]; + + if (pos >= commandLine.Length) + { + throw new ArgumentException($"Invalid escape in: [{commandLine}]"); + } + + arg += commandLine[pos++]; + } + else + { + arg += commandLine[pos++]; + } + } + + pos++; + break; + + default: + + // Space delimited argument: scan for the terminating whitespace. + + while (pos < commandLine.Length && !char.IsWhiteSpace(commandLine[pos])) + { + arg += commandLine[pos++]; + } + + pos++; + break; + } + + if (arg.Length > 0) + { + args.Add(Regex.Unescape(arg)); + } + } + + return args; + } + + //-------------------------------------------------------------------- + // Instance members + + /// + /// Returns the project's friendly name. + /// + public string Name { get; private set; } + + /// + /// Returns the fully qualified path to the project file. + /// + public string FullPath { get; private set; } + + /// + /// Returns the project's GUID. + /// + private Guid Guid { get; set; } + + /// + /// Indicates that the project targets .NET Core rather than the .NET Framework. + /// + public bool IsNetCore { get; private set; } + + /// + /// Returns the projects .NET Core SDK version. Note that this will probably include + /// just the major and minor versions of the SDK. This may also return null + /// if the SDK version could not be identified. + /// + public string SdkVersion { get; private set; } + + /// + /// Returns true if the project references a supported .NET Core SDK version. + /// + public bool IsSupportedSdkVersion { get; private set; } + + /// + /// Returns the project's build configuration. + /// + public string Configuration { get; private set; } + + /// + /// Returns the fully qualified path to the project's output directory. + /// + public string OutputFolder { get; private set; } + + /// + /// Indicates that the program is an executable as opposed to something + /// else, like a DLL. + /// + public bool IsExecutable { get; private set; } + + /// + /// Returns the publish runtime. + /// + public string Runtime => "linux-arm"; + + /// + /// Returns the framework version. + /// + public string Framework => null; + + /// + /// Returns the publication folder. + /// + public string PublishFolder => Path.Combine(OutputFolder, Runtime); + + /// + /// Returns the name of the output assembly. + /// + public string AssemblyName { get; private set; } + + /// + /// Returns the name of the output binary file. + /// + private string OutputFileName { get; set; } + + /// + /// Indicates whether Raspberry debugging is enabled for this project. + /// + private bool DebugEnabled { get; set; } + + /// + /// Returns the connection name identifying the target Raspberry or null + /// when the default Raspberry connection should be used. + /// + public string DebugConnectionName { get; private set; } + + /// + /// Returns the command line arguments to be passed to the debugged program. + /// + public List CommandLineArgs { get; private set; } + + /// + /// Returns the environment variables to be passed to the debugged program. + /// + public Dictionary EnvironmentVariables { get; private set; } + + /// + /// Indicates whether the project is capable of being deployed and debugged + /// on a Raspberry. + /// + public bool IsRaspberryCompatible { get; private set; } + + /// + /// Indicates that this is an ASPNET project. + /// + public bool IsAspNet { get; private set; } + + /// + /// Returns the port number to expose for the ASPNET apps. + /// + public int AspPort { get; private set; } + + /// + /// Indicates whether a browser should be launched for ASPNET apps. + /// + public bool AspLaunchBrowser { get; private set; } + + /// + /// Returns the relative URI to be displayed in the browser when + /// is true. + /// + public string AspRelativeBrowserUri { get; private set; } = string.Empty; + } +} diff --git a/RaspberryDebugger/OptionsPages/ConnectionsPage.cs b/RaspberryDebugger/OptionsPages/ConnectionsPage.cs index 651fb6e..23faa6b 100644 --- a/RaspberryDebugger/OptionsPages/ConnectionsPage.cs +++ b/RaspberryDebugger/OptionsPages/ConnectionsPage.cs @@ -15,17 +15,11 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; - using Microsoft.VisualStudio.Shell; -using Microsoft.VisualStudio.Shell.Settings; -namespace RaspberryDebugger +namespace RaspberryDebugger.OptionsPages { /// /// Implements our custom debug connections options page. diff --git a/RaspberryDebugger/OptionsPages/ConnectionsPanel.Designer.cs b/RaspberryDebugger/OptionsPages/ConnectionsPanel.Designer.cs index 2fbf553..3466df8 100644 --- a/RaspberryDebugger/OptionsPages/ConnectionsPanel.Designer.cs +++ b/RaspberryDebugger/OptionsPages/ConnectionsPanel.Designer.cs @@ -15,11 +15,9 @@ // See the License for the specific language governing permissions and // limitations under the License. -using System; using System.ComponentModel; -using System.Net.NetworkInformation; -namespace RaspberryDebugger +namespace RaspberryDebugger.OptionsPages { /// /// Implements the custom debug connections options panel. diff --git a/RaspberryDebugger/OptionsPages/ConnectionsPanel.cs b/RaspberryDebugger/OptionsPages/ConnectionsPanel.cs index f4db573..ce2637f 100644 --- a/RaspberryDebugger/OptionsPages/ConnectionsPanel.cs +++ b/RaspberryDebugger/OptionsPages/ConnectionsPanel.cs @@ -17,37 +17,29 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Data; -using System.IO; using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; - -using Microsoft.VisualStudio.Threading; - using BrightIdeasSoftware; -using Neon.Common; +using RaspberryDebugger.Dialogs; +using RaspberryDebugger.Models.Connection; -namespace RaspberryDebugger +namespace RaspberryDebugger.OptionsPages { /// /// Implements the debug connections options panel. /// internal partial class ConnectionsPanel : UserControl { - private const int spacing = 8; + private const int Spacing = 8; - private const int defaultColumn = 1; - private const int hostColumn = 2; - private const int portColumn = 3; - private const int userColumn = 4; - private const int authColumn = 5; - private const int blankColumn = 6; + private const int DefaultColumn = 1; + private const int HostColumn = 2; + private const int PortColumn = 3; + private const int UserColumn = 4; + private const int AuthColumn = 5; + private const int BlankColumn = 6; - private bool isInitialized = false; + private bool isInitialized; private List connections; /// @@ -67,7 +59,7 @@ public ConnectionsPanel() /// Returns the parent window to be used when displaying message boxes /// and dialogs. /// - private IWin32Window dialogParent => ConnectionsPage.PanelWindow; + private IWin32Window DialogParent => ConnectionsPage.PanelWindow; /// /// Returns the selected connection or null. @@ -109,8 +101,8 @@ private void PiDebugOptionsPanel_Load(object sender, EventArgs args) new OLVColumn() { Name = "Default", - Text = "Default", - DisplayIndex = defaultColumn, + Text = @"Default", + DisplayIndex = DefaultColumn, Width = 60, HeaderTextAlign = HorizontalAlignment.Center, TextAlign = HorizontalAlignment.Center, @@ -121,9 +113,9 @@ private void PiDebugOptionsPanel_Load(object sender, EventArgs args) new OLVColumn() { Name = "Host", - Text = "Host", + Text = @"Host", AspectName = nameof(ConnectionInfo.Name), - DisplayIndex = hostColumn, + DisplayIndex = HostColumn, Width = 200, HeaderTextAlign = HorizontalAlignment.Left, TextAlign = HorizontalAlignment.Left, @@ -134,9 +126,9 @@ private void PiDebugOptionsPanel_Load(object sender, EventArgs args) new OLVColumn() { Name = "Port", - Text = "Port", + Text = @"Port", AspectName = nameof(ConnectionInfo.Port), - DisplayIndex = portColumn, + DisplayIndex = PortColumn, Width = 60, HeaderTextAlign = HorizontalAlignment.Center, TextAlign = HorizontalAlignment.Center, @@ -147,9 +139,9 @@ private void PiDebugOptionsPanel_Load(object sender, EventArgs args) new OLVColumn() { Name = "User", - Text = "User", + Text = @"User", AspectName = nameof(ConnectionInfo.User), - DisplayIndex = userColumn, + DisplayIndex = UserColumn, FillsFreeSpace = true, MaximumWidth = 500, HeaderTextAlign = HorizontalAlignment.Left, @@ -161,9 +153,9 @@ private void PiDebugOptionsPanel_Load(object sender, EventArgs args) new OLVColumn() { Name = "Authentication", - Text = "Authentication", + Text = @"Authentication", AspectName = nameof(ConnectionInfo.Authentication), - DisplayIndex = authColumn, + DisplayIndex = AuthColumn, Width = 100, HeaderTextAlign = HorizontalAlignment.Center, TextAlign = HorizontalAlignment.Center, @@ -175,7 +167,7 @@ private void PiDebugOptionsPanel_Load(object sender, EventArgs args) { Name = "", Text = "", - DisplayIndex = blankColumn, + DisplayIndex = BlankColumn, Width = 0, IsVisible = false, HeaderTextAlign = HorizontalAlignment.Left, @@ -243,18 +235,18 @@ private void SaveConnections() /// The arguments. private void OptionsPanel_SizeChanged(object sender, EventArgs args) { - var buttonLeft = this.Width - addButton.Width - spacing; + var buttonLeft = this.Width - addButton.Width - Spacing; addButton.Left = buttonLeft; editButton.Left = buttonLeft; verifyButton.Left = buttonLeft; removeButton.Left = buttonLeft; - titleLabel.Left = spacing; + titleLabel.Left = Spacing; - connectionsView.Left = spacing; + connectionsView.Left = Spacing; connectionsView.Height = this.Height - connectionsView.Top; - connectionsView.Width = this.Width - addButton.Width - 4 * spacing; + connectionsView.Width = this.Width - addButton.Width - 4 * Spacing; } /// @@ -340,7 +332,7 @@ private void addButton_Click(object sender, EventArgs args) var connectionDialog = new ConnectionDialog(newConnection, edit: false, connections); - if (connectionDialog.ShowDialog(dialogParent) == DialogResult.OK) + if (connectionDialog.ShowDialog(DialogParent) == DialogResult.OK) { connections.Add(newConnection); SaveConnections(); @@ -362,7 +354,7 @@ private void editButton_Click(object sender, EventArgs args) var connectionDialog = new ConnectionDialog(SelectedConnection, edit: true, connections); - if (connectionDialog.ShowDialog(dialogParent) == DialogResult.OK) + if (connectionDialog.ShowDialog(DialogParent) == DialogResult.OK) { SaveConnections(); ReloadConnections(); @@ -392,7 +384,7 @@ await PackageHelper.ExecuteWithProgressAsync("Verify connection", async () => { try { - using (var connection = await Connection.ConnectAsync(currentConnection)) + using (await Connection.Connection.ConnectAsync(currentConnection)) { exception = null; } @@ -412,16 +404,19 @@ await PackageHelper.ExecuteWithProgressAsync("Verify connection", async () => ReloadConnections(); MessageBox.Show(this, - $"[{SelectedConnection.Name}] Connection is OK!", - $"Success", + $@"[{SelectedConnection.Name}] Connection is OK!", + $@"Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show(this, - $"Connection Failed:\r\n\r\n{exception.GetType().FullName}\r\n{exception.Message}\r\n\r\nView the Debug Output for more details.", - $"Connection Failed", + $@"Connection Failed: + {exception.GetType().FullName} + {exception.Message} + View the Debug Output for more details.", + $@"Connection Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); } diff --git a/RaspberryDebugger/PackageHelper.cs b/RaspberryDebugger/PackageHelper.cs index 32b156d..3f5bb72 100644 --- a/RaspberryDebugger/PackageHelper.cs +++ b/RaspberryDebugger/PackageHelper.cs @@ -14,35 +14,35 @@ // 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. - using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics.Contracts; -using System.Drawing; -using System.Data; using System.IO; using System.Linq; -using System.Net; using System.Reflection; -using System.Text; -using System.Threading.Tasks; +using System.Diagnostics; using System.Windows.Forms; +using System.Threading.Tasks; +using System.Collections.Generic; +using System.Diagnostics.Contracts; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; -using Microsoft.VisualStudio.Threading; -using Microsoft.VisualStudio.Utilities; using EnvDTE; using EnvDTE80; +using Microsoft.VisualStudio.Threading; +using Neon.IO; +using Neon.Common; using Newtonsoft.Json; +using Newtonsoft.Json.Converters; -using Neon.Common; -using Neon.IO; - -using Task = System.Threading.Tasks.Task; +using RaspberryDebugger.Dialogs; +using RaspberryDebugger.Extensions; +using RaspberryDebugger.Models.Sdk; +using RaspberryDebugger.Models.Connection; +using RaspberryDebugger.Models.Project; +using RaspberryDebugger.Models.VisualStudio; +using VersionsService = RaspberryDebugger.Web; namespace RaspberryDebugger { @@ -51,17 +51,7 @@ namespace RaspberryDebugger /// internal static class PackageHelper { - private static object syncLock = new object(); - private static SdkCatalog cachedSdkCatalog = null; - private static SdkCatalog cachedGoodSdkCatalog = null; - private static RaspberryCatalog cachedRaspberryCatalog = null; - private static List cachedWorkstationSdks = null; - - /// - /// The path to the %USERPROFILE%\.raspberry folder where the package - /// will persist its settings and other files. - /// - public static readonly string SettingsFolder; + private static SdkCatalog _cachedSdkCatalog; /// /// The path to the folder holding the Raspberry SSH private keys. @@ -71,7 +61,7 @@ internal static class PackageHelper /// /// The path to the JSON file defining the Raspberry Pi connections. /// - public static readonly string ConnectionsPath; + private static readonly string ConnectionsPath; /// /// The name used to prefix logged output and status bar text. @@ -99,15 +89,10 @@ internal static class PackageHelper /// public const string RemoteDebuggerPath = RemoteDebuggerFolder + "/vsdbg"; - /// - /// URI for the project's GitHub issues. - /// - public const string GitHubIssuesUri = "https://github.com/nforgeio/RaspberryDebugger/issues/"; - /// /// Returns the root directory on the Raspberry Pi where the folder where /// program binaries will be uploaded for the named user. Each program will - /// have a subdirectory named for the program. + /// have a sub directory named for the program. /// public static string RemoteDebugBinaryRoot(string username) { @@ -123,84 +108,80 @@ public static SdkCatalog SdkCatalog { get { - lock (syncLock) - { - if (cachedSdkCatalog == null) - { - var assembly = Assembly.GetExecutingAssembly(); + if (_cachedSdkCatalog != null) return _cachedSdkCatalog; - using (var catalogStream = assembly.GetManifestResourceStream("RaspberryDebugger.sdk-catalog.json")) - { - var catalogJson = Encoding.UTF8.GetString(catalogStream.ReadToEnd()); - - cachedSdkCatalog = NeonHelper.JsonDeserialize(catalogJson); - } - } - - return cachedSdkCatalog; + // read newest .net sdks + if(!ReadSdkCatalogToCache()) + { + // if no SDKs present show a message + MessageBoxEx.Show( + "Cannot find any SDK on page: https://dotnet.microsoft.com/en-us/download/dotnet", + "No SDK found", + MessageBoxButtons.OK, + MessageBoxIcon.Error); } + + return _cachedSdkCatalog; } } /// - /// Returns information about the known good .NET Core SDKs, + /// Read SDK links from hosted service + /// with fallback to sdk-catalog.json entries /// - public static SdkCatalog SdkGoodCatalog + /// true if SDKs present + private static bool ReadSdkCatalogToCache() { - get + using (new CursorWait()) { - lock (syncLock) + try { - if (cachedGoodSdkCatalog == null) - { - var assembly = Assembly.GetExecutingAssembly(); - - using (var catalogStream = assembly.GetManifestResourceStream("RaspberryDebugger.sdk-catalog.json")) - { - var catalogJson = Encoding.UTF8.GetString(catalogStream.ReadToEnd()); - - cachedGoodSdkCatalog = NeonHelper.JsonDeserialize(catalogJson); - - // Remove any unusable SDKs from the catalog. - - foreach (var unusable in cachedGoodSdkCatalog.Items.Where(item => item.IsUnusable).ToArray()) - { - cachedGoodSdkCatalog.Items.Remove(unusable); - } - } - } - - return cachedGoodSdkCatalog; + // try to get the catalog thru version feed service + _cachedSdkCatalog = JsonConvert.DeserializeObject( + ThreadHelper.JoinableTaskFactory.Run(async () => + await new VersionsService.Feed() + .ReadAsync() + .WithTimeout(TimeSpan.FromSeconds(2)))); } + catch (Exception) + { + _cachedSdkCatalog = new SdkCatalog(); + } + + if (_cachedSdkCatalog?.Items.Any() == true) return true; + + _cachedSdkCatalog = ReadIntegratedCatalog(); } + + return true; } /// - /// Returns information about the known Raspberry Pie models. + /// Read assembly integrated catalog json /// - public static RaspberryCatalog RaspberryCatalog + /// SdkCatalog with SDK items + private static SdkCatalog ReadIntegratedCatalog() { - get + try { - lock (syncLock) - { - if (cachedRaspberryCatalog != null) - { - return cachedRaspberryCatalog; - } + // try to get the catalog thru own fetch + using var catalogStream = Assembly + .GetExecutingAssembly() + .GetManifestResourceStream("RaspberryDebugger.sdk-catalog.json"); - var assembly = Assembly.GetExecutingAssembly(); - - using (var catalogStream = assembly.GetManifestResourceStream("RaspberryDebugger.raspberry-catalog.json")) - { - var catalogJson = Encoding.UTF8.GetString(catalogStream.ReadToEnd()); - - cachedRaspberryCatalog = NeonHelper.JsonDeserialize(catalogJson); - } - } + var jsonSerializerSettings = new JsonSerializerSettings(); + jsonSerializerSettings.Converters.Add(new StringEnumConverter()); - return cachedRaspberryCatalog; + return JsonConvert.DeserializeObject( + new StreamReader(catalogStream!).ReadToEnd(), + jsonSerializerSettings); } + catch (Exception) + { + _cachedSdkCatalog = new SdkCatalog(); + } + + return _cachedSdkCatalog; } /// @@ -209,74 +190,21 @@ public static RaspberryCatalog RaspberryCatalog static PackageHelper() { // Initialize the settings path and folders. + var settingsFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".raspberry"); - SettingsFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".raspberry"); - - if (!Directory.Exists(SettingsFolder)) + if (!Directory.Exists(settingsFolder)) { - Directory.CreateDirectory(SettingsFolder); + Directory.CreateDirectory(settingsFolder); } - KeysFolder = Path.Combine(SettingsFolder, "keys"); + KeysFolder = Path.Combine(settingsFolder, "keys"); if (!Directory.Exists(KeysFolder)) { Directory.CreateDirectory(KeysFolder); } - ConnectionsPath = Path.Combine(SettingsFolder, "connections.json"); - } - - /// - /// Returns the .NET SDKs currently installed on the workstation. - /// - public static List InstalledWorkstationSdks - { - get - { - lock (syncLock) - { - if (cachedWorkstationSdks != null) - { - return cachedWorkstationSdks; - } - - var response = NeonHelper.ExecuteCapture("dotnet", new object[] { "--list-sdks" }); - - if (response.ExitCode != 0) - { - throw new Exception($"[dotnet --list-sdks] failed with exitcode={response.ExitCode}]"); - } - - // The output will look something like this: - // - // 2.1.403 [C:\Program Files\dotnet\sdk] - // 3.0.100-preview9-014004 [C:\Program Files\dotnet\sdk] - // 3.1.100 [C:\Program Files\dotnet\sdk] - // 3.1.301 [C:\Program Files\dotnet\sdk] - // 3.1.402 [C:\Program Files\dotnet\sdk] - // - // We'll just extract the SDK name (up to the separating space) and lookup the - // version from our catalog. SDKs that aren't in our catalog will have a NULL - // version. - - cachedWorkstationSdks = new List(); - - using (var reader = new StringReader(response.OutputText)) - { - foreach (var line in reader.Lines()) - { - var name = line.Split(' ').First().Trim(); - var sdkItem = PackageHelper.SdkGoodCatalog.Items.SingleOrDefault(item => item.Name == name && item.Architecture == SdkArchitecture.ARM32); - var version = sdkItem?.Version; - - cachedWorkstationSdks.Add(new Sdk(name, version)); - } - } - - return cachedWorkstationSdks; - } - } + ConnectionsPath = Path.Combine(settingsFolder, "connections.json"); } /// @@ -298,19 +226,16 @@ public static List ReadConnections(bool disableLogging = false) return new List(); } - var connections = NeonHelper.JsonDeserialize>(File.ReadAllText(ConnectionsPath)); - - if (connections == null) - { - connections = new List(); - } + var connections = NeonHelper.JsonDeserialize>(File.ReadAllText(ConnectionsPath)) ?? + new List(); // Ensure that at least one connection is marked as default. We'll // select the first one as sorted by name if necessary. - if (connections.Count > 0 && !connections.Any(connection => connection.IsDefault)) { - connections.OrderBy(connection => connection.Name.ToLowerInvariant()).Single().IsDefault = true; + connections.OrderBy(connection => connection.Name + .ToLowerInvariant()) + .Single().IsDefault = true; } return connections; @@ -340,11 +265,10 @@ public static void WriteConnections(List connections, bool disab try { - connections = connections ?? new List(); + connections ??= new List(); // Ensure that at least one connection is marked as default. We'll // select the first one as sorted by name if necessary. - if (connections.Count > 0 && !connections.Any(connection => connection.IsDefault)) { connections.OrderBy(connection => connection.Name.ToLowerInvariant()).First().IsDefault = true; @@ -354,37 +278,12 @@ public static void WriteConnections(List connections, bool disab } catch (Exception e) { - if (!disableLogging) - { - Log.Exception(e); - } + if (!disableLogging) Log.Exception(e); throw; } } - /// - /// Updates the Visual Studio user interface. This is performed asynchronously - /// by default which will result in better performance. - /// - /// - /// Optionally specifies that the update should be performed immediately, - /// before the method returns. - /// - internal static void UpdateVisualStudioUI(bool synchronously = false) - { - ThreadHelper.ThrowIfNotOnUIThread(); - - var vsShell = (IVsUIShell)RaspberryDebuggerPackage.GetGlobalService(typeof(IVsUIShell)); - - if (vsShell != null) - { - var hr = vsShell.UpdateCommandUI(synchronously ? 1 : 0); - - Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hr); - } - } - /// /// Returns the current Visual Studio startup project for a solution. /// @@ -418,7 +317,7 @@ public static Project GetStartupProject(Solution solution) } else if (project.Kind == EnvDTE.Constants.vsProjectKindSolutionItems) { - startupProject = FindInSubprojects(project, projectName); + startupProject = FindInSubProjects(project, projectName); } if (startupProject != null) @@ -433,7 +332,6 @@ public static Project GetStartupProject(Solution solution) /// /// Returns a solution's active project. /// - /// The Visual Studio DTE. /// The active or null for none. /// /// @@ -443,38 +341,17 @@ public static Project GetStartupProject(Solution solution) /// document. /// /// - public static Project GetActiveProject(DTE2 dte) + private static Project GetActiveProject(DTE2 dte) { Covenant.Requires(dte != null, nameof(dte)); + ThreadHelper.ThrowIfNotOnUIThread(); - var activeSolutionProjects = (Array)dte.ActiveSolutionProjects; + var activeSolutionProjects = (Array)dte?.ActiveSolutionProjects; - if (activeSolutionProjects != null && activeSolutionProjects.Length > 0) - { - return (Project)activeSolutionProjects.GetValue(0); - } - else - { - return null; - } - } - - /// - /// Determines whether a project is capable of being debugged on a Raspberry. - /// - /// The solution. - /// The project being tested. - /// true when the project may be debugged on a Raspberry. - public static bool IsProjectRaspberryCompatible(Solution solution, Project project) - { - Covenant.Requires(solution != null, nameof(solution)); - Covenant.Requires(project != null, nameof(project)); - ThreadHelper.ThrowIfNotOnUIThread(); - - var projectProperties = ProjectProperties.CopyFrom(solution, project); - - return projectProperties.IsRaspberryCompatible; + return activeSolutionProjects is { Length: > 0 } + ? (Project)activeSolutionProjects.GetValue(0) + : null; } /// @@ -482,7 +359,7 @@ public static bool IsProjectRaspberryCompatible(Solution solution, Project proje /// a Raspberry. Currently, the project must target .NET Core 3.1 or /// greater and be an executable. /// - /// The Visual Studio DTE. + /// /// /// true if there's an active project and it satisfies the criterion. /// @@ -498,18 +375,18 @@ public static bool IsActiveProjectRaspberryCompatible(DTE2 dte) return false; } - var projectProperties = ProjectProperties.CopyFrom(dte.Solution, activeProject); + var projectProperties = ProjectProperties.CopyFrom(dte?.Solution, activeProject); return projectProperties.IsRaspberryCompatible; } /// - /// Searches a project's subprojects for a project matching a path. + /// Searches a project's sub project for a project matching a path. /// /// The parent project. /// The desired project name. /// The or null. - public static Project FindInSubprojects(Project parentProject, string projectName) + private static Project FindInSubProjects(Project parentProject, string projectName) { ThreadHelper.ThrowIfNotOnUIThread(); @@ -523,24 +400,20 @@ public static Project FindInSubprojects(Project parentProject, string projectNam return parentProject; } + if (parentProject.Kind != EnvDTE.Constants.vsProjectKindSolutionItems) return null; var project = (Project)null; - if (parentProject.Kind == EnvDTE.Constants.vsProjectKindSolutionItems) + // The project is actually a solution folder so recursively + // search any sub projects. + + foreach (ProjectItem projectItem in parentProject.ProjectItems) { - // The project is actually a solution folder so recursively - // search any subprojects. + if (projectItem.SubProject == null) continue; + project = FindInSubProjects(projectItem.SubProject, projectName); - foreach (ProjectItem projectItem in parentProject.ProjectItems) + if (project != null) { - if (projectItem.SubProject != null) - { - project = FindInSubprojects(projectItem.SubProject, projectName); - - if (project != null) - { - break; - } - } + break; } } @@ -554,7 +427,7 @@ public static Project FindInSubprojects(Project parentProject, string projectNam /// The list where discovered projects will be added. /// The parent solution. /// The project or solution folder. - public static void GetSolutionProjects(List solutionProjects, Solution solution, Project project) + private static void GetSolutionProjects(List solutionProjects, Solution solution, Project project) { Covenant.Requires(solutionProjects != null, nameof(solutionProjects)); Covenant.Requires(solution != null, nameof(solution)); @@ -562,7 +435,7 @@ public static void GetSolutionProjects(List solutionProjects, Solution ThreadHelper.ThrowIfNotOnUIThread(); - if (project.Kind == EnvDTE.Constants.vsProjectKindSolutionItems) + if (project?.Kind == EnvDTE.Constants.vsProjectKindSolutionItems) { foreach (ProjectItem projectItem in project.ProjectItems) { @@ -575,7 +448,7 @@ public static void GetSolutionProjects(List solutionProjects, Solution if (projectProperties.IsRaspberryCompatible) { - solutionProjects.Add(project); + solutionProjects?.Add(project); } } } @@ -589,10 +462,9 @@ public static void GetSolutionProjects(List solutionProjects, Solution private static string GetRaspberryProjectsPath(Solution solution) { Covenant.Requires(solution != null); - ThreadHelper.ThrowIfNotOnUIThread(); - return Path.Combine(Path.GetDirectoryName(solution.FullName), ".vs", "raspberry-projects.json"); + return Path.Combine(Path.GetDirectoryName(solution?.FullName) ?? string.Empty, ".vs", "raspberry-projects.json"); } /// @@ -609,14 +481,9 @@ public static RaspberryProjects ReadRaspberryProjects(Solution solution) var path = GetRaspberryProjectsPath(solution); - if (File.Exists(path)) - { - return NeonHelper.JsonDeserialize(File.ReadAllText(path)); - } - else - { - return new RaspberryProjects(); - } + return File.Exists(path) + ? NeonHelper.JsonDeserialize(File.ReadAllText(path)) + : new RaspberryProjects(); } /// @@ -634,12 +501,14 @@ public static void WriteRaspberryProjects(Solution solution, RaspberryProjects p // Prune any projects with GUIDs that are no longer present in // the solution so these don't accumulate. Note that we need to // recurse into solution folders to look for any projects there. - var solutionProjects = new List(); - foreach (Project project in solution.Projects) + if (solution?.Projects != null) { - GetSolutionProjects(solutionProjects, solution, project); + foreach (Project project in solution.Projects) + { + GetSolutionProjects(solutionProjects, solution, project); + } } var solutionProjectIds = new HashSet(); @@ -650,24 +519,20 @@ public static void WriteRaspberryProjects(Solution solution, RaspberryProjects p solutionProjectIds.Add(project.UniqueName); } - foreach (var projectid in projects.Keys) + if (projects?.Keys != null) { - if (!solutionProjectIds.Contains(projectid)) - { - delList.Add(projectid); - } + delList.AddRange((projects.Keys).Where(projectId => !solutionProjectIds.Contains(projectId))); } foreach (var projectId in delList) { - projects.Remove(projectId); + projects?.Remove(projectId); } // Write the file, ensuring that the parent directories exist. - var path = GetRaspberryProjectsPath(solution); - Directory.CreateDirectory(Path.GetDirectoryName(path)); + Directory.CreateDirectory(Path.GetDirectoryName(path) ?? string.Empty); File.WriteAllText(path, NeonHelper.JsonSerialize(projects, Formatting.Indented)); } @@ -683,20 +548,18 @@ public static ProjectSettings GetProjectSettings(Solution solution, Project proj Covenant.Requires(project != null); ThreadHelper.ThrowIfNotOnUIThread(); - var raspberryProjects = ReadRaspberryProjects(solution); - return raspberryProjects[project.UniqueName]; + return raspberryProjects[project?.UniqueName]; } //--------------------------------------------------------------------- // Progress related code + private const string ProgressCaption = "Raspberry Debugger"; - private const string progressCaption = "Raspberry Debugger"; - - private static IVsThreadedWaitDialog2 progressDialog = null; - private static Stack operationStack = new Stack(); - private static string rootDescription; + private static IVsThreadedWaitDialog2 _progressDialog; + private static readonly Stack OperationStack = new(); + private static string _rootDescription; /// /// Executes an asynchronous action that does not return a result within the context of a @@ -713,41 +576,42 @@ public static async Task ExecuteWithProgressAsync(string description, Func await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - if (progressDialog == null) + if (_progressDialog == null) { - Covenant.Assert(operationStack.Count == 0); + Covenant.Assert(OperationStack.Count == 0); - rootDescription = description; - operationStack.Push(description); + _rootDescription = description; + OperationStack.Push(description); - var dialogFactory = (IVsThreadedWaitDialogFactory)RaspberryDebuggerPackage.GetGlobalService((typeof(SVsThreadedWaitDialogFactory))); + var dialogFactory = (IVsThreadedWaitDialogFactory)Package + .GetGlobalService((typeof(SVsThreadedWaitDialogFactory))); - dialogFactory.CreateInstance(out progressDialog); + dialogFactory.CreateInstance(out _progressDialog); - progressDialog.StartWaitDialog( - szWaitCaption: progressCaption, - szWaitMessage: description, - szProgressText: null, - varStatusBmpAnim: null, - szStatusBarText: null, - iDelayToShowDialog: 0, - fIsCancelable: false, - fShowMarqueeProgress: true); + _progressDialog.StartWaitDialog( + szWaitCaption: ProgressCaption, + szWaitMessage: description, + szProgressText: null, + varStatusBmpAnim: null, + szStatusBarText: null, + iDelayToShowDialog: 0, + fIsCancelable: false, + fShowMarqueeProgress: true); } else { - Covenant.Assert(operationStack.Count > 0); + Covenant.Assert(OperationStack.Count > 0); - operationStack.Push(description); + OperationStack.Push(description); - progressDialog.UpdateProgress( - szUpdatedWaitMessage: progressCaption, - szProgressText: description, - szStatusBarText: null, - iCurrentStep: 0, - iTotalSteps: 0, - fDisableCancel: true, - pfCanceled: out var cancelled); + _progressDialog.UpdateProgress( + szUpdatedWaitMessage: ProgressCaption, + szProgressText: description, + szStatusBarText: null, + iCurrentStep: 0, + iTotalSteps: 0, + fDisableCancel: true, + pfCanceled: out _); } var orgCursor = Cursor.Current; @@ -756,7 +620,7 @@ public static async Task ExecuteWithProgressAsync(string description, Func { Cursor.Current = Cursors.WaitCursor; - await action().ConfigureAwait(false); + if (action != null) await action().ConfigureAwait(false); } finally { @@ -764,25 +628,25 @@ public static async Task ExecuteWithProgressAsync(string description, Func Cursor.Current = orgCursor; - var currentDescription = operationStack.Pop(); + OperationStack.Pop(); - if (operationStack.Count == 0) + if (OperationStack.Count == 0) { - progressDialog.EndWaitDialog(out var cancelled); + _progressDialog.EndWaitDialog(out _); - progressDialog = null; - rootDescription = null; + _progressDialog = null; + _rootDescription = null; } else { - progressDialog.UpdateProgress( - szUpdatedWaitMessage: progressCaption, - szProgressText: description, - szStatusBarText: null, - iCurrentStep: 0, - iTotalSteps: 0, - fDisableCancel: true, - pfCanceled: out var cancelled); + _progressDialog.UpdateProgress( + szUpdatedWaitMessage: ProgressCaption, + szProgressText: description, + szStatusBarText: null, + iCurrentStep: 0, + iTotalSteps: 0, + fDisableCancel: true, + pfCanceled: out _); } } } @@ -803,41 +667,42 @@ public static async Task ExecuteWithProgressAsync(string descr await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); - if (progressDialog == null) + if (_progressDialog == null) { - Covenant.Assert(operationStack.Count == 0); + Covenant.Assert(OperationStack.Count == 0); - rootDescription = description; - operationStack.Push(description); + _rootDescription = description; + OperationStack.Push(description); - var dialogFactory = (IVsThreadedWaitDialogFactory)RaspberryDebuggerPackage.GetGlobalService((typeof(SVsThreadedWaitDialogFactory))); + var dialogFactory = (IVsThreadedWaitDialogFactory)Package + .GetGlobalService((typeof(SVsThreadedWaitDialogFactory))); - dialogFactory.CreateInstance(out progressDialog); + dialogFactory.CreateInstance(out _progressDialog); - progressDialog.StartWaitDialog( - szWaitCaption: progressCaption, - szWaitMessage: description, - szProgressText: null, - varStatusBmpAnim: null, - szStatusBarText: $"[{LogName}]{description}", - iDelayToShowDialog: 0, - fIsCancelable: false, - fShowMarqueeProgress: true); + _progressDialog.StartWaitDialog( + szWaitCaption: ProgressCaption, + szWaitMessage: description, + szProgressText: null, + varStatusBmpAnim: null, + szStatusBarText: $"[{LogName}]{description}", + iDelayToShowDialog: 0, + fIsCancelable: false, + fShowMarqueeProgress: true); } else { - Covenant.Assert(operationStack.Count > 0); + Covenant.Assert(OperationStack.Count > 0); - operationStack.Push(description); + OperationStack.Push(description); - progressDialog.UpdateProgress( - szUpdatedWaitMessage: progressCaption, - szProgressText: description, - szStatusBarText: null, - iCurrentStep: 0, - iTotalSteps: 0, - fDisableCancel: true, - pfCanceled: out var cancelled); + _progressDialog.UpdateProgress( + szUpdatedWaitMessage: ProgressCaption, + szProgressText: description, + szStatusBarText: null, + iCurrentStep: 0, + iTotalSteps: 0, + fDisableCancel: true, + pfCanceled: out _); } var orgCursor = Cursor.Current; @@ -845,7 +710,7 @@ public static async Task ExecuteWithProgressAsync(string descr try { Cursor.Current = Cursors.WaitCursor; - + Debug.Assert(action != null, nameof(action) + " != null"); return await action().ConfigureAwait(false); } finally @@ -854,25 +719,25 @@ public static async Task ExecuteWithProgressAsync(string descr Cursor.Current = orgCursor; - var currentDescription = operationStack.Pop(); + var currentDescription = OperationStack.Pop(); - if (operationStack.Count == 0) + if (OperationStack.Count == 0) { - progressDialog.EndWaitDialog(out var cancelled); + _progressDialog.EndWaitDialog(out _); - progressDialog = null; - rootDescription = null; + _progressDialog = null; + _rootDescription = null; } else { - progressDialog.UpdateProgress( - szUpdatedWaitMessage: currentDescription, - szProgressText: null, - szStatusBarText: rootDescription, - iCurrentStep: 0, - iTotalSteps: 0, - fDisableCancel: true, - pfCanceled: out var cancelled); + _progressDialog.UpdateProgress( + szUpdatedWaitMessage: currentDescription, + szProgressText: null, + szStatusBarText: _rootDescription, + iCurrentStep: 0, + iTotalSteps: 0, + fDisableCancel: true, + pfCanceled: out _); } } } diff --git a/RaspberryDebugger/Properties/AssemblyInfo.cs b/RaspberryDebugger/Properties/AssemblyInfo.cs index 55e260a..22bdae8 100644 --- a/RaspberryDebugger/Properties/AssemblyInfo.cs +++ b/RaspberryDebugger/Properties/AssemblyInfo.cs @@ -16,7 +16,6 @@ // limitations under the License. using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -46,5 +45,5 @@ // 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.6.0.0")] -[assembly: AssemblyFileVersion("1.6.0.0")] +[assembly: AssemblyVersion("3.2.0.0")] +[assembly: AssemblyFileVersion("3.2.0.0")] diff --git a/RaspberryDebugger/RaspberryDebugger.csproj b/RaspberryDebugger/RaspberryDebugger.csproj index 7086266..7350d32 100644 --- a/RaspberryDebugger/RaspberryDebugger.csproj +++ b/RaspberryDebugger/RaspberryDebugger.csproj @@ -7,6 +7,12 @@ false + + latest + + + latest + Debug @@ -39,6 +45,7 @@ prompt 4 CS0414 + latest pdbonly @@ -48,8 +55,10 @@ prompt 4 CS0414 + latest + @@ -78,12 +87,15 @@ SettingsDialog.cs + + + @@ -101,6 +113,7 @@ + @@ -121,53 +134,63 @@ + + + + + 15.0.6142705 - 8.0.50728 + 17.2.32505.113 + + + 15.8.243 + + + compile; build; native; contentfiles; analyzers; buildtransitive - - 16.7.30329.38 + 17.2.32505.113 - 16.3.23 + 16.3.36 - + runtime; build; native; contentfiles; analyzers; buildtransitive all - 2.12.0 + 2.18.2 - 2.12.0 + 2.18.2 - 2.12.0 + 2.18.2 - 12.0.3 + 13.0.1 2.9.1 - - 2020.0.1 + + 7.2.3 - 2.6.121 + 2.11.35 @@ -195,6 +218,7 @@ true + 'click') + event = event.replace(stripNameRegex, ''); + return customEvents[event] || event; + } - /** - * ------------------------------------------------------------------------ - * Constants - * ------------------------------------------------------------------------ - */ + const EventHandler = { + on(element, event, handler, delegationFn) { + addHandler(element, event, handler, delegationFn, false); + }, - var NAME$2 = 'carousel'; - var VERSION$2 = '4.3.1'; - var DATA_KEY$2 = 'bs.carousel'; - var EVENT_KEY$2 = "." + DATA_KEY$2; - var DATA_API_KEY$2 = '.data-api'; - var JQUERY_NO_CONFLICT$2 = $.fn[NAME$2]; - var ARROW_LEFT_KEYCODE = 37; // KeyboardEvent.which value for left arrow key + one(element, event, handler, delegationFn) { + addHandler(element, event, handler, delegationFn, true); + }, - var ARROW_RIGHT_KEYCODE = 39; // KeyboardEvent.which value for right arrow key + off(element, originalTypeEvent, handler, delegationFn) { + if (typeof originalTypeEvent !== 'string' || !element) { + return; + } - var TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch + const [delegation, originalHandler, typeEvent] = normalizeParams(originalTypeEvent, handler, delegationFn); + const inNamespace = typeEvent !== originalTypeEvent; + const events = getEvent(element); + const isNamespace = originalTypeEvent.startsWith('.'); - var SWIPE_THRESHOLD = 40; - var Default = { - interval: 5000, + if (typeof originalHandler !== 'undefined') { + // Simplest case: handler is passed, remove that listener ONLY. + if (!events || !events[typeEvent]) { + return; + } + + removeHandler(element, events, typeEvent, originalHandler, delegation ? handler : null); + return; + } + + if (isNamespace) { + Object.keys(events).forEach(elementEvent => { + removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1)); + }); + } + + const storeElementEvent = events[typeEvent] || {}; + Object.keys(storeElementEvent).forEach(keyHandlers => { + const handlerKey = keyHandlers.replace(stripUidRegex, ''); + + if (!inNamespace || originalTypeEvent.includes(handlerKey)) { + const event = storeElementEvent[keyHandlers]; + removeHandler(element, events, typeEvent, event.originalHandler, event.delegationSelector); + } + }); + }, + + trigger(element, event, args) { + if (typeof event !== 'string' || !element) { + return null; + } + + const $ = getjQuery(); + const typeEvent = getTypeEvent(event); + const inNamespace = event !== typeEvent; + const isNative = nativeEvents.has(typeEvent); + let jQueryEvent; + let bubbles = true; + let nativeDispatch = true; + let defaultPrevented = false; + let evt = null; + + if (inNamespace && $) { + jQueryEvent = $.Event(event, args); + $(element).trigger(jQueryEvent); + bubbles = !jQueryEvent.isPropagationStopped(); + nativeDispatch = !jQueryEvent.isImmediatePropagationStopped(); + defaultPrevented = jQueryEvent.isDefaultPrevented(); + } + + if (isNative) { + evt = document.createEvent('HTMLEvents'); + evt.initEvent(typeEvent, bubbles, true); + } else { + evt = new CustomEvent(event, { + bubbles, + cancelable: true + }); + } // merge custom information in our event + + + if (typeof args !== 'undefined') { + Object.keys(args).forEach(key => { + Object.defineProperty(evt, key, { + get() { + return args[key]; + } + + }); + }); + } + + if (defaultPrevented) { + evt.preventDefault(); + } + + if (nativeDispatch) { + element.dispatchEvent(evt); + } + + if (evt.defaultPrevented && typeof jQueryEvent !== 'undefined') { + jQueryEvent.preventDefault(); + } + + return evt; + } + + }; + + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): dom/data.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + + /** + * ------------------------------------------------------------------------ + * Constants + * ------------------------------------------------------------------------ + */ + const elementMap = new Map(); + var Data = { + set(element, key, instance) { + if (!elementMap.has(element)) { + elementMap.set(element, new Map()); + } + + const instanceMap = elementMap.get(element); // make it clear we only want one instance per element + // can be removed later when multiple key/instances are fine to be used + + if (!instanceMap.has(key) && instanceMap.size !== 0) { + // eslint-disable-next-line no-console + console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(instanceMap.keys())[0]}.`); + return; + } + + instanceMap.set(key, instance); + }, + + get(element, key) { + if (elementMap.has(element)) { + return elementMap.get(element).get(key) || null; + } + + return null; + }, + + remove(element, key) { + if (!elementMap.has(element)) { + return; + } + + const instanceMap = elementMap.get(element); + instanceMap.delete(key); // free up element references if there are no instances left for an element + + if (instanceMap.size === 0) { + elementMap.delete(element); + } + } + + }; + + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): base-component.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + /** + * ------------------------------------------------------------------------ + * Constants + * ------------------------------------------------------------------------ + */ + + const VERSION = '5.1.0'; + + class BaseComponent { + constructor(element) { + element = getElement(element); + + if (!element) { + return; + } + + this._element = element; + Data.set(this._element, this.constructor.DATA_KEY, this); + } + + dispose() { + Data.remove(this._element, this.constructor.DATA_KEY); + EventHandler.off(this._element, this.constructor.EVENT_KEY); + Object.getOwnPropertyNames(this).forEach(propertyName => { + this[propertyName] = null; + }); + } + + _queueCallback(callback, element, isAnimated = true) { + executeAfterTransition(callback, element, isAnimated); + } + /** Static */ + + + static getInstance(element) { + return Data.get(getElement(element), this.DATA_KEY); + } + + static getOrCreateInstance(element, config = {}) { + return this.getInstance(element) || new this(element, typeof config === 'object' ? config : null); + } + + static get VERSION() { + return VERSION; + } + + static get NAME() { + throw new Error('You have to implement the static method "NAME", for each component!'); + } + + static get DATA_KEY() { + return `bs.${this.NAME}`; + } + + static get EVENT_KEY() { + return `.${this.DATA_KEY}`; + } + + } + + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): util/component-functions.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + + const enableDismissTrigger = (component, method = 'hide') => { + const clickEvent = `click.dismiss${component.EVENT_KEY}`; + const name = component.NAME; + EventHandler.on(document, clickEvent, `[data-bs-dismiss="${name}"]`, function (event) { + if (['A', 'AREA'].includes(this.tagName)) { + event.preventDefault(); + } + + if (isDisabled(this)) { + return; + } + + const target = getElementFromSelector(this) || this.closest(`.${name}`); + const instance = component.getOrCreateInstance(target); // Method argument is left, for Alert and only, as it doesn't implement the 'hide' method + + instance[method](); + }); + }; + + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): alert.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + /** + * ------------------------------------------------------------------------ + * Constants + * ------------------------------------------------------------------------ + */ + + const NAME$d = 'alert'; + const DATA_KEY$c = 'bs.alert'; + const EVENT_KEY$c = `.${DATA_KEY$c}`; + const EVENT_CLOSE = `close${EVENT_KEY$c}`; + const EVENT_CLOSED = `closed${EVENT_KEY$c}`; + const CLASS_NAME_FADE$5 = 'fade'; + const CLASS_NAME_SHOW$8 = 'show'; + /** + * ------------------------------------------------------------------------ + * Class Definition + * ------------------------------------------------------------------------ + */ + + class Alert extends BaseComponent { + // Getters + static get NAME() { + return NAME$d; + } // Public + + + close() { + const closeEvent = EventHandler.trigger(this._element, EVENT_CLOSE); + + if (closeEvent.defaultPrevented) { + return; + } + + this._element.classList.remove(CLASS_NAME_SHOW$8); + + const isAnimated = this._element.classList.contains(CLASS_NAME_FADE$5); + + this._queueCallback(() => this._destroyElement(), this._element, isAnimated); + } // Private + + + _destroyElement() { + this._element.remove(); + + EventHandler.trigger(this._element, EVENT_CLOSED); + this.dispose(); + } // Static + + + static jQueryInterface(config) { + return this.each(function () { + const data = Alert.getOrCreateInstance(this); + + if (typeof config !== 'string') { + return; + } + + if (data[config] === undefined || config.startsWith('_') || config === 'constructor') { + throw new TypeError(`No method named "${config}"`); + } + + data[config](this); + }); + } + + } + /** + * ------------------------------------------------------------------------ + * Data Api implementation + * ------------------------------------------------------------------------ + */ + + + enableDismissTrigger(Alert, 'close'); + /** + * ------------------------------------------------------------------------ + * jQuery + * ------------------------------------------------------------------------ + * add .Alert to jQuery only if jQuery is present + */ + + defineJQueryPlugin(Alert); + + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): button.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + /** + * ------------------------------------------------------------------------ + * Constants + * ------------------------------------------------------------------------ + */ + + const NAME$c = 'button'; + const DATA_KEY$b = 'bs.button'; + const EVENT_KEY$b = `.${DATA_KEY$b}`; + const DATA_API_KEY$7 = '.data-api'; + const CLASS_NAME_ACTIVE$3 = 'active'; + const SELECTOR_DATA_TOGGLE$5 = '[data-bs-toggle="button"]'; + const EVENT_CLICK_DATA_API$6 = `click${EVENT_KEY$b}${DATA_API_KEY$7}`; + /** + * ------------------------------------------------------------------------ + * Class Definition + * ------------------------------------------------------------------------ + */ + + class Button extends BaseComponent { + // Getters + static get NAME() { + return NAME$c; + } // Public + + + toggle() { + // Toggle class and sync the `aria-pressed` attribute with the return value of the `.toggle()` method + this._element.setAttribute('aria-pressed', this._element.classList.toggle(CLASS_NAME_ACTIVE$3)); + } // Static + + + static jQueryInterface(config) { + return this.each(function () { + const data = Button.getOrCreateInstance(this); + + if (config === 'toggle') { + data[config](); + } + }); + } + + } + /** + * ------------------------------------------------------------------------ + * Data Api implementation + * ------------------------------------------------------------------------ + */ + + + EventHandler.on(document, EVENT_CLICK_DATA_API$6, SELECTOR_DATA_TOGGLE$5, event => { + event.preventDefault(); + const button = event.target.closest(SELECTOR_DATA_TOGGLE$5); + const data = Button.getOrCreateInstance(button); + data.toggle(); + }); + /** + * ------------------------------------------------------------------------ + * jQuery + * ------------------------------------------------------------------------ + * add .Button to jQuery only if jQuery is present + */ + + defineJQueryPlugin(Button); + + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): dom/manipulator.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + function normalizeData(val) { + if (val === 'true') { + return true; + } + + if (val === 'false') { + return false; + } + + if (val === Number(val).toString()) { + return Number(val); + } + + if (val === '' || val === 'null') { + return null; + } + + return val; + } + + function normalizeDataKey(key) { + return key.replace(/[A-Z]/g, chr => `-${chr.toLowerCase()}`); + } + + const Manipulator = { + setDataAttribute(element, key, value) { + element.setAttribute(`data-bs-${normalizeDataKey(key)}`, value); + }, + + removeDataAttribute(element, key) { + element.removeAttribute(`data-bs-${normalizeDataKey(key)}`); + }, + + getDataAttributes(element) { + if (!element) { + return {}; + } + + const attributes = {}; + Object.keys(element.dataset).filter(key => key.startsWith('bs')).forEach(key => { + let pureKey = key.replace(/^bs/, ''); + pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length); + attributes[pureKey] = normalizeData(element.dataset[key]); + }); + return attributes; + }, + + getDataAttribute(element, key) { + return normalizeData(element.getAttribute(`data-bs-${normalizeDataKey(key)}`)); + }, + + offset(element) { + const rect = element.getBoundingClientRect(); + return { + top: rect.top + window.pageYOffset, + left: rect.left + window.pageXOffset + }; + }, + + position(element) { + return { + top: element.offsetTop, + left: element.offsetLeft + }; + } + + }; + + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): dom/selector-engine.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + const NODE_TEXT = 3; + const SelectorEngine = { + find(selector, element = document.documentElement) { + return [].concat(...Element.prototype.querySelectorAll.call(element, selector)); + }, + + findOne(selector, element = document.documentElement) { + return Element.prototype.querySelector.call(element, selector); + }, + + children(element, selector) { + return [].concat(...element.children).filter(child => child.matches(selector)); + }, + + parents(element, selector) { + const parents = []; + let ancestor = element.parentNode; + + while (ancestor && ancestor.nodeType === Node.ELEMENT_NODE && ancestor.nodeType !== NODE_TEXT) { + if (ancestor.matches(selector)) { + parents.push(ancestor); + } + + ancestor = ancestor.parentNode; + } + + return parents; + }, + + prev(element, selector) { + let previous = element.previousElementSibling; + + while (previous) { + if (previous.matches(selector)) { + return [previous]; + } + + previous = previous.previousElementSibling; + } + + return []; + }, + + next(element, selector) { + let next = element.nextElementSibling; + + while (next) { + if (next.matches(selector)) { + return [next]; + } + + next = next.nextElementSibling; + } + + return []; + }, + + focusableChildren(element) { + const focusables = ['a', 'button', 'input', 'textarea', 'select', 'details', '[tabindex]', '[contenteditable="true"]'].map(selector => `${selector}:not([tabindex^="-"])`).join(', '); + return this.find(focusables, element).filter(el => !isDisabled(el) && isVisible(el)); + } + + }; + + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): carousel.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + /** + * ------------------------------------------------------------------------ + * Constants + * ------------------------------------------------------------------------ + */ + + const NAME$b = 'carousel'; + const DATA_KEY$a = 'bs.carousel'; + const EVENT_KEY$a = `.${DATA_KEY$a}`; + const DATA_API_KEY$6 = '.data-api'; + const ARROW_LEFT_KEY = 'ArrowLeft'; + const ARROW_RIGHT_KEY = 'ArrowRight'; + const TOUCHEVENT_COMPAT_WAIT = 500; // Time for mouse compat events to fire after touch + + const SWIPE_THRESHOLD = 40; + const Default$a = { + interval: 5000, keyboard: true, slide: false, pause: 'hover', wrap: true, touch: true }; - var DefaultType = { + const DefaultType$a = { interval: '(number|boolean)', keyboard: 'boolean', slide: '(boolean|string)', @@ -576,4007 +1096,3783 @@ wrap: 'boolean', touch: 'boolean' }; - var Direction = { - NEXT: 'next', - PREV: 'prev', - LEFT: 'left', - RIGHT: 'right' - }; - var Event$2 = { - SLIDE: "slide" + EVENT_KEY$2, - SLID: "slid" + EVENT_KEY$2, - KEYDOWN: "keydown" + EVENT_KEY$2, - MOUSEENTER: "mouseenter" + EVENT_KEY$2, - MOUSELEAVE: "mouseleave" + EVENT_KEY$2, - TOUCHSTART: "touchstart" + EVENT_KEY$2, - TOUCHMOVE: "touchmove" + EVENT_KEY$2, - TOUCHEND: "touchend" + EVENT_KEY$2, - POINTERDOWN: "pointerdown" + EVENT_KEY$2, - POINTERUP: "pointerup" + EVENT_KEY$2, - DRAG_START: "dragstart" + EVENT_KEY$2, - LOAD_DATA_API: "load" + EVENT_KEY$2 + DATA_API_KEY$2, - CLICK_DATA_API: "click" + EVENT_KEY$2 + DATA_API_KEY$2 - }; - var ClassName$2 = { - CAROUSEL: 'carousel', - ACTIVE: 'active', - SLIDE: 'slide', - RIGHT: 'carousel-item-right', - LEFT: 'carousel-item-left', - NEXT: 'carousel-item-next', - PREV: 'carousel-item-prev', - ITEM: 'carousel-item', - POINTER_EVENT: 'pointer-event' + const ORDER_NEXT = 'next'; + const ORDER_PREV = 'prev'; + const DIRECTION_LEFT = 'left'; + const DIRECTION_RIGHT = 'right'; + const KEY_TO_DIRECTION = { + [ARROW_LEFT_KEY]: DIRECTION_RIGHT, + [ARROW_RIGHT_KEY]: DIRECTION_LEFT }; - var Selector$2 = { - ACTIVE: '.active', - ACTIVE_ITEM: '.active.carousel-item', - ITEM: '.carousel-item', - ITEM_IMG: '.carousel-item img', - NEXT_PREV: '.carousel-item-next, .carousel-item-prev', - INDICATORS: '.carousel-indicators', - DATA_SLIDE: '[data-slide], [data-slide-to]', - DATA_RIDE: '[data-ride="carousel"]' - }; - var PointerType = { - TOUCH: 'touch', - PEN: 'pen' - /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ - */ + const EVENT_SLIDE = `slide${EVENT_KEY$a}`; + const EVENT_SLID = `slid${EVENT_KEY$a}`; + const EVENT_KEYDOWN = `keydown${EVENT_KEY$a}`; + const EVENT_MOUSEENTER = `mouseenter${EVENT_KEY$a}`; + const EVENT_MOUSELEAVE = `mouseleave${EVENT_KEY$a}`; + const EVENT_TOUCHSTART = `touchstart${EVENT_KEY$a}`; + const EVENT_TOUCHMOVE = `touchmove${EVENT_KEY$a}`; + const EVENT_TOUCHEND = `touchend${EVENT_KEY$a}`; + const EVENT_POINTERDOWN = `pointerdown${EVENT_KEY$a}`; + const EVENT_POINTERUP = `pointerup${EVENT_KEY$a}`; + const EVENT_DRAG_START = `dragstart${EVENT_KEY$a}`; + const EVENT_LOAD_DATA_API$2 = `load${EVENT_KEY$a}${DATA_API_KEY$6}`; + const EVENT_CLICK_DATA_API$5 = `click${EVENT_KEY$a}${DATA_API_KEY$6}`; + const CLASS_NAME_CAROUSEL = 'carousel'; + const CLASS_NAME_ACTIVE$2 = 'active'; + const CLASS_NAME_SLIDE = 'slide'; + const CLASS_NAME_END = 'carousel-item-end'; + const CLASS_NAME_START = 'carousel-item-start'; + const CLASS_NAME_NEXT = 'carousel-item-next'; + const CLASS_NAME_PREV = 'carousel-item-prev'; + const CLASS_NAME_POINTER_EVENT = 'pointer-event'; + const SELECTOR_ACTIVE$1 = '.active'; + const SELECTOR_ACTIVE_ITEM = '.active.carousel-item'; + const SELECTOR_ITEM = '.carousel-item'; + const SELECTOR_ITEM_IMG = '.carousel-item img'; + const SELECTOR_NEXT_PREV = '.carousel-item-next, .carousel-item-prev'; + const SELECTOR_INDICATORS = '.carousel-indicators'; + const SELECTOR_INDICATOR = '[data-bs-target]'; + const SELECTOR_DATA_SLIDE = '[data-bs-slide], [data-bs-slide-to]'; + const SELECTOR_DATA_RIDE = '[data-bs-ride="carousel"]'; + const POINTER_TYPE_TOUCH = 'touch'; + const POINTER_TYPE_PEN = 'pen'; + /** + * ------------------------------------------------------------------------ + * Class Definition + * ------------------------------------------------------------------------ + */ + + class Carousel extends BaseComponent { + constructor(element, config) { + super(element); + this._items = null; + this._interval = null; + this._activeElement = null; + this._isPaused = false; + this._isSliding = false; + this.touchTimeout = null; + this.touchStartX = 0; + this.touchDeltaX = 0; + this._config = this._getConfig(config); + this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element); + this._touchSupported = 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0; + this._pointerEvent = Boolean(window.PointerEvent); + + this._addEventListeners(); + } // Getters + + + static get Default() { + return Default$a; + } + + static get NAME() { + return NAME$b; + } // Public + + + next() { + this._slide(ORDER_NEXT); + } + + nextWhenVisible() { + // Don't call next when the page isn't visible + // or the carousel or its parent isn't visible + if (!document.hidden && isVisible(this._element)) { + this.next(); + } + } + + prev() { + this._slide(ORDER_PREV); + } + + pause(event) { + if (!event) { + this._isPaused = true; + } + + if (SelectorEngine.findOne(SELECTOR_NEXT_PREV, this._element)) { + triggerTransitionEnd(this._element); + this.cycle(true); + } + + clearInterval(this._interval); + this._interval = null; + } + + cycle(event) { + if (!event) { + this._isPaused = false; + } + + if (this._interval) { + clearInterval(this._interval); + this._interval = null; + } + + if (this._config && this._config.interval && !this._isPaused) { + this._updateInterval(); + + this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval); + } + } + + to(index) { + this._activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element); + + const activeIndex = this._getItemIndex(this._activeElement); + + if (index > this._items.length - 1 || index < 0) { + return; + } + + if (this._isSliding) { + EventHandler.one(this._element, EVENT_SLID, () => this.to(index)); + return; + } + + if (activeIndex === index) { + this.pause(); + this.cycle(); + return; + } - }; + const order = index > activeIndex ? ORDER_NEXT : ORDER_PREV; - var Carousel = - /*#__PURE__*/ - function () { - function Carousel(element, config) { - this._items = null; - this._interval = null; - this._activeElement = null; - this._isPaused = false; - this._isSliding = false; - this.touchTimeout = null; - this.touchStartX = 0; + this._slide(order, this._items[index]); + } // Private + + + _getConfig(config) { + config = { ...Default$a, + ...Manipulator.getDataAttributes(this._element), + ...(typeof config === 'object' ? config : {}) + }; + typeCheckConfig(NAME$b, config, DefaultType$a); + return config; + } + + _handleSwipe() { + const absDeltax = Math.abs(this.touchDeltaX); + + if (absDeltax <= SWIPE_THRESHOLD) { + return; + } + + const direction = absDeltax / this.touchDeltaX; this.touchDeltaX = 0; - this._config = this._getConfig(config); - this._element = element; - this._indicatorsElement = this._element.querySelector(Selector$2.INDICATORS); - this._touchSupported = 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0; - this._pointerEvent = Boolean(window.PointerEvent || window.MSPointerEvent); - this._addEventListeners(); - } // Getters + if (!direction) { + return; + } + this._slide(direction > 0 ? DIRECTION_RIGHT : DIRECTION_LEFT); + } - var _proto = Carousel.prototype; + _addEventListeners() { + if (this._config.keyboard) { + EventHandler.on(this._element, EVENT_KEYDOWN, event => this._keydown(event)); + } - // Public - _proto.next = function next() { - if (!this._isSliding) { - this._slide(Direction.NEXT); + if (this._config.pause === 'hover') { + EventHandler.on(this._element, EVENT_MOUSEENTER, event => this.pause(event)); + EventHandler.on(this._element, EVENT_MOUSELEAVE, event => this.cycle(event)); } - }; - _proto.nextWhenVisible = function nextWhenVisible() { - // Don't call next when the page isn't visible - // or the carousel or its parent isn't visible - if (!document.hidden && $(this._element).is(':visible') && $(this._element).css('visibility') !== 'hidden') { - this.next(); + if (this._config.touch && this._touchSupported) { + this._addTouchEventListeners(); } - }; + } + + _addTouchEventListeners() { + const start = event => { + if (this._pointerEvent && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH)) { + this.touchStartX = event.clientX; + } else if (!this._pointerEvent) { + this.touchStartX = event.touches[0].clientX; + } + }; + + const move = event => { + // ensure swiping with one touch and not pinching + this.touchDeltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this.touchStartX; + }; + + const end = event => { + if (this._pointerEvent && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH)) { + this.touchDeltaX = event.clientX - this.touchStartX; + } + + this._handleSwipe(); + + if (this._config.pause === 'hover') { + // If it's a touch-enabled device, mouseenter/leave are fired as + // part of the mouse compatibility events on first tap - the carousel + // would stop cycling until user tapped out of it; + // here, we listen for touchend, explicitly pause the carousel + // (as if it's the second time we tap on it, mouseenter compat event + // is NOT fired) and after a timeout (to allow for mouse compatibility + // events to fire) we explicitly restart cycling + this.pause(); + + if (this.touchTimeout) { + clearTimeout(this.touchTimeout); + } + + this.touchTimeout = setTimeout(event => this.cycle(event), TOUCHEVENT_COMPAT_WAIT + this._config.interval); + } + }; + + SelectorEngine.find(SELECTOR_ITEM_IMG, this._element).forEach(itemImg => { + EventHandler.on(itemImg, EVENT_DRAG_START, e => e.preventDefault()); + }); + + if (this._pointerEvent) { + EventHandler.on(this._element, EVENT_POINTERDOWN, event => start(event)); + EventHandler.on(this._element, EVENT_POINTERUP, event => end(event)); - _proto.prev = function prev() { - if (!this._isSliding) { - this._slide(Direction.PREV); + this._element.classList.add(CLASS_NAME_POINTER_EVENT); + } else { + EventHandler.on(this._element, EVENT_TOUCHSTART, event => start(event)); + EventHandler.on(this._element, EVENT_TOUCHMOVE, event => move(event)); + EventHandler.on(this._element, EVENT_TOUCHEND, event => end(event)); } - }; + } - _proto.pause = function pause(event) { - if (!event) { - this._isPaused = true; + _keydown(event) { + if (/input|textarea/i.test(event.target.tagName)) { + return; } - if (this._element.querySelector(Selector$2.NEXT_PREV)) { - Util.triggerTransitionEnd(this._element); - this.cycle(true); + const direction = KEY_TO_DIRECTION[event.key]; + + if (direction) { + event.preventDefault(); + + this._slide(direction); } + } - clearInterval(this._interval); - this._interval = null; - }; + _getItemIndex(element) { + this._items = element && element.parentNode ? SelectorEngine.find(SELECTOR_ITEM, element.parentNode) : []; + return this._items.indexOf(element); + } - _proto.cycle = function cycle(event) { - if (!event) { - this._isPaused = false; + _getItemByOrder(order, activeElement) { + const isNext = order === ORDER_NEXT; + return getNextActiveElement(this._items, activeElement, isNext, this._config.wrap); + } + + _triggerSlideEvent(relatedTarget, eventDirectionName) { + const targetIndex = this._getItemIndex(relatedTarget); + + const fromIndex = this._getItemIndex(SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element)); + + return EventHandler.trigger(this._element, EVENT_SLIDE, { + relatedTarget, + direction: eventDirectionName, + from: fromIndex, + to: targetIndex + }); + } + + _setActiveIndicatorElement(element) { + if (this._indicatorsElement) { + const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE$1, this._indicatorsElement); + activeIndicator.classList.remove(CLASS_NAME_ACTIVE$2); + activeIndicator.removeAttribute('aria-current'); + const indicators = SelectorEngine.find(SELECTOR_INDICATOR, this._indicatorsElement); + + for (let i = 0; i < indicators.length; i++) { + if (Number.parseInt(indicators[i].getAttribute('data-bs-slide-to'), 10) === this._getItemIndex(element)) { + indicators[i].classList.add(CLASS_NAME_ACTIVE$2); + indicators[i].setAttribute('aria-current', 'true'); + break; + } + } } + } - if (this._interval) { - clearInterval(this._interval); - this._interval = null; + _updateInterval() { + const element = this._activeElement || SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element); + + if (!element) { + return; } - if (this._config.interval && !this._isPaused) { - this._interval = setInterval((document.visibilityState ? this.nextWhenVisible : this.next).bind(this), this._config.interval); + const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10); + + if (elementInterval) { + this._config.defaultInterval = this._config.defaultInterval || this._config.interval; + this._config.interval = elementInterval; + } else { + this._config.interval = this._config.defaultInterval || this._config.interval; } - }; + } - _proto.to = function to(index) { - var _this = this; + _slide(directionOrOrder, element) { + const order = this._directionToOrder(directionOrOrder); - this._activeElement = this._element.querySelector(Selector$2.ACTIVE_ITEM); + const activeElement = SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element); - var activeIndex = this._getItemIndex(this._activeElement); + const activeElementIndex = this._getItemIndex(activeElement); - if (index > this._items.length - 1 || index < 0) { + const nextElement = element || this._getItemByOrder(order, activeElement); + + const nextElementIndex = this._getItemIndex(nextElement); + + const isCycling = Boolean(this._interval); + const isNext = order === ORDER_NEXT; + const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END; + const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV; + + const eventDirectionName = this._orderToDirection(order); + + if (nextElement && nextElement.classList.contains(CLASS_NAME_ACTIVE$2)) { + this._isSliding = false; return; } if (this._isSliding) { - $(this._element).one(Event$2.SLID, function () { - return _this.to(index); - }); return; } - if (activeIndex === index) { + const slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName); + + if (slideEvent.defaultPrevented) { + return; + } + + if (!activeElement || !nextElement) { + // Some weirdness is happening, so we bail + return; + } + + this._isSliding = true; + + if (isCycling) { this.pause(); + } + + this._setActiveIndicatorElement(nextElement); + + this._activeElement = nextElement; + + const triggerSlidEvent = () => { + EventHandler.trigger(this._element, EVENT_SLID, { + relatedTarget: nextElement, + direction: eventDirectionName, + from: activeElementIndex, + to: nextElementIndex + }); + }; + + if (this._element.classList.contains(CLASS_NAME_SLIDE)) { + nextElement.classList.add(orderClassName); + reflow(nextElement); + activeElement.classList.add(directionalClassName); + nextElement.classList.add(directionalClassName); + + const completeCallBack = () => { + nextElement.classList.remove(directionalClassName, orderClassName); + nextElement.classList.add(CLASS_NAME_ACTIVE$2); + activeElement.classList.remove(CLASS_NAME_ACTIVE$2, orderClassName, directionalClassName); + this._isSliding = false; + setTimeout(triggerSlidEvent, 0); + }; + + this._queueCallback(completeCallBack, activeElement, true); + } else { + activeElement.classList.remove(CLASS_NAME_ACTIVE$2); + nextElement.classList.add(CLASS_NAME_ACTIVE$2); + this._isSliding = false; + triggerSlidEvent(); + } + + if (isCycling) { this.cycle(); + } + } + + _directionToOrder(direction) { + if (![DIRECTION_RIGHT, DIRECTION_LEFT].includes(direction)) { + return direction; + } + + if (isRTL()) { + return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT; + } + + return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV; + } + + _orderToDirection(order) { + if (![ORDER_NEXT, ORDER_PREV].includes(order)) { + return order; + } + + if (isRTL()) { + return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT; + } + + return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT; + } // Static + + + static carouselInterface(element, config) { + const data = Carousel.getOrCreateInstance(element, config); + let { + _config + } = data; + + if (typeof config === 'object') { + _config = { ..._config, + ...config + }; + } + + const action = typeof config === 'string' ? config : _config.slide; + + if (typeof config === 'number') { + data.to(config); + } else if (typeof action === 'string') { + if (typeof data[action] === 'undefined') { + throw new TypeError(`No method named "${action}"`); + } + + data[action](); + } else if (_config.interval && _config.ride) { + data.pause(); + data.cycle(); + } + } + + static jQueryInterface(config) { + return this.each(function () { + Carousel.carouselInterface(this, config); + }); + } + + static dataApiClickHandler(event) { + const target = getElementFromSelector(this); + + if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) { return; } - var direction = index > activeIndex ? Direction.NEXT : Direction.PREV; + const config = { ...Manipulator.getDataAttributes(target), + ...Manipulator.getDataAttributes(this) + }; + const slideIndex = this.getAttribute('data-bs-slide-to'); - this._slide(direction, this._items[index]); - }; + if (slideIndex) { + config.interval = false; + } - _proto.dispose = function dispose() { - $(this._element).off(EVENT_KEY$2); - $.removeData(this._element, DATA_KEY$2); - this._items = null; - this._config = null; - this._element = null; - this._interval = null; - this._isPaused = null; - this._isSliding = null; - this._activeElement = null; - this._indicatorsElement = null; - } // Private - ; + Carousel.carouselInterface(target, config); + + if (slideIndex) { + Carousel.getInstance(target).to(slideIndex); + } + + event.preventDefault(); + } + + } + /** + * ------------------------------------------------------------------------ + * Data Api implementation + * ------------------------------------------------------------------------ + */ + + + EventHandler.on(document, EVENT_CLICK_DATA_API$5, SELECTOR_DATA_SLIDE, Carousel.dataApiClickHandler); + EventHandler.on(window, EVENT_LOAD_DATA_API$2, () => { + const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE); + + for (let i = 0, len = carousels.length; i < len; i++) { + Carousel.carouselInterface(carousels[i], Carousel.getInstance(carousels[i])); + } + }); + /** + * ------------------------------------------------------------------------ + * jQuery + * ------------------------------------------------------------------------ + * add .Carousel to jQuery only if jQuery is present + */ + + defineJQueryPlugin(Carousel); + + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): collapse.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + /** + * ------------------------------------------------------------------------ + * Constants + * ------------------------------------------------------------------------ + */ + + const NAME$a = 'collapse'; + const DATA_KEY$9 = 'bs.collapse'; + const EVENT_KEY$9 = `.${DATA_KEY$9}`; + const DATA_API_KEY$5 = '.data-api'; + const Default$9 = { + toggle: true, + parent: null + }; + const DefaultType$9 = { + toggle: 'boolean', + parent: '(null|element)' + }; + const EVENT_SHOW$5 = `show${EVENT_KEY$9}`; + const EVENT_SHOWN$5 = `shown${EVENT_KEY$9}`; + const EVENT_HIDE$5 = `hide${EVENT_KEY$9}`; + const EVENT_HIDDEN$5 = `hidden${EVENT_KEY$9}`; + const EVENT_CLICK_DATA_API$4 = `click${EVENT_KEY$9}${DATA_API_KEY$5}`; + const CLASS_NAME_SHOW$7 = 'show'; + const CLASS_NAME_COLLAPSE = 'collapse'; + const CLASS_NAME_COLLAPSING = 'collapsing'; + const CLASS_NAME_COLLAPSED = 'collapsed'; + const CLASS_NAME_HORIZONTAL = 'collapse-horizontal'; + const WIDTH = 'width'; + const HEIGHT = 'height'; + const SELECTOR_ACTIVES = '.show, .collapsing'; + const SELECTOR_DATA_TOGGLE$4 = '[data-bs-toggle="collapse"]'; + /** + * ------------------------------------------------------------------------ + * Class Definition + * ------------------------------------------------------------------------ + */ + + class Collapse extends BaseComponent { + constructor(element, config) { + super(element); + this._isTransitioning = false; + this._config = this._getConfig(config); + this._triggerArray = []; + const toggleList = SelectorEngine.find(SELECTOR_DATA_TOGGLE$4); + + for (let i = 0, len = toggleList.length; i < len; i++) { + const elem = toggleList[i]; + const selector = getSelectorFromElement(elem); + const filterElement = SelectorEngine.find(selector).filter(foundElem => foundElem === this._element); + + if (selector !== null && filterElement.length) { + this._selector = selector; + + this._triggerArray.push(elem); + } + } + + this._initializeChildren(); + + if (!this._config.parent) { + this._addAriaAndCollapsedClass(this._triggerArray, this._isShown()); + } + + if (this._config.toggle) { + this.toggle(); + } + } // Getters - _proto._getConfig = function _getConfig(config) { - config = _objectSpread({}, Default, config); - Util.typeCheckConfig(NAME$2, config, DefaultType); - return config; - }; - _proto._handleSwipe = function _handleSwipe() { - var absDeltax = Math.abs(this.touchDeltaX); + static get Default() { + return Default$9; + } + + static get NAME() { + return NAME$a; + } // Public + + + toggle() { + if (this._isShown()) { + this.hide(); + } else { + this.show(); + } + } - if (absDeltax <= SWIPE_THRESHOLD) { + show() { + if (this._isTransitioning || this._isShown()) { return; } - var direction = absDeltax / this.touchDeltaX; // swipe left - - if (direction > 0) { - this.prev(); - } // swipe right - + let actives = []; + let activesData; - if (direction < 0) { - this.next(); + if (this._config.parent) { + const children = SelectorEngine.find(`.${CLASS_NAME_COLLAPSE} .${CLASS_NAME_COLLAPSE}`, this._config.parent); + actives = SelectorEngine.find(SELECTOR_ACTIVES, this._config.parent).filter(elem => !children.includes(elem)); // remove children if greater depth } - }; - _proto._addEventListeners = function _addEventListeners() { - var _this2 = this; - - if (this._config.keyboard) { - $(this._element).on(Event$2.KEYDOWN, function (event) { - return _this2._keydown(event); - }); - } + const container = SelectorEngine.findOne(this._selector); - if (this._config.pause === 'hover') { - $(this._element).on(Event$2.MOUSEENTER, function (event) { - return _this2.pause(event); - }).on(Event$2.MOUSELEAVE, function (event) { - return _this2.cycle(event); - }); - } + if (actives.length) { + const tempActiveData = actives.find(elem => container !== elem); + activesData = tempActiveData ? Collapse.getInstance(tempActiveData) : null; - if (this._config.touch) { - this._addTouchEventListeners(); + if (activesData && activesData._isTransitioning) { + return; + } } - }; - _proto._addTouchEventListeners = function _addTouchEventListeners() { - var _this3 = this; + const startEvent = EventHandler.trigger(this._element, EVENT_SHOW$5); - if (!this._touchSupported) { + if (startEvent.defaultPrevented) { return; } - var start = function start(event) { - if (_this3._pointerEvent && PointerType[event.originalEvent.pointerType.toUpperCase()]) { - _this3.touchStartX = event.originalEvent.clientX; - } else if (!_this3._pointerEvent) { - _this3.touchStartX = event.originalEvent.touches[0].clientX; - } - }; - - var move = function move(event) { - // ensure swiping with one touch and not pinching - if (event.originalEvent.touches && event.originalEvent.touches.length > 1) { - _this3.touchDeltaX = 0; - } else { - _this3.touchDeltaX = event.originalEvent.touches[0].clientX - _this3.touchStartX; + actives.forEach(elemActive => { + if (container !== elemActive) { + Collapse.getOrCreateInstance(elemActive, { + toggle: false + }).hide(); } - }; - var end = function end(event) { - if (_this3._pointerEvent && PointerType[event.originalEvent.pointerType.toUpperCase()]) { - _this3.touchDeltaX = event.originalEvent.clientX - _this3.touchStartX; + if (!activesData) { + Data.set(elemActive, DATA_KEY$9, null); } + }); - _this3._handleSwipe(); + const dimension = this._getDimension(); - if (_this3._config.pause === 'hover') { - // If it's a touch-enabled device, mouseenter/leave are fired as - // part of the mouse compatibility events on first tap - the carousel - // would stop cycling until user tapped out of it; - // here, we listen for touchend, explicitly pause the carousel - // (as if it's the second time we tap on it, mouseenter compat event - // is NOT fired) and after a timeout (to allow for mouse compatibility - // events to fire) we explicitly restart cycling - _this3.pause(); + this._element.classList.remove(CLASS_NAME_COLLAPSE); - if (_this3.touchTimeout) { - clearTimeout(_this3.touchTimeout); - } + this._element.classList.add(CLASS_NAME_COLLAPSING); - _this3.touchTimeout = setTimeout(function (event) { - return _this3.cycle(event); - }, TOUCHEVENT_COMPAT_WAIT + _this3._config.interval); - } - }; + this._element.style[dimension] = 0; - $(this._element.querySelectorAll(Selector$2.ITEM_IMG)).on(Event$2.DRAG_START, function (e) { - return e.preventDefault(); - }); + this._addAriaAndCollapsedClass(this._triggerArray, true); - if (this._pointerEvent) { - $(this._element).on(Event$2.POINTERDOWN, function (event) { - return start(event); - }); - $(this._element).on(Event$2.POINTERUP, function (event) { - return end(event); - }); + this._isTransitioning = true; - this._element.classList.add(ClassName$2.POINTER_EVENT); - } else { - $(this._element).on(Event$2.TOUCHSTART, function (event) { - return start(event); - }); - $(this._element).on(Event$2.TOUCHMOVE, function (event) { - return move(event); - }); - $(this._element).on(Event$2.TOUCHEND, function (event) { - return end(event); - }); - } - }; + const complete = () => { + this._isTransitioning = false; - _proto._keydown = function _keydown(event) { - if (/input|textarea/i.test(event.target.tagName)) { - return; - } + this._element.classList.remove(CLASS_NAME_COLLAPSING); - switch (event.which) { - case ARROW_LEFT_KEYCODE: - event.preventDefault(); - this.prev(); - break; + this._element.classList.add(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7); - case ARROW_RIGHT_KEYCODE: - event.preventDefault(); - this.next(); - break; + this._element.style[dimension] = ''; + EventHandler.trigger(this._element, EVENT_SHOWN$5); + }; - default: - } - }; + const capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1); + const scrollSize = `scroll${capitalizedDimension}`; - _proto._getItemIndex = function _getItemIndex(element) { - this._items = element && element.parentNode ? [].slice.call(element.parentNode.querySelectorAll(Selector$2.ITEM)) : []; - return this._items.indexOf(element); - }; + this._queueCallback(complete, this._element, true); - _proto._getItemByDirection = function _getItemByDirection(direction, activeElement) { - var isNextDirection = direction === Direction.NEXT; - var isPrevDirection = direction === Direction.PREV; + this._element.style[dimension] = `${this._element[scrollSize]}px`; + } - var activeIndex = this._getItemIndex(activeElement); + hide() { + if (this._isTransitioning || !this._isShown()) { + return; + } - var lastItemIndex = this._items.length - 1; - var isGoingToWrap = isPrevDirection && activeIndex === 0 || isNextDirection && activeIndex === lastItemIndex; + const startEvent = EventHandler.trigger(this._element, EVENT_HIDE$5); - if (isGoingToWrap && !this._config.wrap) { - return activeElement; + if (startEvent.defaultPrevented) { + return; } - var delta = direction === Direction.PREV ? -1 : 1; - var itemIndex = (activeIndex + delta) % this._items.length; - return itemIndex === -1 ? this._items[this._items.length - 1] : this._items[itemIndex]; - }; + const dimension = this._getDimension(); - _proto._triggerSlideEvent = function _triggerSlideEvent(relatedTarget, eventDirectionName) { - var targetIndex = this._getItemIndex(relatedTarget); + this._element.style[dimension] = `${this._element.getBoundingClientRect()[dimension]}px`; + reflow(this._element); - var fromIndex = this._getItemIndex(this._element.querySelector(Selector$2.ACTIVE_ITEM)); + this._element.classList.add(CLASS_NAME_COLLAPSING); - var slideEvent = $.Event(Event$2.SLIDE, { - relatedTarget: relatedTarget, - direction: eventDirectionName, - from: fromIndex, - to: targetIndex - }); - $(this._element).trigger(slideEvent); - return slideEvent; - }; + this._element.classList.remove(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7); - _proto._setActiveIndicatorElement = function _setActiveIndicatorElement(element) { - if (this._indicatorsElement) { - var indicators = [].slice.call(this._indicatorsElement.querySelectorAll(Selector$2.ACTIVE)); - $(indicators).removeClass(ClassName$2.ACTIVE); + const triggerArrayLength = this._triggerArray.length; - var nextIndicator = this._indicatorsElement.children[this._getItemIndex(element)]; + for (let i = 0; i < triggerArrayLength; i++) { + const trigger = this._triggerArray[i]; + const elem = getElementFromSelector(trigger); - if (nextIndicator) { - $(nextIndicator).addClass(ClassName$2.ACTIVE); + if (elem && !this._isShown(elem)) { + this._addAriaAndCollapsedClass([trigger], false); } } - }; - _proto._slide = function _slide(direction, element) { - var _this4 = this; + this._isTransitioning = true; - var activeElement = this._element.querySelector(Selector$2.ACTIVE_ITEM); + const complete = () => { + this._isTransitioning = false; - var activeElementIndex = this._getItemIndex(activeElement); + this._element.classList.remove(CLASS_NAME_COLLAPSING); - var nextElement = element || activeElement && this._getItemByDirection(direction, activeElement); + this._element.classList.add(CLASS_NAME_COLLAPSE); - var nextElementIndex = this._getItemIndex(nextElement); + EventHandler.trigger(this._element, EVENT_HIDDEN$5); + }; - var isCycling = Boolean(this._interval); - var directionalClassName; - var orderClassName; - var eventDirectionName; + this._element.style[dimension] = ''; - if (direction === Direction.NEXT) { - directionalClassName = ClassName$2.LEFT; - orderClassName = ClassName$2.NEXT; - eventDirectionName = Direction.LEFT; - } else { - directionalClassName = ClassName$2.RIGHT; - orderClassName = ClassName$2.PREV; - eventDirectionName = Direction.RIGHT; - } + this._queueCallback(complete, this._element, true); + } - if (nextElement && $(nextElement).hasClass(ClassName$2.ACTIVE)) { - this._isSliding = false; - return; - } + _isShown(element = this._element) { + return element.classList.contains(CLASS_NAME_SHOW$7); + } // Private - var slideEvent = this._triggerSlideEvent(nextElement, eventDirectionName); - if (slideEvent.isDefaultPrevented()) { - return; - } + _getConfig(config) { + config = { ...Default$9, + ...Manipulator.getDataAttributes(this._element), + ...config + }; + config.toggle = Boolean(config.toggle); // Coerce string values - if (!activeElement || !nextElement) { - // Some weirdness is happening, so we bail - return; - } + config.parent = getElement(config.parent); + typeCheckConfig(NAME$a, config, DefaultType$9); + return config; + } - this._isSliding = true; + _getDimension() { + return this._element.classList.contains(CLASS_NAME_HORIZONTAL) ? WIDTH : HEIGHT; + } - if (isCycling) { - this.pause(); + _initializeChildren() { + if (!this._config.parent) { + return; } - this._setActiveIndicatorElement(nextElement); + const children = SelectorEngine.find(`.${CLASS_NAME_COLLAPSE} .${CLASS_NAME_COLLAPSE}`, this._config.parent); + SelectorEngine.find(SELECTOR_DATA_TOGGLE$4, this._config.parent).filter(elem => !children.includes(elem)).forEach(element => { + const selected = getElementFromSelector(element); - var slidEvent = $.Event(Event$2.SLID, { - relatedTarget: nextElement, - direction: eventDirectionName, - from: activeElementIndex, - to: nextElementIndex + if (selected) { + this._addAriaAndCollapsedClass([element], this._isShown(selected)); + } }); + } - if ($(this._element).hasClass(ClassName$2.SLIDE)) { - $(nextElement).addClass(orderClassName); - Util.reflow(nextElement); - $(activeElement).addClass(directionalClassName); - $(nextElement).addClass(directionalClassName); - var nextElementInterval = parseInt(nextElement.getAttribute('data-interval'), 10); + _addAriaAndCollapsedClass(triggerArray, isOpen) { + if (!triggerArray.length) { + return; + } - if (nextElementInterval) { - this._config.defaultInterval = this._config.defaultInterval || this._config.interval; - this._config.interval = nextElementInterval; + triggerArray.forEach(elem => { + if (isOpen) { + elem.classList.remove(CLASS_NAME_COLLAPSED); } else { - this._config.interval = this._config.defaultInterval || this._config.interval; + elem.classList.add(CLASS_NAME_COLLAPSED); } - var transitionDuration = Util.getTransitionDurationFromElement(activeElement); - $(activeElement).one(Util.TRANSITION_END, function () { - $(nextElement).removeClass(directionalClassName + " " + orderClassName).addClass(ClassName$2.ACTIVE); - $(activeElement).removeClass(ClassName$2.ACTIVE + " " + orderClassName + " " + directionalClassName); - _this4._isSliding = false; - setTimeout(function () { - return $(_this4._element).trigger(slidEvent); - }, 0); - }).emulateTransitionEnd(transitionDuration); - } else { - $(activeElement).removeClass(ClassName$2.ACTIVE); - $(nextElement).addClass(ClassName$2.ACTIVE); - this._isSliding = false; - $(this._element).trigger(slidEvent); - } - - if (isCycling) { - this.cycle(); - } + elem.setAttribute('aria-expanded', isOpen); + }); } // Static - ; - Carousel._jQueryInterface = function _jQueryInterface(config) { - return this.each(function () { - var data = $(this).data(DATA_KEY$2); - var _config = _objectSpread({}, Default, $(this).data()); + static jQueryInterface(config) { + return this.each(function () { + const _config = {}; - if (typeof config === 'object') { - _config = _objectSpread({}, _config, config); + if (typeof config === 'string' && /show|hide/.test(config)) { + _config.toggle = false; } - var action = typeof config === 'string' ? config : _config.slide; - - if (!data) { - data = new Carousel(this, _config); - $(this).data(DATA_KEY$2, data); - } + const data = Collapse.getOrCreateInstance(this, _config); - if (typeof config === 'number') { - data.to(config); - } else if (typeof action === 'string') { - if (typeof data[action] === 'undefined') { - throw new TypeError("No method named \"" + action + "\""); + if (typeof config === 'string') { + if (typeof data[config] === 'undefined') { + throw new TypeError(`No method named "${config}"`); } - data[action](); - } else if (_config.interval && _config.ride) { - data.pause(); - data.cycle(); + data[config](); } }); - }; + } + + } + /** + * ------------------------------------------------------------------------ + * Data Api implementation + * ------------------------------------------------------------------------ + */ - Carousel._dataApiClickHandler = function _dataApiClickHandler(event) { - var selector = Util.getSelectorFromElement(this); - if (!selector) { - return; - } + EventHandler.on(document, EVENT_CLICK_DATA_API$4, SELECTOR_DATA_TOGGLE$4, function (event) { + // preventDefault only for elements (which change the URL) not inside the collapsible element + if (event.target.tagName === 'A' || event.delegateTarget && event.delegateTarget.tagName === 'A') { + event.preventDefault(); + } - var target = $(selector)[0]; + const selector = getSelectorFromElement(this); + const selectorElements = SelectorEngine.find(selector); + selectorElements.forEach(element => { + Collapse.getOrCreateInstance(element, { + toggle: false + }).toggle(); + }); + }); + /** + * ------------------------------------------------------------------------ + * jQuery + * ------------------------------------------------------------------------ + * add .Collapse to jQuery only if jQuery is present + */ - if (!target || !$(target).hasClass(ClassName$2.CAROUSEL)) { - return; - } + defineJQueryPlugin(Collapse); + + var top = 'top'; + var bottom = 'bottom'; + var right = 'right'; + var left = 'left'; + var auto = 'auto'; + var basePlacements = [top, bottom, right, left]; + var start = 'start'; + var end = 'end'; + var clippingParents = 'clippingParents'; + var viewport = 'viewport'; + var popper = 'popper'; + var reference = 'reference'; + var variationPlacements = /*#__PURE__*/basePlacements.reduce(function (acc, placement) { + return acc.concat([placement + "-" + start, placement + "-" + end]); + }, []); + var placements = /*#__PURE__*/[].concat(basePlacements, [auto]).reduce(function (acc, placement) { + return acc.concat([placement, placement + "-" + start, placement + "-" + end]); + }, []); // modifiers that need to read the DOM + + var beforeRead = 'beforeRead'; + var read = 'read'; + var afterRead = 'afterRead'; // pure-logic modifiers + + var beforeMain = 'beforeMain'; + var main = 'main'; + var afterMain = 'afterMain'; // modifier with the purpose to write to the DOM (or write into a framework state) + + var beforeWrite = 'beforeWrite'; + var write = 'write'; + var afterWrite = 'afterWrite'; + var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite]; + + function getNodeName(element) { + return element ? (element.nodeName || '').toLowerCase() : null; + } - var config = _objectSpread({}, $(target).data(), $(this).data()); + function getWindow(node) { + if (node == null) { + return window; + } - var slideIndex = this.getAttribute('data-slide-to'); + if (node.toString() !== '[object Window]') { + var ownerDocument = node.ownerDocument; + return ownerDocument ? ownerDocument.defaultView || window : window; + } - if (slideIndex) { - config.interval = false; - } + return node; + } - Carousel._jQueryInterface.call($(target), config); + function isElement(node) { + var OwnElement = getWindow(node).Element; + return node instanceof OwnElement || node instanceof Element; + } - if (slideIndex) { - $(target).data(DATA_KEY$2).to(slideIndex); - } + function isHTMLElement(node) { + var OwnElement = getWindow(node).HTMLElement; + return node instanceof OwnElement || node instanceof HTMLElement; + } - event.preventDefault(); - }; + function isShadowRoot(node) { + // IE 11 has no ShadowRoot + if (typeof ShadowRoot === 'undefined') { + return false; + } - _createClass(Carousel, null, [{ - key: "VERSION", - get: function get() { - return VERSION$2; - } - }, { - key: "Default", - get: function get() { - return Default; - } - }]); + var OwnElement = getWindow(node).ShadowRoot; + return node instanceof OwnElement || node instanceof ShadowRoot; + } - return Carousel; - }(); - /** - * ------------------------------------------------------------------------ - * Data Api implementation - * ------------------------------------------------------------------------ - */ + // and applies them to the HTMLElements such as popper and arrow + + function applyStyles(_ref) { + var state = _ref.state; + Object.keys(state.elements).forEach(function (name) { + var style = state.styles[name] || {}; + var attributes = state.attributes[name] || {}; + var element = state.elements[name]; // arrow is optional + virtual elements + + if (!isHTMLElement(element) || !getNodeName(element)) { + return; + } // Flow doesn't support to extend this property, but it's the most + // effective way to apply styles to an HTMLElement + // $FlowFixMe[cannot-write] - $(document).on(Event$2.CLICK_DATA_API, Selector$2.DATA_SLIDE, Carousel._dataApiClickHandler); - $(window).on(Event$2.LOAD_DATA_API, function () { - var carousels = [].slice.call(document.querySelectorAll(Selector$2.DATA_RIDE)); + Object.assign(element.style, style); + Object.keys(attributes).forEach(function (name) { + var value = attributes[name]; + + if (value === false) { + element.removeAttribute(name); + } else { + element.setAttribute(name, value === true ? '' : value); + } + }); + }); + } - for (var i = 0, len = carousels.length; i < len; i++) { - var $carousel = $(carousels[i]); + function effect$2(_ref2) { + var state = _ref2.state; + var initialStyles = { + popper: { + position: state.options.strategy, + left: '0', + top: '0', + margin: '0' + }, + arrow: { + position: 'absolute' + }, + reference: {} + }; + Object.assign(state.elements.popper.style, initialStyles.popper); + state.styles = initialStyles; - Carousel._jQueryInterface.call($carousel, $carousel.data()); + if (state.elements.arrow) { + Object.assign(state.elements.arrow.style, initialStyles.arrow); } - }); - /** - * ------------------------------------------------------------------------ - * jQuery - * ------------------------------------------------------------------------ - */ - $.fn[NAME$2] = Carousel._jQueryInterface; - $.fn[NAME$2].Constructor = Carousel; + return function () { + Object.keys(state.elements).forEach(function (name) { + var element = state.elements[name]; + var attributes = state.attributes[name] || {}; + var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); // Set all values to an empty string to unset them - $.fn[NAME$2].noConflict = function () { - $.fn[NAME$2] = JQUERY_NO_CONFLICT$2; - return Carousel._jQueryInterface; - }; + var style = styleProperties.reduce(function (style, property) { + style[property] = ''; + return style; + }, {}); // arrow is optional + virtual elements - /** - * ------------------------------------------------------------------------ - * Constants - * ------------------------------------------------------------------------ - */ + if (!isHTMLElement(element) || !getNodeName(element)) { + return; + } - var NAME$3 = 'collapse'; - var VERSION$3 = '4.3.1'; - var DATA_KEY$3 = 'bs.collapse'; - var EVENT_KEY$3 = "." + DATA_KEY$3; - var DATA_API_KEY$3 = '.data-api'; - var JQUERY_NO_CONFLICT$3 = $.fn[NAME$3]; - var Default$1 = { - toggle: true, - parent: '' - }; - var DefaultType$1 = { - toggle: 'boolean', - parent: '(string|element)' - }; - var Event$3 = { - SHOW: "show" + EVENT_KEY$3, - SHOWN: "shown" + EVENT_KEY$3, - HIDE: "hide" + EVENT_KEY$3, - HIDDEN: "hidden" + EVENT_KEY$3, - CLICK_DATA_API: "click" + EVENT_KEY$3 + DATA_API_KEY$3 - }; - var ClassName$3 = { - SHOW: 'show', - COLLAPSE: 'collapse', - COLLAPSING: 'collapsing', - COLLAPSED: 'collapsed' - }; - var Dimension = { - WIDTH: 'width', - HEIGHT: 'height' - }; - var Selector$3 = { - ACTIVES: '.show, .collapsing', - DATA_TOGGLE: '[data-toggle="collapse"]' - /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ - */ + Object.assign(element.style, style); + Object.keys(attributes).forEach(function (attribute) { + element.removeAttribute(attribute); + }); + }); + }; + } // eslint-disable-next-line import/no-unused-modules + + var applyStyles$1 = { + name: 'applyStyles', + enabled: true, + phase: 'write', + fn: applyStyles, + effect: effect$2, + requires: ['computeStyles'] }; - var Collapse = - /*#__PURE__*/ - function () { - function Collapse(element, config) { - this._isTransitioning = false; - this._element = element; - this._config = this._getConfig(config); - this._triggerArray = [].slice.call(document.querySelectorAll("[data-toggle=\"collapse\"][href=\"#" + element.id + "\"]," + ("[data-toggle=\"collapse\"][data-target=\"#" + element.id + "\"]"))); - var toggleList = [].slice.call(document.querySelectorAll(Selector$3.DATA_TOGGLE)); - - for (var i = 0, len = toggleList.length; i < len; i++) { - var elem = toggleList[i]; - var selector = Util.getSelectorFromElement(elem); - var filterElement = [].slice.call(document.querySelectorAll(selector)).filter(function (foundElem) { - return foundElem === element; - }); + function getBasePlacement(placement) { + return placement.split('-')[0]; + } - if (selector !== null && filterElement.length > 0) { - this._selector = selector; + var round$1 = Math.round; + function getBoundingClientRect(element, includeScale) { + if (includeScale === void 0) { + includeScale = false; + } - this._triggerArray.push(elem); - } - } + var rect = element.getBoundingClientRect(); + var scaleX = 1; + var scaleY = 1; - this._parent = this._config.parent ? this._getParent() : null; + if (isHTMLElement(element) && includeScale) { + // Fallback to 1 in case both values are `0` + scaleX = rect.width / element.offsetWidth || 1; + scaleY = rect.height / element.offsetHeight || 1; + } - if (!this._config.parent) { - this._addAriaAndCollapsedClass(this._element, this._triggerArray); - } + return { + width: round$1(rect.width / scaleX), + height: round$1(rect.height / scaleY), + top: round$1(rect.top / scaleY), + right: round$1(rect.right / scaleX), + bottom: round$1(rect.bottom / scaleY), + left: round$1(rect.left / scaleX), + x: round$1(rect.left / scaleX), + y: round$1(rect.top / scaleY) + }; + } - if (this._config.toggle) { - this.toggle(); - } - } // Getters + // means it doesn't take into account transforms. + function getLayoutRect(element) { + var clientRect = getBoundingClientRect(element); // Use the clientRect sizes if it's not been transformed. + // Fixes https://github.com/popperjs/popper-core/issues/1223 - var _proto = Collapse.prototype; + var width = element.offsetWidth; + var height = element.offsetHeight; - // Public - _proto.toggle = function toggle() { - if ($(this._element).hasClass(ClassName$3.SHOW)) { - this.hide(); - } else { - this.show(); - } + if (Math.abs(clientRect.width - width) <= 1) { + width = clientRect.width; + } + + if (Math.abs(clientRect.height - height) <= 1) { + height = clientRect.height; + } + + return { + x: element.offsetLeft, + y: element.offsetTop, + width: width, + height: height }; + } + + function contains(parent, child) { + var rootNode = child.getRootNode && child.getRootNode(); // First, attempt with faster native method + + if (parent.contains(child)) { + return true; + } // then fallback to custom implementation with Shadow DOM support + else if (rootNode && isShadowRoot(rootNode)) { + var next = child; + + do { + if (next && parent.isSameNode(next)) { + return true; + } // $FlowFixMe[prop-missing]: need a better way to handle this... + + + next = next.parentNode || next.host; + } while (next); + } // Give up, the result is false + + + return false; + } + + function getComputedStyle$1(element) { + return getWindow(element).getComputedStyle(element); + } + + function isTableElement(element) { + return ['table', 'td', 'th'].indexOf(getNodeName(element)) >= 0; + } + + function getDocumentElement(element) { + // $FlowFixMe[incompatible-return]: assume body is always available + return ((isElement(element) ? element.ownerDocument : // $FlowFixMe[prop-missing] + element.document) || window.document).documentElement; + } + + function getParentNode(element) { + if (getNodeName(element) === 'html') { + return element; + } + + return (// this is a quicker (but less type safe) way to save quite some bytes from the bundle + // $FlowFixMe[incompatible-return] + // $FlowFixMe[prop-missing] + element.assignedSlot || // step into the shadow DOM of the parent of a slotted node + element.parentNode || ( // DOM Element detected + isShadowRoot(element) ? element.host : null) || // ShadowRoot detected + // $FlowFixMe[incompatible-call]: HTMLElement is a Node + getDocumentElement(element) // fallback + + ); + } - _proto.show = function show() { - var _this = this; + function getTrueOffsetParent(element) { + if (!isHTMLElement(element) || // https://github.com/popperjs/popper-core/issues/837 + getComputedStyle$1(element).position === 'fixed') { + return null; + } - if (this._isTransitioning || $(this._element).hasClass(ClassName$3.SHOW)) { - return; - } + return element.offsetParent; + } // `.offsetParent` reports `null` for fixed elements, while absolute elements + // return the containing block - var actives; - var activesData; - if (this._parent) { - actives = [].slice.call(this._parent.querySelectorAll(Selector$3.ACTIVES)).filter(function (elem) { - if (typeof _this._config.parent === 'string') { - return elem.getAttribute('data-parent') === _this._config.parent; - } + function getContainingBlock(element) { + var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') !== -1; + var isIE = navigator.userAgent.indexOf('Trident') !== -1; - return elem.classList.contains(ClassName$3.COLLAPSE); - }); + if (isIE && isHTMLElement(element)) { + // In IE 9, 10 and 11 fixed elements containing block is always established by the viewport + var elementCss = getComputedStyle$1(element); - if (actives.length === 0) { - actives = null; - } + if (elementCss.position === 'fixed') { + return null; } + } - if (actives) { - activesData = $(actives).not(this._selector).data(DATA_KEY$3); - - if (activesData && activesData._isTransitioning) { - return; - } - } + var currentNode = getParentNode(element); - var startEvent = $.Event(Event$3.SHOW); - $(this._element).trigger(startEvent); + while (isHTMLElement(currentNode) && ['html', 'body'].indexOf(getNodeName(currentNode)) < 0) { + var css = getComputedStyle$1(currentNode); // This is non-exhaustive but covers the most common CSS properties that + // create a containing block. + // https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block#identifying_the_containing_block - if (startEvent.isDefaultPrevented()) { - return; + if (css.transform !== 'none' || css.perspective !== 'none' || css.contain === 'paint' || ['transform', 'perspective'].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === 'filter' || isFirefox && css.filter && css.filter !== 'none') { + return currentNode; + } else { + currentNode = currentNode.parentNode; } + } - if (actives) { - Collapse._jQueryInterface.call($(actives).not(this._selector), 'hide'); + return null; + } // Gets the closest ancestor positioned element. Handles some edge cases, + // such as table ancestors and cross browser bugs. - if (!activesData) { - $(actives).data(DATA_KEY$3, null); - } - } - var dimension = this._getDimension(); + function getOffsetParent(element) { + var window = getWindow(element); + var offsetParent = getTrueOffsetParent(element); - $(this._element).removeClass(ClassName$3.COLLAPSE).addClass(ClassName$3.COLLAPSING); - this._element.style[dimension] = 0; + while (offsetParent && isTableElement(offsetParent) && getComputedStyle$1(offsetParent).position === 'static') { + offsetParent = getTrueOffsetParent(offsetParent); + } - if (this._triggerArray.length) { - $(this._triggerArray).removeClass(ClassName$3.COLLAPSED).attr('aria-expanded', true); - } + if (offsetParent && (getNodeName(offsetParent) === 'html' || getNodeName(offsetParent) === 'body' && getComputedStyle$1(offsetParent).position === 'static')) { + return window; + } - this.setTransitioning(true); + return offsetParent || getContainingBlock(element) || window; + } - var complete = function complete() { - $(_this._element).removeClass(ClassName$3.COLLAPSING).addClass(ClassName$3.COLLAPSE).addClass(ClassName$3.SHOW); - _this._element.style[dimension] = ''; + function getMainAxisFromPlacement(placement) { + return ['top', 'bottom'].indexOf(placement) >= 0 ? 'x' : 'y'; + } - _this.setTransitioning(false); + var max = Math.max; + var min = Math.min; + var round = Math.round; - $(_this._element).trigger(Event$3.SHOWN); - }; + function within(min$1, value, max$1) { + return max(min$1, min(value, max$1)); + } - var capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1); - var scrollSize = "scroll" + capitalizedDimension; - var transitionDuration = Util.getTransitionDurationFromElement(this._element); - $(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration); - this._element.style[dimension] = this._element[scrollSize] + "px"; + function getFreshSideObject() { + return { + top: 0, + right: 0, + bottom: 0, + left: 0 }; + } - _proto.hide = function hide() { - var _this2 = this; + function mergePaddingObject(paddingObject) { + return Object.assign({}, getFreshSideObject(), paddingObject); + } - if (this._isTransitioning || !$(this._element).hasClass(ClassName$3.SHOW)) { - return; - } + function expandToHashMap(value, keys) { + return keys.reduce(function (hashMap, key) { + hashMap[key] = value; + return hashMap; + }, {}); + } - var startEvent = $.Event(Event$3.HIDE); - $(this._element).trigger(startEvent); + var toPaddingObject = function toPaddingObject(padding, state) { + padding = typeof padding === 'function' ? padding(Object.assign({}, state.rects, { + placement: state.placement + })) : padding; + return mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements)); + }; - if (startEvent.isDefaultPrevented()) { - return; - } + function arrow(_ref) { + var _state$modifiersData$; + + var state = _ref.state, + name = _ref.name, + options = _ref.options; + var arrowElement = state.elements.arrow; + var popperOffsets = state.modifiersData.popperOffsets; + var basePlacement = getBasePlacement(state.placement); + var axis = getMainAxisFromPlacement(basePlacement); + var isVertical = [left, right].indexOf(basePlacement) >= 0; + var len = isVertical ? 'height' : 'width'; - var dimension = this._getDimension(); + if (!arrowElement || !popperOffsets) { + return; + } - this._element.style[dimension] = this._element.getBoundingClientRect()[dimension] + "px"; - Util.reflow(this._element); - $(this._element).addClass(ClassName$3.COLLAPSING).removeClass(ClassName$3.COLLAPSE).removeClass(ClassName$3.SHOW); - var triggerArrayLength = this._triggerArray.length; + var paddingObject = toPaddingObject(options.padding, state); + var arrowRect = getLayoutRect(arrowElement); + var minProp = axis === 'y' ? top : left; + var maxProp = axis === 'y' ? bottom : right; + var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets[axis] - state.rects.popper[len]; + var startDiff = popperOffsets[axis] - state.rects.reference[axis]; + var arrowOffsetParent = getOffsetParent(arrowElement); + var clientSize = arrowOffsetParent ? axis === 'y' ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0; + var centerToReference = endDiff / 2 - startDiff / 2; // Make sure the arrow doesn't overflow the popper if the center point is + // outside of the popper bounds + + var min = paddingObject[minProp]; + var max = clientSize - arrowRect[len] - paddingObject[maxProp]; + var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference; + var offset = within(min, center, max); // Prevents breaking syntax highlighting... + + var axisProp = axis; + state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset, _state$modifiersData$.centerOffset = offset - center, _state$modifiersData$); + } - if (triggerArrayLength > 0) { - for (var i = 0; i < triggerArrayLength; i++) { - var trigger = this._triggerArray[i]; - var selector = Util.getSelectorFromElement(trigger); + function effect$1(_ref2) { + var state = _ref2.state, + options = _ref2.options; + var _options$element = options.element, + arrowElement = _options$element === void 0 ? '[data-popper-arrow]' : _options$element; - if (selector !== null) { - var $elem = $([].slice.call(document.querySelectorAll(selector))); + if (arrowElement == null) { + return; + } // CSS selector - if (!$elem.hasClass(ClassName$3.SHOW)) { - $(trigger).addClass(ClassName$3.COLLAPSED).attr('aria-expanded', false); - } - } - } - } - this.setTransitioning(true); + if (typeof arrowElement === 'string') { + arrowElement = state.elements.popper.querySelector(arrowElement); - var complete = function complete() { - _this2.setTransitioning(false); + if (!arrowElement) { + return; + } + } - $(_this2._element).removeClass(ClassName$3.COLLAPSING).addClass(ClassName$3.COLLAPSE).trigger(Event$3.HIDDEN); - }; + if (!contains(state.elements.popper, arrowElement)) { - this._element.style[dimension] = ''; - var transitionDuration = Util.getTransitionDurationFromElement(this._element); - $(this._element).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration); - }; + return; + } - _proto.setTransitioning = function setTransitioning(isTransitioning) { - this._isTransitioning = isTransitioning; - }; + state.elements.arrow = arrowElement; + } // eslint-disable-next-line import/no-unused-modules - _proto.dispose = function dispose() { - $.removeData(this._element, DATA_KEY$3); - this._config = null; - this._parent = null; - this._element = null; - this._triggerArray = null; - this._isTransitioning = null; - } // Private - ; - _proto._getConfig = function _getConfig(config) { - config = _objectSpread({}, Default$1, config); - config.toggle = Boolean(config.toggle); // Coerce string values + var arrow$1 = { + name: 'arrow', + enabled: true, + phase: 'main', + fn: arrow, + effect: effect$1, + requires: ['popperOffsets'], + requiresIfExists: ['preventOverflow'] + }; - Util.typeCheckConfig(NAME$3, config, DefaultType$1); - return config; + var unsetSides = { + top: 'auto', + right: 'auto', + bottom: 'auto', + left: 'auto' + }; // Round the offsets to the nearest suitable subpixel based on the DPR. + // Zooming can change the DPR, but it seems to report a value that will + // cleanly divide the values into the appropriate subpixels. + + function roundOffsetsByDPR(_ref) { + var x = _ref.x, + y = _ref.y; + var win = window; + var dpr = win.devicePixelRatio || 1; + return { + x: round(round(x * dpr) / dpr) || 0, + y: round(round(y * dpr) / dpr) || 0 }; + } - _proto._getDimension = function _getDimension() { - var hasWidth = $(this._element).hasClass(Dimension.WIDTH); - return hasWidth ? Dimension.WIDTH : Dimension.HEIGHT; - }; + function mapToStyles(_ref2) { + var _Object$assign2; + + var popper = _ref2.popper, + popperRect = _ref2.popperRect, + placement = _ref2.placement, + offsets = _ref2.offsets, + position = _ref2.position, + gpuAcceleration = _ref2.gpuAcceleration, + adaptive = _ref2.adaptive, + roundOffsets = _ref2.roundOffsets; + + var _ref3 = roundOffsets === true ? roundOffsetsByDPR(offsets) : typeof roundOffsets === 'function' ? roundOffsets(offsets) : offsets, + _ref3$x = _ref3.x, + x = _ref3$x === void 0 ? 0 : _ref3$x, + _ref3$y = _ref3.y, + y = _ref3$y === void 0 ? 0 : _ref3$y; + + var hasX = offsets.hasOwnProperty('x'); + var hasY = offsets.hasOwnProperty('y'); + var sideX = left; + var sideY = top; + var win = window; + + if (adaptive) { + var offsetParent = getOffsetParent(popper); + var heightProp = 'clientHeight'; + var widthProp = 'clientWidth'; + + if (offsetParent === getWindow(popper)) { + offsetParent = getDocumentElement(popper); + + if (getComputedStyle$1(offsetParent).position !== 'static') { + heightProp = 'scrollHeight'; + widthProp = 'scrollWidth'; + } + } // $FlowFixMe[incompatible-cast]: force type refinement, we compare offsetParent with window above, but Flow doesn't detect it - _proto._getParent = function _getParent() { - var _this3 = this; - var parent; + offsetParent = offsetParent; - if (Util.isElement(this._config.parent)) { - parent = this._config.parent; // It's a jQuery object + if (placement === top) { + sideY = bottom; // $FlowFixMe[prop-missing] - if (typeof this._config.parent.jquery !== 'undefined') { - parent = this._config.parent[0]; - } - } else { - parent = document.querySelector(this._config.parent); + y -= offsetParent[heightProp] - popperRect.height; + y *= gpuAcceleration ? 1 : -1; } - var selector = "[data-toggle=\"collapse\"][data-parent=\"" + this._config.parent + "\"]"; - var children = [].slice.call(parent.querySelectorAll(selector)); - $(children).each(function (i, element) { - _this3._addAriaAndCollapsedClass(Collapse._getTargetFromElement(element), [element]); - }); - return parent; - }; - - _proto._addAriaAndCollapsedClass = function _addAriaAndCollapsedClass(element, triggerArray) { - var isOpen = $(element).hasClass(ClassName$3.SHOW); + if (placement === left) { + sideX = right; // $FlowFixMe[prop-missing] - if (triggerArray.length) { - $(triggerArray).toggleClass(ClassName$3.COLLAPSED, !isOpen).attr('aria-expanded', isOpen); + x -= offsetParent[widthProp] - popperRect.width; + x *= gpuAcceleration ? 1 : -1; } - } // Static - ; - - Collapse._getTargetFromElement = function _getTargetFromElement(element) { - var selector = Util.getSelectorFromElement(element); - return selector ? document.querySelector(selector) : null; - }; - - Collapse._jQueryInterface = function _jQueryInterface(config) { - return this.each(function () { - var $this = $(this); - var data = $this.data(DATA_KEY$3); + } - var _config = _objectSpread({}, Default$1, $this.data(), typeof config === 'object' && config ? config : {}); + var commonStyles = Object.assign({ + position: position + }, adaptive && unsetSides); - if (!data && _config.toggle && /show|hide/.test(config)) { - _config.toggle = false; - } + if (gpuAcceleration) { + var _Object$assign; - if (!data) { - data = new Collapse(this, _config); - $this.data(DATA_KEY$3, data); - } + return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? '0' : '', _Object$assign[sideX] = hasX ? '0' : '', _Object$assign.transform = (win.devicePixelRatio || 1) < 2 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign)); + } - if (typeof config === 'string') { - if (typeof data[config] === 'undefined') { - throw new TypeError("No method named \"" + config + "\""); - } + return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : '', _Object$assign2[sideX] = hasX ? x + "px" : '', _Object$assign2.transform = '', _Object$assign2)); + } - data[config](); - } - }); + function computeStyles(_ref4) { + var state = _ref4.state, + options = _ref4.options; + var _options$gpuAccelerat = options.gpuAcceleration, + gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, + _options$adaptive = options.adaptive, + adaptive = _options$adaptive === void 0 ? true : _options$adaptive, + _options$roundOffsets = options.roundOffsets, + roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets; + + var commonStyles = { + placement: getBasePlacement(state.placement), + popper: state.elements.popper, + popperRect: state.rects.popper, + gpuAcceleration: gpuAcceleration }; - _createClass(Collapse, null, [{ - key: "VERSION", - get: function get() { - return VERSION$3; - } - }, { - key: "Default", - get: function get() { - return Default$1; - } - }]); - - return Collapse; - }(); - /** - * ------------------------------------------------------------------------ - * Data Api implementation - * ------------------------------------------------------------------------ - */ - - - $(document).on(Event$3.CLICK_DATA_API, Selector$3.DATA_TOGGLE, function (event) { - // preventDefault only for elements (which change the URL) not inside the collapsible element - if (event.currentTarget.tagName === 'A') { - event.preventDefault(); + if (state.modifiersData.popperOffsets != null) { + state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, { + offsets: state.modifiersData.popperOffsets, + position: state.options.strategy, + adaptive: adaptive, + roundOffsets: roundOffsets + }))); } - var $trigger = $(this); - var selector = Util.getSelectorFromElement(this); - var selectors = [].slice.call(document.querySelectorAll(selector)); - $(selectors).each(function () { - var $target = $(this); - var data = $target.data(DATA_KEY$3); - var config = data ? 'toggle' : $trigger.data(); + if (state.modifiersData.arrow != null) { + state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, { + offsets: state.modifiersData.arrow, + position: 'absolute', + adaptive: false, + roundOffsets: roundOffsets + }))); + } - Collapse._jQueryInterface.call($target, config); + state.attributes.popper = Object.assign({}, state.attributes.popper, { + 'data-popper-placement': state.placement }); - }); - /** - * ------------------------------------------------------------------------ - * jQuery - * ------------------------------------------------------------------------ - */ + } // eslint-disable-next-line import/no-unused-modules - $.fn[NAME$3] = Collapse._jQueryInterface; - $.fn[NAME$3].Constructor = Collapse; - $.fn[NAME$3].noConflict = function () { - $.fn[NAME$3] = JQUERY_NO_CONFLICT$3; - return Collapse._jQueryInterface; + var computeStyles$1 = { + name: 'computeStyles', + enabled: true, + phase: 'beforeWrite', + fn: computeStyles, + data: {} }; - /**! - * @fileOverview Kickass library to create and place poppers near their reference elements. - * @version 1.14.7 - * @license - * Copyright (c) 2016 Federico Zivolo 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 isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'; + var passive = { + passive: true + }; - var longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox']; - var timeoutDuration = 0; - for (var i = 0; i < longerTimeoutBrowsers.length; i += 1) { - if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) { - timeoutDuration = 1; - break; + function effect(_ref) { + var state = _ref.state, + instance = _ref.instance, + options = _ref.options; + var _options$scroll = options.scroll, + scroll = _options$scroll === void 0 ? true : _options$scroll, + _options$resize = options.resize, + resize = _options$resize === void 0 ? true : _options$resize; + var window = getWindow(state.elements.popper); + var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper); + + if (scroll) { + scrollParents.forEach(function (scrollParent) { + scrollParent.addEventListener('scroll', instance.update, passive); + }); + } + + if (resize) { + window.addEventListener('resize', instance.update, passive); } - } - function microtaskDebounce(fn) { - var called = false; return function () { - if (called) { - return; + if (scroll) { + scrollParents.forEach(function (scrollParent) { + scrollParent.removeEventListener('scroll', instance.update, passive); + }); } - called = true; - window.Promise.resolve().then(function () { - called = false; - fn(); - }); - }; - } - function taskDebounce(fn) { - var scheduled = false; - return function () { - if (!scheduled) { - scheduled = true; - setTimeout(function () { - scheduled = false; - fn(); - }, timeoutDuration); + if (resize) { + window.removeEventListener('resize', instance.update, passive); } }; - } + } // eslint-disable-next-line import/no-unused-modules - var supportsMicroTasks = isBrowser && window.Promise; - /** - * Create a debounced version of a method, that's asynchronously deferred - * but called in the minimum time possible. - * - * @method - * @memberof Popper.Utils - * @argument {Function} fn - * @returns {Function} - */ - var debounce = supportsMicroTasks ? microtaskDebounce : taskDebounce; + var eventListeners = { + name: 'eventListeners', + enabled: true, + phase: 'write', + fn: function fn() {}, + effect: effect, + data: {} + }; - /** - * Check if the given variable is a function - * @method - * @memberof Popper.Utils - * @argument {Any} functionToCheck - variable to check - * @returns {Boolean} answer to: is a function? - */ - function isFunction(functionToCheck) { - var getType = {}; - return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; + var hash$1 = { + left: 'right', + right: 'left', + bottom: 'top', + top: 'bottom' + }; + function getOppositePlacement(placement) { + return placement.replace(/left|right|bottom|top/g, function (matched) { + return hash$1[matched]; + }); } - /** - * Get CSS computed property of the given element - * @method - * @memberof Popper.Utils - * @argument {Eement} element - * @argument {String} property - */ - function getStyleComputedProperty(element, property) { - if (element.nodeType !== 1) { - return []; - } - // NOTE: 1 DOM access here - var window = element.ownerDocument.defaultView; - var css = window.getComputedStyle(element, null); - return property ? css[property] : css; + var hash = { + start: 'end', + end: 'start' + }; + function getOppositeVariationPlacement(placement) { + return placement.replace(/start|end/g, function (matched) { + return hash[matched]; + }); } - /** - * Returns the parentNode or the host of the element - * @method - * @memberof Popper.Utils - * @argument {Element} element - * @returns {Element} parent - */ - function getParentNode(element) { - if (element.nodeName === 'HTML') { - return element; - } - return element.parentNode || element.host; + function getWindowScroll(node) { + var win = getWindow(node); + var scrollLeft = win.pageXOffset; + var scrollTop = win.pageYOffset; + return { + scrollLeft: scrollLeft, + scrollTop: scrollTop + }; } - /** - * Returns the scrolling parent of the given element - * @method - * @memberof Popper.Utils - * @argument {Element} element - * @returns {Element} scroll parent - */ - function getScrollParent(element) { - // Return body, `getScroll` will take care to get the correct `scrollTop` from it - if (!element) { - return document.body; - } + function getWindowScrollBarX(element) { + // If has a CSS width greater than the viewport, then this will be + // incorrect for RTL. + // Popper 1 is broken in this case and never had a bug report so let's assume + // it's not an issue. I don't think anyone ever specifies width on + // anyway. + // Browsers where the left scrollbar doesn't cause an issue report `0` for + // this (e.g. Edge 2019, IE11, Safari) + return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft; + } - switch (element.nodeName) { - case 'HTML': - case 'BODY': - return element.ownerDocument.body; - case '#document': - return element.body; + function getViewportRect(element) { + var win = getWindow(element); + var html = getDocumentElement(element); + var visualViewport = win.visualViewport; + var width = html.clientWidth; + var height = html.clientHeight; + var x = 0; + var y = 0; // NB: This isn't supported on iOS <= 12. If the keyboard is open, the popper + // can be obscured underneath it. + // Also, `html.clientHeight` adds the bottom bar height in Safari iOS, even + // if it isn't open, so if this isn't available, the popper will be detected + // to overflow the bottom of the screen too early. + + if (visualViewport) { + width = visualViewport.width; + height = visualViewport.height; // Uses Layout Viewport (like Chrome; Safari does not currently) + // In Chrome, it returns a value very close to 0 (+/-) but contains rounding + // errors due to floating point numbers, so we need to check precision. + // Safari returns a number <= 0, usually < -1 when pinch-zoomed + // Feature detection fails in mobile emulation mode in Chrome. + // Math.abs(win.innerWidth / visualViewport.scale - visualViewport.width) < + // 0.001 + // Fallback here: "Not Safari" userAgent + + if (!/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { + x = visualViewport.offsetLeft; + y = visualViewport.offsetTop; + } } - // Firefox want us to check `-x` and `-y` variations as well + return { + width: width, + height: height, + x: x + getWindowScrollBarX(element), + y: y + }; + } + + // of the `` and `` rect bounds if horizontally scrollable - var _getStyleComputedProp = getStyleComputedProperty(element), - overflow = _getStyleComputedProp.overflow, - overflowX = _getStyleComputedProp.overflowX, - overflowY = _getStyleComputedProp.overflowY; + function getDocumentRect(element) { + var _element$ownerDocumen; - if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) { - return element; + var html = getDocumentElement(element); + var winScroll = getWindowScroll(element); + var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body; + var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0); + var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0); + var x = -winScroll.scrollLeft + getWindowScrollBarX(element); + var y = -winScroll.scrollTop; + + if (getComputedStyle$1(body || html).direction === 'rtl') { + x += max(html.clientWidth, body ? body.clientWidth : 0) - width; } - return getScrollParent(getParentNode(element)); + return { + width: width, + height: height, + x: x, + y: y + }; } - var isIE11 = isBrowser && !!(window.MSInputMethodContext && document.documentMode); - var isIE10 = isBrowser && /MSIE 10/.test(navigator.userAgent); + function isScrollParent(element) { + // Firefox wants us to check `-x` and `-y` variations as well + var _getComputedStyle = getComputedStyle$1(element), + overflow = _getComputedStyle.overflow, + overflowX = _getComputedStyle.overflowX, + overflowY = _getComputedStyle.overflowY; - /** - * Determines if the browser is Internet Explorer - * @method - * @memberof Popper.Utils - * @param {Number} version to check - * @returns {Boolean} isIE - */ - function isIE(version) { - if (version === 11) { - return isIE11; - } - if (version === 10) { - return isIE10; - } - return isIE11 || isIE10; + return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX); } - /** - * Returns the offset parent of the given element - * @method - * @memberof Popper.Utils - * @argument {Element} element - * @returns {Element} offset parent - */ - function getOffsetParent(element) { - if (!element) { - return document.documentElement; + function getScrollParent(node) { + if (['html', 'body', '#document'].indexOf(getNodeName(node)) >= 0) { + // $FlowFixMe[incompatible-return]: assume body is always available + return node.ownerDocument.body; } - var noOffsetParent = isIE(10) ? document.body : null; - - // NOTE: 1 DOM access here - var offsetParent = element.offsetParent || null; - // Skip hidden elements which don't have an offsetParent - while (offsetParent === noOffsetParent && element.nextElementSibling) { - offsetParent = (element = element.nextElementSibling).offsetParent; + if (isHTMLElement(node) && isScrollParent(node)) { + return node; } - var nodeName = offsetParent && offsetParent.nodeName; + return getScrollParent(getParentNode(node)); + } - if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') { - return element ? element.ownerDocument.documentElement : document.documentElement; - } + /* + given a DOM element, return the list of all scroll parents, up the list of ancesors + until we get to the top window object. This list is what we attach scroll listeners + to, because if any of these parent elements scroll, we'll need to re-calculate the + reference element's position. + */ + + function listScrollParents(element, list) { + var _element$ownerDocumen; - // .offsetParent will return the closest TH, TD or TABLE in case - // no offsetParent is present, I hate this job... - if (['TH', 'TD', 'TABLE'].indexOf(offsetParent.nodeName) !== -1 && getStyleComputedProperty(offsetParent, 'position') === 'static') { - return getOffsetParent(offsetParent); + if (list === void 0) { + list = []; } - return offsetParent; + var scrollParent = getScrollParent(element); + var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body); + var win = getWindow(scrollParent); + var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent; + var updatedList = list.concat(target); + return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here + updatedList.concat(listScrollParents(getParentNode(target))); } - function isOffsetContainer(element) { - var nodeName = element.nodeName; - - if (nodeName === 'BODY') { - return false; - } - return nodeName === 'HTML' || getOffsetParent(element.firstElementChild) === element; + function rectToClientRect(rect) { + return Object.assign({}, rect, { + left: rect.x, + top: rect.y, + right: rect.x + rect.width, + bottom: rect.y + rect.height + }); } - /** - * Finds the root node (document, shadowDOM root) of the given element - * @method - * @memberof Popper.Utils - * @argument {Element} node - * @returns {Element} root node - */ - function getRoot(node) { - if (node.parentNode !== null) { - return getRoot(node.parentNode); - } - - return node; + function getInnerBoundingClientRect(element) { + var rect = getBoundingClientRect(element); + rect.top = rect.top + element.clientTop; + rect.left = rect.left + element.clientLeft; + rect.bottom = rect.top + element.clientHeight; + rect.right = rect.left + element.clientWidth; + rect.width = element.clientWidth; + rect.height = element.clientHeight; + rect.x = rect.left; + rect.y = rect.top; + return rect; } - /** - * Finds the offset parent common to the two provided nodes - * @method - * @memberof Popper.Utils - * @argument {Element} element1 - * @argument {Element} element2 - * @returns {Element} common offset parent - */ - function findCommonOffsetParent(element1, element2) { - // This check is needed to avoid errors in case one of the elements isn't defined for any reason - if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) { - return document.documentElement; - } - - // Here we make sure to give as "start" the element that comes first in the DOM - var order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING; - var start = order ? element1 : element2; - var end = order ? element2 : element1; + function getClientRectFromMixedType(element, clippingParent) { + return clippingParent === viewport ? rectToClientRect(getViewportRect(element)) : isHTMLElement(clippingParent) ? getInnerBoundingClientRect(clippingParent) : rectToClientRect(getDocumentRect(getDocumentElement(element))); + } // A "clipping parent" is an overflowable container with the characteristic of + // clipping (or hiding) overflowing elements with a position different from + // `initial` - // Get common ancestor container - var range = document.createRange(); - range.setStart(start, 0); - range.setEnd(end, 0); - var commonAncestorContainer = range.commonAncestorContainer; - // Both nodes are inside #document + function getClippingParents(element) { + var clippingParents = listScrollParents(getParentNode(element)); + var canEscapeClipping = ['absolute', 'fixed'].indexOf(getComputedStyle$1(element).position) >= 0; + var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element; - if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer || start.contains(end)) { - if (isOffsetContainer(commonAncestorContainer)) { - return commonAncestorContainer; - } + if (!isElement(clipperElement)) { + return []; + } // $FlowFixMe[incompatible-return]: https://github.com/facebook/flow/issues/1414 - return getOffsetParent(commonAncestorContainer); - } - // one of the nodes is inside shadowDOM, find which one - var element1root = getRoot(element1); - if (element1root.host) { - return findCommonOffsetParent(element1root.host, element2); - } else { - return findCommonOffsetParent(element1, getRoot(element2).host); - } + return clippingParents.filter(function (clippingParent) { + return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== 'body'; + }); + } // Gets the maximum area that the element is visible in due to any number of + // clipping parents + + + function getClippingRect(element, boundary, rootBoundary) { + var mainClippingParents = boundary === 'clippingParents' ? getClippingParents(element) : [].concat(boundary); + var clippingParents = [].concat(mainClippingParents, [rootBoundary]); + var firstClippingParent = clippingParents[0]; + var clippingRect = clippingParents.reduce(function (accRect, clippingParent) { + var rect = getClientRectFromMixedType(element, clippingParent); + accRect.top = max(rect.top, accRect.top); + accRect.right = min(rect.right, accRect.right); + accRect.bottom = min(rect.bottom, accRect.bottom); + accRect.left = max(rect.left, accRect.left); + return accRect; + }, getClientRectFromMixedType(element, firstClippingParent)); + clippingRect.width = clippingRect.right - clippingRect.left; + clippingRect.height = clippingRect.bottom - clippingRect.top; + clippingRect.x = clippingRect.left; + clippingRect.y = clippingRect.top; + return clippingRect; } - /** - * Gets the scroll value of the given element in the given side (top and left) - * @method - * @memberof Popper.Utils - * @argument {Element} element - * @argument {String} side `top` or `left` - * @returns {number} amount of scrolled pixels - */ - function getScroll(element) { - var side = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'top'; + function getVariation(placement) { + return placement.split('-')[1]; + } - var upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft'; - var nodeName = element.nodeName; + function computeOffsets(_ref) { + var reference = _ref.reference, + element = _ref.element, + placement = _ref.placement; + var basePlacement = placement ? getBasePlacement(placement) : null; + var variation = placement ? getVariation(placement) : null; + var commonX = reference.x + reference.width / 2 - element.width / 2; + var commonY = reference.y + reference.height / 2 - element.height / 2; + var offsets; + + switch (basePlacement) { + case top: + offsets = { + x: commonX, + y: reference.y - element.height + }; + break; - if (nodeName === 'BODY' || nodeName === 'HTML') { - var html = element.ownerDocument.documentElement; - var scrollingElement = element.ownerDocument.scrollingElement || html; - return scrollingElement[upperSide]; - } + case bottom: + offsets = { + x: commonX, + y: reference.y + reference.height + }; + break; - return element[upperSide]; - } + case right: + offsets = { + x: reference.x + reference.width, + y: commonY + }; + break; - /* - * Sum or subtract the element scroll values (left and top) from a given rect object - * @method - * @memberof Popper.Utils - * @param {Object} rect - Rect object you want to change - * @param {HTMLElement} element - The element from the function reads the scroll values - * @param {Boolean} subtract - set to true if you want to subtract the scroll values - * @return {Object} rect - The modifier rect object - */ - function includeScroll(rect, element) { - var subtract = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - - var scrollTop = getScroll(element, 'top'); - var scrollLeft = getScroll(element, 'left'); - var modifier = subtract ? -1 : 1; - rect.top += scrollTop * modifier; - rect.bottom += scrollTop * modifier; - rect.left += scrollLeft * modifier; - rect.right += scrollLeft * modifier; - return rect; - } + case left: + offsets = { + x: reference.x - element.width, + y: commonY + }; + break; - /* - * Helper to detect borders of a given element - * @method - * @memberof Popper.Utils - * @param {CSSStyleDeclaration} styles - * Result of `getStyleComputedProperty` on the given element - * @param {String} axis - `x` or `y` - * @return {number} borders - The borders size of the given axis - */ + default: + offsets = { + x: reference.x, + y: reference.y + }; + } - function getBordersSize(styles, axis) { - var sideA = axis === 'x' ? 'Left' : 'Top'; - var sideB = sideA === 'Left' ? 'Right' : 'Bottom'; + var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null; - return parseFloat(styles['border' + sideA + 'Width'], 10) + parseFloat(styles['border' + sideB + 'Width'], 10); - } + if (mainAxis != null) { + var len = mainAxis === 'y' ? 'height' : 'width'; - function getSize(axis, body, html, computedStyle) { - return Math.max(body['offset' + axis], body['scroll' + axis], html['client' + axis], html['offset' + axis], html['scroll' + axis], isIE(10) ? parseInt(html['offset' + axis]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Top' : 'Left')]) + parseInt(computedStyle['margin' + (axis === 'Height' ? 'Bottom' : 'Right')]) : 0); - } + switch (variation) { + case start: + offsets[mainAxis] = offsets[mainAxis] - (reference[len] / 2 - element[len] / 2); + break; - function getWindowSizes(document) { - var body = document.body; - var html = document.documentElement; - var computedStyle = isIE(10) && getComputedStyle(html); + case end: + offsets[mainAxis] = offsets[mainAxis] + (reference[len] / 2 - element[len] / 2); + break; + } + } - return { - height: getSize('Height', body, html, computedStyle), - width: getSize('Width', body, html, computedStyle) - }; + return offsets; } - var classCallCheck = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - }; - - var createClass = function () { - function defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } + function detectOverflow(state, options) { + if (options === void 0) { + options = {}; } - return function (Constructor, protoProps, staticProps) { - if (protoProps) defineProperties(Constructor.prototype, protoProps); - if (staticProps) defineProperties(Constructor, staticProps); - return Constructor; + var _options = options, + _options$placement = _options.placement, + placement = _options$placement === void 0 ? state.placement : _options$placement, + _options$boundary = _options.boundary, + boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, + _options$rootBoundary = _options.rootBoundary, + rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, + _options$elementConte = _options.elementContext, + elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, + _options$altBoundary = _options.altBoundary, + altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, + _options$padding = _options.padding, + padding = _options$padding === void 0 ? 0 : _options$padding; + var paddingObject = mergePaddingObject(typeof padding !== 'number' ? padding : expandToHashMap(padding, basePlacements)); + var altContext = elementContext === popper ? reference : popper; + var referenceElement = state.elements.reference; + var popperRect = state.rects.popper; + var element = state.elements[altBoundary ? altContext : elementContext]; + var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary); + var referenceClientRect = getBoundingClientRect(referenceElement); + var popperOffsets = computeOffsets({ + reference: referenceClientRect, + element: popperRect, + strategy: 'absolute', + placement: placement + }); + var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets)); + var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; // positive = overflowing the clipping rect + // 0 or negative = within the clipping rect + + var overflowOffsets = { + top: clippingClientRect.top - elementClientRect.top + paddingObject.top, + bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom, + left: clippingClientRect.left - elementClientRect.left + paddingObject.left, + right: elementClientRect.right - clippingClientRect.right + paddingObject.right }; - }(); + var offsetData = state.modifiersData.offset; // Offsets can be applied only to the popper element + + if (elementContext === popper && offsetData) { + var offset = offsetData[placement]; + Object.keys(overflowOffsets).forEach(function (key) { + var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1; + var axis = [top, bottom].indexOf(key) >= 0 ? 'y' : 'x'; + overflowOffsets[key] += offset[axis] * multiply; + }); + } + return overflowOffsets; + } + function computeAutoPlacement(state, options) { + if (options === void 0) { + options = {}; + } + var _options = options, + placement = _options.placement, + boundary = _options.boundary, + rootBoundary = _options.rootBoundary, + padding = _options.padding, + flipVariations = _options.flipVariations, + _options$allowedAutoP = _options.allowedAutoPlacements, + allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP; + var variation = getVariation(placement); + var placements$1 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function (placement) { + return getVariation(placement) === variation; + }) : basePlacements; + var allowedPlacements = placements$1.filter(function (placement) { + return allowedAutoPlacements.indexOf(placement) >= 0; + }); + if (allowedPlacements.length === 0) { + allowedPlacements = placements$1; + } // $FlowFixMe[incompatible-type]: Flow seems to have problems with two array unions... + + + var overflows = allowedPlacements.reduce(function (acc, placement) { + acc[placement] = detectOverflow(state, { + placement: placement, + boundary: boundary, + rootBoundary: rootBoundary, + padding: padding + })[getBasePlacement(placement)]; + return acc; + }, {}); + return Object.keys(overflows).sort(function (a, b) { + return overflows[a] - overflows[b]; + }); + } - var defineProperty = function (obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; + function getExpandedFallbackPlacements(placement) { + if (getBasePlacement(placement) === auto) { + return []; } - return obj; - }; + var oppositePlacement = getOppositePlacement(placement); + return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)]; + } - var _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; + function flip(_ref) { + var state = _ref.state, + options = _ref.options, + name = _ref.name; - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } + if (state.modifiersData[name]._skip) { + return; } - return target; - }; - - /** - * Given element offsets, generate an output similar to getBoundingClientRect - * @method - * @memberof Popper.Utils - * @argument {Object} offsets - * @returns {Object} ClientRect like output - */ - function getClientRect(offsets) { - return _extends({}, offsets, { - right: offsets.left + offsets.width, - bottom: offsets.top + offsets.height - }); - } + var _options$mainAxis = options.mainAxis, + checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, + _options$altAxis = options.altAxis, + checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, + specifiedFallbackPlacements = options.fallbackPlacements, + padding = options.padding, + boundary = options.boundary, + rootBoundary = options.rootBoundary, + altBoundary = options.altBoundary, + _options$flipVariatio = options.flipVariations, + flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, + allowedAutoPlacements = options.allowedAutoPlacements; + var preferredPlacement = state.options.placement; + var basePlacement = getBasePlacement(preferredPlacement); + var isBasePlacement = basePlacement === preferredPlacement; + var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement)); + var placements = [preferredPlacement].concat(fallbackPlacements).reduce(function (acc, placement) { + return acc.concat(getBasePlacement(placement) === auto ? computeAutoPlacement(state, { + placement: placement, + boundary: boundary, + rootBoundary: rootBoundary, + padding: padding, + flipVariations: flipVariations, + allowedAutoPlacements: allowedAutoPlacements + }) : placement); + }, []); + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var checksMap = new Map(); + var makeFallbackChecks = true; + var firstFittingPlacement = placements[0]; + + for (var i = 0; i < placements.length; i++) { + var placement = placements[i]; + + var _basePlacement = getBasePlacement(placement); + + var isStartVariation = getVariation(placement) === start; + var isVertical = [top, bottom].indexOf(_basePlacement) >= 0; + var len = isVertical ? 'width' : 'height'; + var overflow = detectOverflow(state, { + placement: placement, + boundary: boundary, + rootBoundary: rootBoundary, + altBoundary: altBoundary, + padding: padding + }); + var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top; - /** - * Get bounding client rect of given element - * @method - * @memberof Popper.Utils - * @param {HTMLElement} element - * @return {Object} client rect - */ - function getBoundingClientRect(element) { - var rect = {}; - - // IE10 10 FIX: Please, don't ask, the element isn't - // considered in DOM in some circumstances... - // This isn't reproducible in IE10 compatibility mode of IE11 - try { - if (isIE(10)) { - rect = element.getBoundingClientRect(); - var scrollTop = getScroll(element, 'top'); - var scrollLeft = getScroll(element, 'left'); - rect.top += scrollTop; - rect.left += scrollLeft; - rect.bottom += scrollTop; - rect.right += scrollLeft; - } else { - rect = element.getBoundingClientRect(); + if (referenceRect[len] > popperRect[len]) { + mainVariationSide = getOppositePlacement(mainVariationSide); } - } catch (e) {} - var result = { - left: rect.left, - top: rect.top, - width: rect.right - rect.left, - height: rect.bottom - rect.top - }; + var altVariationSide = getOppositePlacement(mainVariationSide); + var checks = []; - // subtract scrollbar size from sizes - var sizes = element.nodeName === 'HTML' ? getWindowSizes(element.ownerDocument) : {}; - var width = sizes.width || element.clientWidth || result.right - result.left; - var height = sizes.height || element.clientHeight || result.bottom - result.top; + if (checkMainAxis) { + checks.push(overflow[_basePlacement] <= 0); + } - var horizScrollbar = element.offsetWidth - width; - var vertScrollbar = element.offsetHeight - height; + if (checkAltAxis) { + checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0); + } - // if an hypothetical scrollbar is detected, we must be sure it's not a `border` - // we make this check conditional for performance reasons - if (horizScrollbar || vertScrollbar) { - var styles = getStyleComputedProperty(element); - horizScrollbar -= getBordersSize(styles, 'x'); - vertScrollbar -= getBordersSize(styles, 'y'); + if (checks.every(function (check) { + return check; + })) { + firstFittingPlacement = placement; + makeFallbackChecks = false; + break; + } - result.width -= horizScrollbar; - result.height -= vertScrollbar; + checksMap.set(placement, checks); } - return getClientRect(result); - } + if (makeFallbackChecks) { + // `2` may be desired in some cases – research later + var numberOfChecks = flipVariations ? 3 : 1; - function getOffsetRectRelativeToArbitraryNode(children, parent) { - var fixedPosition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - - var isIE10 = isIE(10); - var isHTML = parent.nodeName === 'HTML'; - var childrenRect = getBoundingClientRect(children); - var parentRect = getBoundingClientRect(parent); - var scrollParent = getScrollParent(children); - - var styles = getStyleComputedProperty(parent); - var borderTopWidth = parseFloat(styles.borderTopWidth, 10); - var borderLeftWidth = parseFloat(styles.borderLeftWidth, 10); - - // In cases where the parent is fixed, we must ignore negative scroll in offset calc - if (fixedPosition && isHTML) { - parentRect.top = Math.max(parentRect.top, 0); - parentRect.left = Math.max(parentRect.left, 0); - } - var offsets = getClientRect({ - top: childrenRect.top - parentRect.top - borderTopWidth, - left: childrenRect.left - parentRect.left - borderLeftWidth, - width: childrenRect.width, - height: childrenRect.height - }); - offsets.marginTop = 0; - offsets.marginLeft = 0; + var _loop = function _loop(_i) { + var fittingPlacement = placements.find(function (placement) { + var checks = checksMap.get(placement); - // Subtract margins of documentElement in case it's being used as parent - // we do this only on HTML because it's the only element that behaves - // differently when margins are applied to it. The margins are included in - // the box of the documentElement, in the other cases not. - if (!isIE10 && isHTML) { - var marginTop = parseFloat(styles.marginTop, 10); - var marginLeft = parseFloat(styles.marginLeft, 10); + if (checks) { + return checks.slice(0, _i).every(function (check) { + return check; + }); + } + }); - offsets.top -= borderTopWidth - marginTop; - offsets.bottom -= borderTopWidth - marginTop; - offsets.left -= borderLeftWidth - marginLeft; - offsets.right -= borderLeftWidth - marginLeft; + if (fittingPlacement) { + firstFittingPlacement = fittingPlacement; + return "break"; + } + }; - // Attach marginTop and marginLeft because in some circumstances we may need them - offsets.marginTop = marginTop; - offsets.marginLeft = marginLeft; - } + for (var _i = numberOfChecks; _i > 0; _i--) { + var _ret = _loop(_i); - if (isIE10 && !fixedPosition ? parent.contains(scrollParent) : parent === scrollParent && scrollParent.nodeName !== 'BODY') { - offsets = includeScroll(offsets, parent); + if (_ret === "break") break; + } } - return offsets; - } + if (state.placement !== firstFittingPlacement) { + state.modifiersData[name]._skip = true; + state.placement = firstFittingPlacement; + state.reset = true; + } + } // eslint-disable-next-line import/no-unused-modules - function getViewportOffsetRectRelativeToArtbitraryNode(element) { - var excludeScroll = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var html = element.ownerDocument.documentElement; - var relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html); - var width = Math.max(html.clientWidth, window.innerWidth || 0); - var height = Math.max(html.clientHeight, window.innerHeight || 0); + var flip$1 = { + name: 'flip', + enabled: true, + phase: 'main', + fn: flip, + requiresIfExists: ['offset'], + data: { + _skip: false + } + }; - var scrollTop = !excludeScroll ? getScroll(html) : 0; - var scrollLeft = !excludeScroll ? getScroll(html, 'left') : 0; + function getSideOffsets(overflow, rect, preventedOffsets) { + if (preventedOffsets === void 0) { + preventedOffsets = { + x: 0, + y: 0 + }; + } - var offset = { - top: scrollTop - relativeOffset.top + relativeOffset.marginTop, - left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft, - width: width, - height: height + return { + top: overflow.top - rect.height - preventedOffsets.y, + right: overflow.right - rect.width + preventedOffsets.x, + bottom: overflow.bottom - rect.height + preventedOffsets.y, + left: overflow.left - rect.width - preventedOffsets.x }; - - return getClientRect(offset); } - /** - * Check if the given element is fixed or is inside a fixed parent - * @method - * @memberof Popper.Utils - * @argument {Element} element - * @argument {Element} customContainer - * @returns {Boolean} answer to "isFixed?" - */ - function isFixed(element) { - var nodeName = element.nodeName; - if (nodeName === 'BODY' || nodeName === 'HTML') { - return false; - } - if (getStyleComputedProperty(element, 'position') === 'fixed') { - return true; - } - var parentNode = getParentNode(element); - if (!parentNode) { - return false; - } - return isFixed(parentNode); + function isAnySideFullyClipped(overflow) { + return [top, right, bottom, left].some(function (side) { + return overflow[side] >= 0; + }); } - /** - * Finds the first parent of an element that has a transformed property defined - * @method - * @memberof Popper.Utils - * @argument {Element} element - * @returns {Element} first transformed parent or documentElement - */ - - function getFixedPositionOffsetParent(element) { - // This check is needed to avoid errors in case one of the elements isn't defined for any reason - if (!element || !element.parentElement || isIE()) { - return document.documentElement; - } - var el = element.parentElement; - while (el && getStyleComputedProperty(el, 'transform') === 'none') { - el = el.parentElement; - } - return el || document.documentElement; - } + function hide(_ref) { + var state = _ref.state, + name = _ref.name; + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var preventedOffsets = state.modifiersData.preventOverflow; + var referenceOverflow = detectOverflow(state, { + elementContext: 'reference' + }); + var popperAltOverflow = detectOverflow(state, { + altBoundary: true + }); + var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect); + var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets); + var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets); + var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets); + state.modifiersData[name] = { + referenceClippingOffsets: referenceClippingOffsets, + popperEscapeOffsets: popperEscapeOffsets, + isReferenceHidden: isReferenceHidden, + hasPopperEscaped: hasPopperEscaped + }; + state.attributes.popper = Object.assign({}, state.attributes.popper, { + 'data-popper-reference-hidden': isReferenceHidden, + 'data-popper-escaped': hasPopperEscaped + }); + } // eslint-disable-next-line import/no-unused-modules - /** - * Computed the boundaries limits and return them - * @method - * @memberof Popper.Utils - * @param {HTMLElement} popper - * @param {HTMLElement} reference - * @param {number} padding - * @param {HTMLElement} boundariesElement - Element used to define the boundaries - * @param {Boolean} fixedPosition - Is in fixed position mode - * @returns {Object} Coordinates of the boundaries - */ - function getBoundaries(popper, reference, padding, boundariesElement) { - var fixedPosition = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; - // NOTE: 1 DOM access here + var hide$1 = { + name: 'hide', + enabled: true, + phase: 'main', + requiresIfExists: ['preventOverflow'], + fn: hide + }; - var boundaries = { top: 0, left: 0 }; - var offsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, reference); + function distanceAndSkiddingToXY(placement, rects, offset) { + var basePlacement = getBasePlacement(placement); + var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1; + + var _ref = typeof offset === 'function' ? offset(Object.assign({}, rects, { + placement: placement + })) : offset, + skidding = _ref[0], + distance = _ref[1]; + + skidding = skidding || 0; + distance = (distance || 0) * invertDistance; + return [left, right].indexOf(basePlacement) >= 0 ? { + x: distance, + y: skidding + } : { + x: skidding, + y: distance + }; + } - // Handle viewport case - if (boundariesElement === 'viewport') { - boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent, fixedPosition); - } else { - // Handle other cases based on DOM element used as boundaries - var boundariesNode = void 0; - if (boundariesElement === 'scrollParent') { - boundariesNode = getScrollParent(getParentNode(reference)); - if (boundariesNode.nodeName === 'BODY') { - boundariesNode = popper.ownerDocument.documentElement; - } - } else if (boundariesElement === 'window') { - boundariesNode = popper.ownerDocument.documentElement; - } else { - boundariesNode = boundariesElement; - } + function offset(_ref2) { + var state = _ref2.state, + options = _ref2.options, + name = _ref2.name; + var _options$offset = options.offset, + offset = _options$offset === void 0 ? [0, 0] : _options$offset; + var data = placements.reduce(function (acc, placement) { + acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset); + return acc; + }, {}); + var _data$state$placement = data[state.placement], + x = _data$state$placement.x, + y = _data$state$placement.y; + + if (state.modifiersData.popperOffsets != null) { + state.modifiersData.popperOffsets.x += x; + state.modifiersData.popperOffsets.y += y; + } - var offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent, fixedPosition); + state.modifiersData[name] = data; + } // eslint-disable-next-line import/no-unused-modules - // In case of HTML, we need a different computation - if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) { - var _getWindowSizes = getWindowSizes(popper.ownerDocument), - height = _getWindowSizes.height, - width = _getWindowSizes.width; - boundaries.top += offsets.top - offsets.marginTop; - boundaries.bottom = height + offsets.top; - boundaries.left += offsets.left - offsets.marginLeft; - boundaries.right = width + offsets.left; - } else { - // for all the other DOM elements, this one is good - boundaries = offsets; - } - } + var offset$1 = { + name: 'offset', + enabled: true, + phase: 'main', + requires: ['popperOffsets'], + fn: offset + }; - // Add paddings - padding = padding || 0; - var isPaddingNumber = typeof padding === 'number'; - boundaries.left += isPaddingNumber ? padding : padding.left || 0; - boundaries.top += isPaddingNumber ? padding : padding.top || 0; - boundaries.right -= isPaddingNumber ? padding : padding.right || 0; - boundaries.bottom -= isPaddingNumber ? padding : padding.bottom || 0; + function popperOffsets(_ref) { + var state = _ref.state, + name = _ref.name; + // Offsets are the actual position the popper needs to have to be + // properly positioned near its reference element + // This is the most basic placement, and will be adjusted by + // the modifiers in the next step + state.modifiersData[name] = computeOffsets({ + reference: state.rects.reference, + element: state.rects.popper, + strategy: 'absolute', + placement: state.placement + }); + } // eslint-disable-next-line import/no-unused-modules - return boundaries; - } - function getArea(_ref) { - var width = _ref.width, - height = _ref.height; + var popperOffsets$1 = { + name: 'popperOffsets', + enabled: true, + phase: 'read', + fn: popperOffsets, + data: {} + }; - return width * height; + function getAltAxis(axis) { + return axis === 'x' ? 'y' : 'x'; } - /** - * Utility used to transform the `auto` placement to the placement with more - * available space. - * @method - * @memberof Popper.Utils - * @argument {Object} data - The data object generated by update method - * @argument {Object} options - Modifiers configuration and options - * @returns {Object} The data object, properly modified - */ - function computeAutoPlacement(placement, refRect, popper, reference, boundariesElement) { - var padding = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; + function preventOverflow(_ref) { + var state = _ref.state, + options = _ref.options, + name = _ref.name; + var _options$mainAxis = options.mainAxis, + checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, + _options$altAxis = options.altAxis, + checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, + boundary = options.boundary, + rootBoundary = options.rootBoundary, + altBoundary = options.altBoundary, + padding = options.padding, + _options$tether = options.tether, + tether = _options$tether === void 0 ? true : _options$tether, + _options$tetherOffset = options.tetherOffset, + tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset; + var overflow = detectOverflow(state, { + boundary: boundary, + rootBoundary: rootBoundary, + padding: padding, + altBoundary: altBoundary + }); + var basePlacement = getBasePlacement(state.placement); + var variation = getVariation(state.placement); + var isBasePlacement = !variation; + var mainAxis = getMainAxisFromPlacement(basePlacement); + var altAxis = getAltAxis(mainAxis); + var popperOffsets = state.modifiersData.popperOffsets; + var referenceRect = state.rects.reference; + var popperRect = state.rects.popper; + var tetherOffsetValue = typeof tetherOffset === 'function' ? tetherOffset(Object.assign({}, state.rects, { + placement: state.placement + })) : tetherOffset; + var data = { + x: 0, + y: 0 + }; - if (placement.indexOf('auto') === -1) { - return placement; + if (!popperOffsets) { + return; } - var boundaries = getBoundaries(popper, reference, padding, boundariesElement); + if (checkMainAxis || checkAltAxis) { + var mainSide = mainAxis === 'y' ? top : left; + var altSide = mainAxis === 'y' ? bottom : right; + var len = mainAxis === 'y' ? 'height' : 'width'; + var offset = popperOffsets[mainAxis]; + var min$1 = popperOffsets[mainAxis] + overflow[mainSide]; + var max$1 = popperOffsets[mainAxis] - overflow[altSide]; + var additive = tether ? -popperRect[len] / 2 : 0; + var minLen = variation === start ? referenceRect[len] : popperRect[len]; + var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; // We need to include the arrow in the calculation so the arrow doesn't go + // outside the reference bounds + + var arrowElement = state.elements.arrow; + var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : { + width: 0, + height: 0 + }; + var arrowPaddingObject = state.modifiersData['arrow#persistent'] ? state.modifiersData['arrow#persistent'].padding : getFreshSideObject(); + var arrowPaddingMin = arrowPaddingObject[mainSide]; + var arrowPaddingMax = arrowPaddingObject[altSide]; // If the reference length is smaller than the arrow length, we don't want + // to include its full size in the calculation. If the reference is small + // and near the edge of a boundary, the popper can overflow even if the + // reference is not overflowing as well (e.g. virtual elements with no + // width or height) - var rects = { - top: { - width: boundaries.width, - height: refRect.top - boundaries.top - }, - right: { - width: boundaries.right - refRect.right, - height: boundaries.height - }, - bottom: { - width: boundaries.width, - height: boundaries.bottom - refRect.bottom - }, - left: { - width: refRect.left - boundaries.left, - height: boundaries.height + var arrowLen = within(0, referenceRect[len], arrowRect[len]); + var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - tetherOffsetValue : minLen - arrowLen - arrowPaddingMin - tetherOffsetValue; + var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + tetherOffsetValue : maxLen + arrowLen + arrowPaddingMax + tetherOffsetValue; + var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow); + var clientOffset = arrowOffsetParent ? mainAxis === 'y' ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0; + var offsetModifierValue = state.modifiersData.offset ? state.modifiersData.offset[state.placement][mainAxis] : 0; + var tetherMin = popperOffsets[mainAxis] + minOffset - offsetModifierValue - clientOffset; + var tetherMax = popperOffsets[mainAxis] + maxOffset - offsetModifierValue; + + if (checkMainAxis) { + var preventedOffset = within(tether ? min(min$1, tetherMin) : min$1, offset, tether ? max(max$1, tetherMax) : max$1); + popperOffsets[mainAxis] = preventedOffset; + data[mainAxis] = preventedOffset - offset; } - }; - var sortedAreas = Object.keys(rects).map(function (key) { - return _extends({ - key: key - }, rects[key], { - area: getArea(rects[key]) - }); - }).sort(function (a, b) { - return b.area - a.area; - }); + if (checkAltAxis) { + var _mainSide = mainAxis === 'x' ? top : left; - var filteredAreas = sortedAreas.filter(function (_ref2) { - var width = _ref2.width, - height = _ref2.height; - return width >= popper.clientWidth && height >= popper.clientHeight; - }); + var _altSide = mainAxis === 'x' ? bottom : right; - var computedPlacement = filteredAreas.length > 0 ? filteredAreas[0].key : sortedAreas[0].key; + var _offset = popperOffsets[altAxis]; - var variation = placement.split('-')[1]; + var _min = _offset + overflow[_mainSide]; - return computedPlacement + (variation ? '-' + variation : ''); - } + var _max = _offset - overflow[_altSide]; - /** - * Get offsets to the reference element - * @method - * @memberof Popper.Utils - * @param {Object} state - * @param {Element} popper - the popper element - * @param {Element} reference - the reference element (the popper will be relative to this) - * @param {Element} fixedPosition - is in fixed position mode - * @returns {Object} An object containing the offsets which will be applied to the popper - */ - function getReferenceOffsets(state, popper, reference) { - var fixedPosition = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; + var _preventedOffset = within(tether ? min(_min, tetherMin) : _min, _offset, tether ? max(_max, tetherMax) : _max); - var commonOffsetParent = fixedPosition ? getFixedPositionOffsetParent(popper) : findCommonOffsetParent(popper, reference); - return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent, fixedPosition); - } + popperOffsets[altAxis] = _preventedOffset; + data[altAxis] = _preventedOffset - _offset; + } + } - /** - * Get the outer sizes of the given element (offset size + margins) - * @method - * @memberof Popper.Utils - * @argument {Element} element - * @returns {Object} object containing width and height properties - */ - function getOuterSizes(element) { - var window = element.ownerDocument.defaultView; - var styles = window.getComputedStyle(element); - var x = parseFloat(styles.marginTop || 0) + parseFloat(styles.marginBottom || 0); - var y = parseFloat(styles.marginLeft || 0) + parseFloat(styles.marginRight || 0); - var result = { - width: element.offsetWidth + y, - height: element.offsetHeight + x + state.modifiersData[name] = data; + } // eslint-disable-next-line import/no-unused-modules + + + var preventOverflow$1 = { + name: 'preventOverflow', + enabled: true, + phase: 'main', + fn: preventOverflow, + requiresIfExists: ['offset'] + }; + + function getHTMLElementScroll(element) { + return { + scrollLeft: element.scrollLeft, + scrollTop: element.scrollTop }; - return result; } - /** - * Get the opposite placement of the given one - * @method - * @memberof Popper.Utils - * @argument {String} placement - * @returns {String} flipped placement - */ - function getOppositePlacement(placement) { - var hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; - return placement.replace(/left|right|bottom|top/g, function (matched) { - return hash[matched]; - }); + function getNodeScroll(node) { + if (node === getWindow(node) || !isHTMLElement(node)) { + return getWindowScroll(node); + } else { + return getHTMLElementScroll(node); + } } - /** - * Get offsets to the popper - * @method - * @memberof Popper.Utils - * @param {Object} position - CSS position the Popper will get applied - * @param {HTMLElement} popper - the popper element - * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this) - * @param {String} placement - one of the valid placement options - * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper - */ - function getPopperOffsets(popper, referenceOffsets, placement) { - placement = placement.split('-')[0]; - - // Get popper node sizes - var popperRect = getOuterSizes(popper); + function isElementScaled(element) { + var rect = element.getBoundingClientRect(); + var scaleX = rect.width / element.offsetWidth || 1; + var scaleY = rect.height / element.offsetHeight || 1; + return scaleX !== 1 || scaleY !== 1; + } // Returns the composite rect of an element relative to its offsetParent. + // Composite means it takes into account transforms as well as layout. - // Add position, width and height to our offsets object - var popperOffsets = { - width: popperRect.width, - height: popperRect.height - }; - - // depending by the popper placement we have to compute its offsets slightly differently - var isHoriz = ['right', 'left'].indexOf(placement) !== -1; - var mainSide = isHoriz ? 'top' : 'left'; - var secondarySide = isHoriz ? 'left' : 'top'; - var measurement = isHoriz ? 'height' : 'width'; - var secondaryMeasurement = !isHoriz ? 'height' : 'width'; - popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2; - if (placement === secondarySide) { - popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement]; - } else { - popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)]; + function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) { + if (isFixed === void 0) { + isFixed = false; } - return popperOffsets; - } + var isOffsetParentAnElement = isHTMLElement(offsetParent); + var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent); + var documentElement = getDocumentElement(offsetParent); + var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled); + var scroll = { + scrollLeft: 0, + scrollTop: 0 + }; + var offsets = { + x: 0, + y: 0 + }; - /** - * Mimics the `find` method of Array - * @method - * @memberof Popper.Utils - * @argument {Array} arr - * @argument prop - * @argument value - * @returns index or -1 - */ - function find(arr, check) { - // use native find if supported - if (Array.prototype.find) { - return arr.find(check); + if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { + if (getNodeName(offsetParent) !== 'body' || // https://github.com/popperjs/popper-core/issues/1078 + isScrollParent(documentElement)) { + scroll = getNodeScroll(offsetParent); + } + + if (isHTMLElement(offsetParent)) { + offsets = getBoundingClientRect(offsetParent, true); + offsets.x += offsetParent.clientLeft; + offsets.y += offsetParent.clientTop; + } else if (documentElement) { + offsets.x = getWindowScrollBarX(documentElement); + } } - // use `filter` to obtain the same behavior of `find` - return arr.filter(check)[0]; + return { + x: rect.left + scroll.scrollLeft - offsets.x, + y: rect.top + scroll.scrollTop - offsets.y, + width: rect.width, + height: rect.height + }; } - /** - * Return the index of the matching object - * @method - * @memberof Popper.Utils - * @argument {Array} arr - * @argument prop - * @argument value - * @returns index or -1 - */ - function findIndex(arr, prop, value) { - // use native findIndex if supported - if (Array.prototype.findIndex) { - return arr.findIndex(function (cur) { - return cur[prop] === value; + function order(modifiers) { + var map = new Map(); + var visited = new Set(); + var result = []; + modifiers.forEach(function (modifier) { + map.set(modifier.name, modifier); + }); // On visiting object, check for its dependencies and visit them recursively + + function sort(modifier) { + visited.add(modifier.name); + var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []); + requires.forEach(function (dep) { + if (!visited.has(dep)) { + var depModifier = map.get(dep); + + if (depModifier) { + sort(depModifier); + } + } }); + result.push(modifier); } - // use `find` + `indexOf` if `findIndex` isn't supported - var match = find(arr, function (obj) { - return obj[prop] === value; + modifiers.forEach(function (modifier) { + if (!visited.has(modifier.name)) { + // check for visited object + sort(modifier); + } }); - return arr.indexOf(match); + return result; } - /** - * Loop trough the list of modifiers and run them in order, - * each of them will then edit the data object. - * @method - * @memberof Popper.Utils - * @param {dataObject} data - * @param {Array} modifiers - * @param {String} ends - Optional modifier name used as stopper - * @returns {dataObject} - */ - function runModifiers(modifiers, data, ends) { - var modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends)); + function orderModifiers(modifiers) { + // order based on dependencies + var orderedModifiers = order(modifiers); // order based on phase - modifiersToRun.forEach(function (modifier) { - if (modifier['function']) { - // eslint-disable-line dot-notation - console.warn('`modifier.function` is deprecated, use `modifier.fn`!'); - } - var fn = modifier['function'] || modifier.fn; // eslint-disable-line dot-notation - if (modifier.enabled && isFunction(fn)) { - // Add properties to offsets to make them a complete clientRect object - // we do this before each modifier to make sure the previous one doesn't - // mess with these values - data.offsets.popper = getClientRect(data.offsets.popper); - data.offsets.reference = getClientRect(data.offsets.reference); + return modifierPhases.reduce(function (acc, phase) { + return acc.concat(orderedModifiers.filter(function (modifier) { + return modifier.phase === phase; + })); + }, []); + } - data = fn(data, modifier); + function debounce(fn) { + var pending; + return function () { + if (!pending) { + pending = new Promise(function (resolve) { + Promise.resolve().then(function () { + pending = undefined; + resolve(fn()); + }); + }); } + + return pending; + }; + } + + function mergeByName(modifiers) { + var merged = modifiers.reduce(function (merged, current) { + var existing = merged[current.name]; + merged[current.name] = existing ? Object.assign({}, existing, current, { + options: Object.assign({}, existing.options, current.options), + data: Object.assign({}, existing.data, current.data) + }) : current; + return merged; + }, {}); // IE11 does not support Object.values + + return Object.keys(merged).map(function (key) { + return merged[key]; }); + } + + var DEFAULT_OPTIONS = { + placement: 'bottom', + modifiers: [], + strategy: 'absolute' + }; + + function areValidElements() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } - return data; + return !args.some(function (element) { + return !(element && typeof element.getBoundingClientRect === 'function'); + }); } - /** - * Updates the position of the popper, computing the new offsets and applying - * the new style.
- * Prefer `scheduleUpdate` over `update` because of performance reasons. - * @method - * @memberof Popper - */ - function update() { - // if popper is destroyed, don't perform any further update - if (this.state.isDestroyed) { - return; + function popperGenerator(generatorOptions) { + if (generatorOptions === void 0) { + generatorOptions = {}; } - var data = { - instance: this, - styles: {}, - arrowStyles: {}, - attributes: {}, - flipped: false, - offsets: {} - }; + var _generatorOptions = generatorOptions, + _generatorOptions$def = _generatorOptions.defaultModifiers, + defaultModifiers = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, + _generatorOptions$def2 = _generatorOptions.defaultOptions, + defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2; + return function createPopper(reference, popper, options) { + if (options === void 0) { + options = defaultOptions; + } + + var state = { + placement: 'bottom', + orderedModifiers: [], + options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions), + modifiersData: {}, + elements: { + reference: reference, + popper: popper + }, + attributes: {}, + styles: {} + }; + var effectCleanupFns = []; + var isDestroyed = false; + var instance = { + state: state, + setOptions: function setOptions(options) { + cleanupModifierEffects(); + state.options = Object.assign({}, defaultOptions, state.options, options); + state.scrollParents = { + reference: isElement(reference) ? listScrollParents(reference) : reference.contextElement ? listScrollParents(reference.contextElement) : [], + popper: listScrollParents(popper) + }; // Orders the modifiers based on their dependencies and `phase` + // properties + + var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers, state.options.modifiers))); // Strip out disabled modifiers + + state.orderedModifiers = orderedModifiers.filter(function (m) { + return m.enabled; + }); // Validate the provided modifiers so that the consumer will get warned + + runModifierEffects(); + return instance.update(); + }, + // Sync update – it will always be executed, even if not necessary. This + // is useful for low frequency updates where sync behavior simplifies the + // logic. + // For high frequency updates (e.g. `resize` and `scroll` events), always + // prefer the async Popper#update method + forceUpdate: function forceUpdate() { + if (isDestroyed) { + return; + } - // compute reference element offsets - data.offsets.reference = getReferenceOffsets(this.state, this.popper, this.reference, this.options.positionFixed); + var _state$elements = state.elements, + reference = _state$elements.reference, + popper = _state$elements.popper; // Don't proceed if `reference` or `popper` are not valid elements + // anymore - // compute auto placement, store placement inside the data object, - // modifiers will be able to edit `placement` if needed - // and refer to originalPlacement to know the original value - data.placement = computeAutoPlacement(this.options.placement, data.offsets.reference, this.popper, this.reference, this.options.modifiers.flip.boundariesElement, this.options.modifiers.flip.padding); + if (!areValidElements(reference, popper)) { - // store the computed placement inside `originalPlacement` - data.originalPlacement = data.placement; + return; + } // Store the reference and popper rects to be read by modifiers + + + state.rects = { + reference: getCompositeRect(reference, getOffsetParent(popper), state.options.strategy === 'fixed'), + popper: getLayoutRect(popper) + }; // Modifiers have the ability to reset the current update cycle. The + // most common use case for this is the `flip` modifier changing the + // placement, which then needs to re-run all the modifiers, because the + // logic was previously ran for the previous placement and is therefore + // stale/incorrect + + state.reset = false; + state.placement = state.options.placement; // On each update cycle, the `modifiersData` property for each modifier + // is filled with the initial data specified by the modifier. This means + // it doesn't persist and is fresh on each update. + // To ensure persistent data, use `${name}#persistent` + + state.orderedModifiers.forEach(function (modifier) { + return state.modifiersData[modifier.name] = Object.assign({}, modifier.data); + }); - data.positionFixed = this.options.positionFixed; + for (var index = 0; index < state.orderedModifiers.length; index++) { - // compute the popper offsets - data.offsets.popper = getPopperOffsets(this.popper, data.offsets.reference, data.placement); + if (state.reset === true) { + state.reset = false; + index = -1; + continue; + } - data.offsets.popper.position = this.options.positionFixed ? 'fixed' : 'absolute'; + var _state$orderedModifie = state.orderedModifiers[index], + fn = _state$orderedModifie.fn, + _state$orderedModifie2 = _state$orderedModifie.options, + _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, + name = _state$orderedModifie.name; + + if (typeof fn === 'function') { + state = fn({ + state: state, + options: _options, + name: name, + instance: instance + }) || state; + } + } + }, + // Async and optimistically optimized update – it will not be executed if + // not necessary (debounced to run at most once-per-tick) + update: debounce(function () { + return new Promise(function (resolve) { + instance.forceUpdate(); + resolve(state); + }); + }), + destroy: function destroy() { + cleanupModifierEffects(); + isDestroyed = true; + } + }; - // run the modifiers - data = runModifiers(this.modifiers, data); + if (!areValidElements(reference, popper)) { - // the first `update` will call `onCreate` callback - // the other ones will call `onUpdate` callback - if (!this.state.isCreated) { - this.state.isCreated = true; - this.options.onCreate(data); - } else { - this.options.onUpdate(data); - } + return instance; + } + + instance.setOptions(options).then(function (state) { + if (!isDestroyed && options.onFirstUpdate) { + options.onFirstUpdate(state); + } + }); // Modifiers have the ability to execute arbitrary code before the first + // update cycle runs. They will be executed in the same order as the update + // cycle. This is useful when a modifier adds some persistent data that + // other modifiers need to use, but the modifier is run after the dependent + // one. + + function runModifierEffects() { + state.orderedModifiers.forEach(function (_ref3) { + var name = _ref3.name, + _ref3$options = _ref3.options, + options = _ref3$options === void 0 ? {} : _ref3$options, + effect = _ref3.effect; + + if (typeof effect === 'function') { + var cleanupFn = effect({ + state: state, + name: name, + instance: instance, + options: options + }); + + var noopFn = function noopFn() {}; + + effectCleanupFns.push(cleanupFn || noopFn); + } + }); + } + + function cleanupModifierEffects() { + effectCleanupFns.forEach(function (fn) { + return fn(); + }); + effectCleanupFns = []; + } + + return instance; + }; } + var createPopper$2 = /*#__PURE__*/popperGenerator(); // eslint-disable-next-line import/no-unused-modules + + var defaultModifiers$1 = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1]; + var createPopper$1 = /*#__PURE__*/popperGenerator({ + defaultModifiers: defaultModifiers$1 + }); // eslint-disable-next-line import/no-unused-modules + + var defaultModifiers = [eventListeners, popperOffsets$1, computeStyles$1, applyStyles$1, offset$1, flip$1, preventOverflow$1, arrow$1, hide$1]; + var createPopper = /*#__PURE__*/popperGenerator({ + defaultModifiers: defaultModifiers + }); // eslint-disable-next-line import/no-unused-modules + + var Popper = /*#__PURE__*/Object.freeze({ + __proto__: null, + popperGenerator: popperGenerator, + detectOverflow: detectOverflow, + createPopperBase: createPopper$2, + createPopper: createPopper, + createPopperLite: createPopper$1, + top: top, + bottom: bottom, + right: right, + left: left, + auto: auto, + basePlacements: basePlacements, + start: start, + end: end, + clippingParents: clippingParents, + viewport: viewport, + popper: popper, + reference: reference, + variationPlacements: variationPlacements, + placements: placements, + beforeRead: beforeRead, + read: read, + afterRead: afterRead, + beforeMain: beforeMain, + main: main, + afterMain: afterMain, + beforeWrite: beforeWrite, + write: write, + afterWrite: afterWrite, + modifierPhases: modifierPhases, + applyStyles: applyStyles$1, + arrow: arrow$1, + computeStyles: computeStyles$1, + eventListeners: eventListeners, + flip: flip$1, + hide: hide$1, + offset: offset$1, + popperOffsets: popperOffsets$1, + preventOverflow: preventOverflow$1 + }); /** - * Helper used to know if the given modifier is enabled. - * @method - * @memberof Popper.Utils - * @returns {Boolean} + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): dropdown.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- */ - function isModifierEnabled(modifiers, modifierName) { - return modifiers.some(function (_ref) { - var name = _ref.name, - enabled = _ref.enabled; - return enabled && name === modifierName; - }); - } - /** - * Get the prefixed supported property name - * @method - * @memberof Popper.Utils - * @argument {String} property (camelCase) - * @returns {String} prefixed property (camelCase or PascalCase, depending on the vendor prefix) + * ------------------------------------------------------------------------ + * Constants + * ------------------------------------------------------------------------ */ - function getSupportedPropertyName(property) { - var prefixes = [false, 'ms', 'Webkit', 'Moz', 'O']; - var upperProp = property.charAt(0).toUpperCase() + property.slice(1); - - for (var i = 0; i < prefixes.length; i++) { - var prefix = prefixes[i]; - var toCheck = prefix ? '' + prefix + upperProp : property; - if (typeof document.body.style[toCheck] !== 'undefined') { - return toCheck; - } - } - return null; - } + const NAME$9 = 'dropdown'; + const DATA_KEY$8 = 'bs.dropdown'; + const EVENT_KEY$8 = `.${DATA_KEY$8}`; + const DATA_API_KEY$4 = '.data-api'; + const ESCAPE_KEY$2 = 'Escape'; + const SPACE_KEY = 'Space'; + const TAB_KEY$1 = 'Tab'; + const ARROW_UP_KEY = 'ArrowUp'; + const ARROW_DOWN_KEY = 'ArrowDown'; + const RIGHT_MOUSE_BUTTON = 2; // MouseEvent.button value for the secondary button, usually the right button + + const REGEXP_KEYDOWN = new RegExp(`${ARROW_UP_KEY}|${ARROW_DOWN_KEY}|${ESCAPE_KEY$2}`); + const EVENT_HIDE$4 = `hide${EVENT_KEY$8}`; + const EVENT_HIDDEN$4 = `hidden${EVENT_KEY$8}`; + const EVENT_SHOW$4 = `show${EVENT_KEY$8}`; + const EVENT_SHOWN$4 = `shown${EVENT_KEY$8}`; + const EVENT_CLICK_DATA_API$3 = `click${EVENT_KEY$8}${DATA_API_KEY$4}`; + const EVENT_KEYDOWN_DATA_API = `keydown${EVENT_KEY$8}${DATA_API_KEY$4}`; + const EVENT_KEYUP_DATA_API = `keyup${EVENT_KEY$8}${DATA_API_KEY$4}`; + const CLASS_NAME_SHOW$6 = 'show'; + const CLASS_NAME_DROPUP = 'dropup'; + const CLASS_NAME_DROPEND = 'dropend'; + const CLASS_NAME_DROPSTART = 'dropstart'; + const CLASS_NAME_NAVBAR = 'navbar'; + const SELECTOR_DATA_TOGGLE$3 = '[data-bs-toggle="dropdown"]'; + const SELECTOR_MENU = '.dropdown-menu'; + const SELECTOR_NAVBAR_NAV = '.navbar-nav'; + const SELECTOR_VISIBLE_ITEMS = '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)'; + const PLACEMENT_TOP = isRTL() ? 'top-end' : 'top-start'; + const PLACEMENT_TOPEND = isRTL() ? 'top-start' : 'top-end'; + const PLACEMENT_BOTTOM = isRTL() ? 'bottom-end' : 'bottom-start'; + const PLACEMENT_BOTTOMEND = isRTL() ? 'bottom-start' : 'bottom-end'; + const PLACEMENT_RIGHT = isRTL() ? 'left-start' : 'right-start'; + const PLACEMENT_LEFT = isRTL() ? 'right-start' : 'left-start'; + const Default$8 = { + offset: [0, 2], + boundary: 'clippingParents', + reference: 'toggle', + display: 'dynamic', + popperConfig: null, + autoClose: true + }; + const DefaultType$8 = { + offset: '(array|string|function)', + boundary: '(string|element)', + reference: '(string|element|object)', + display: 'string', + popperConfig: '(null|object|function)', + autoClose: '(boolean|string)' + }; /** - * Destroys the popper. - * @method - * @memberof Popper + * ------------------------------------------------------------------------ + * Class Definition + * ------------------------------------------------------------------------ */ - function destroy() { - this.state.isDestroyed = true; - // touch DOM only if `applyStyle` modifier is enabled - if (isModifierEnabled(this.modifiers, 'applyStyle')) { - this.popper.removeAttribute('x-placement'); - this.popper.style.position = ''; - this.popper.style.top = ''; - this.popper.style.left = ''; - this.popper.style.right = ''; - this.popper.style.bottom = ''; - this.popper.style.willChange = ''; - this.popper.style[getSupportedPropertyName('transform')] = ''; - } + class Dropdown extends BaseComponent { + constructor(element, config) { + super(element); + this._popper = null; + this._config = this._getConfig(config); + this._menu = this._getMenuElement(); + this._inNavbar = this._detectNavbar(); + } // Getters - this.disableEventListeners(); - // remove the popper if user explicity asked for the deletion on destroy - // do not use `remove` because IE11 doesn't support it - if (this.options.removeOnDestroy) { - this.popper.parentNode.removeChild(this.popper); + static get Default() { + return Default$8; } - return this; - } - /** - * Get the window associated with the element - * @argument {Element} element - * @returns {Window} - */ - function getWindow(element) { - var ownerDocument = element.ownerDocument; - return ownerDocument ? ownerDocument.defaultView : window; - } + static get DefaultType() { + return DefaultType$8; + } + + static get NAME() { + return NAME$9; + } // Public - function attachToScrollParents(scrollParent, event, callback, scrollParents) { - var isBody = scrollParent.nodeName === 'BODY'; - var target = isBody ? scrollParent.ownerDocument.defaultView : scrollParent; - target.addEventListener(event, callback, { passive: true }); - if (!isBody) { - attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents); + toggle() { + return this._isShown() ? this.hide() : this.show(); } - scrollParents.push(target); - } - /** - * Setup needed event listeners used to update the popper position - * @method - * @memberof Popper.Utils - * @private - */ - function setupEventListeners(reference, options, state, updateBound) { - // Resize event listener on window - state.updateBound = updateBound; - getWindow(reference).addEventListener('resize', state.updateBound, { passive: true }); - - // Scroll event listener on scroll parents - var scrollElement = getScrollParent(reference); - attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents); - state.scrollElement = scrollElement; - state.eventsEnabled = true; - - return state; - } + show() { + if (isDisabled(this._element) || this._isShown(this._menu)) { + return; + } - /** - * It will add resize/scroll events and start recalculating - * position of the popper element when they are triggered. - * @method - * @memberof Popper - */ - function enableEventListeners() { - if (!this.state.eventsEnabled) { - this.state = setupEventListeners(this.reference, this.options, this.state, this.scheduleUpdate); - } - } + const relatedTarget = { + relatedTarget: this._element + }; + const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$4, relatedTarget); - /** - * Remove event listeners used to update the popper position - * @method - * @memberof Popper.Utils - * @private - */ - function removeEventListeners(reference, state) { - // Remove resize event listener on window - getWindow(reference).removeEventListener('resize', state.updateBound); + if (showEvent.defaultPrevented) { + return; + } - // Remove scroll event listener on scroll parents - state.scrollParents.forEach(function (target) { - target.removeEventListener('scroll', state.updateBound); - }); + const parent = Dropdown.getParentFromElement(this._element); // Totally disable Popper for Dropdowns in Navbar - // Reset state - state.updateBound = null; - state.scrollParents = []; - state.scrollElement = null; - state.eventsEnabled = false; - return state; - } + if (this._inNavbar) { + Manipulator.setDataAttribute(this._menu, 'popper', 'none'); + } else { + this._createPopper(parent); + } // If this is a touch-enabled device we add extra + // empty mouseover listeners to the body's immediate children; + // only needed because of broken event delegation on iOS + // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html - /** - * It will remove resize/scroll events and won't recalculate popper position - * when they are triggered. It also won't trigger `onUpdate` callback anymore, - * unless you call `update` method manually. - * @method - * @memberof Popper - */ - function disableEventListeners() { - if (this.state.eventsEnabled) { - cancelAnimationFrame(this.scheduleUpdate); - this.state = removeEventListeners(this.reference, this.state); - } - } - /** - * Tells if a given input is a number - * @method - * @memberof Popper.Utils - * @param {*} input to check - * @return {Boolean} - */ - function isNumeric(n) { - return n !== '' && !isNaN(parseFloat(n)) && isFinite(n); - } + if ('ontouchstart' in document.documentElement && !parent.closest(SELECTOR_NAVBAR_NAV)) { + [].concat(...document.body.children).forEach(elem => EventHandler.on(elem, 'mouseover', noop)); + } - /** - * Set the style to the given popper - * @method - * @memberof Popper.Utils - * @argument {Element} element - Element to apply the style to - * @argument {Object} styles - * Object with a list of properties and values which will be applied to the element - */ - function setStyles(element, styles) { - Object.keys(styles).forEach(function (prop) { - var unit = ''; - // add unit if the value is numeric and is one of the following - if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) { - unit = 'px'; - } - element.style[prop] = styles[prop] + unit; - }); - } + this._element.focus(); - /** - * Set the attributes to the given popper - * @method - * @memberof Popper.Utils - * @argument {Element} element - Element to apply the attributes to - * @argument {Object} styles - * Object with a list of properties and values which will be applied to the element - */ - function setAttributes(element, attributes) { - Object.keys(attributes).forEach(function (prop) { - var value = attributes[prop]; - if (value !== false) { - element.setAttribute(prop, attributes[prop]); - } else { - element.removeAttribute(prop); + this._element.setAttribute('aria-expanded', true); + + this._menu.classList.add(CLASS_NAME_SHOW$6); + + this._element.classList.add(CLASS_NAME_SHOW$6); + + EventHandler.trigger(this._element, EVENT_SHOWN$4, relatedTarget); + } + + hide() { + if (isDisabled(this._element) || !this._isShown(this._menu)) { + return; } - }); - } - /** - * @function - * @memberof Modifiers - * @argument {Object} data - The data object generated by `update` method - * @argument {Object} data.styles - List of style properties - values to apply to popper element - * @argument {Object} data.attributes - List of attribute properties - values to apply to popper element - * @argument {Object} options - Modifiers configuration and options - * @returns {Object} The same data object - */ - function applyStyle(data) { - // any property present in `data.styles` will be applied to the popper, - // in this way we can make the 3rd party modifiers add custom styles to it - // Be aware, modifiers could override the properties defined in the previous - // lines of this modifier! - setStyles(data.instance.popper, data.styles); + const relatedTarget = { + relatedTarget: this._element + }; + + this._completeHide(relatedTarget); + } - // any property present in `data.attributes` will be applied to the popper, - // they will be set as HTML attributes of the element - setAttributes(data.instance.popper, data.attributes); + dispose() { + if (this._popper) { + this._popper.destroy(); + } - // if arrowElement is defined and arrowStyles has some properties - if (data.arrowElement && Object.keys(data.arrowStyles).length) { - setStyles(data.arrowElement, data.arrowStyles); + super.dispose(); } - return data; - } + update() { + this._inNavbar = this._detectNavbar(); - /** - * Set the x-placement attribute before everything else because it could be used - * to add margins to the popper margins needs to be calculated to get the - * correct popper offsets. - * @method - * @memberof Popper.modifiers - * @param {HTMLElement} reference - The reference element used to position the popper - * @param {HTMLElement} popper - The HTML element used as popper - * @param {Object} options - Popper.js options - */ - function applyStyleOnLoad(reference, popper, options, modifierOptions, state) { - // compute reference element offsets - var referenceOffsets = getReferenceOffsets(state, popper, reference, options.positionFixed); + if (this._popper) { + this._popper.update(); + } + } // Private - // compute auto placement, store placement inside the data object, - // modifiers will be able to edit `placement` if needed - // and refer to originalPlacement to know the original value - var placement = computeAutoPlacement(options.placement, referenceOffsets, popper, reference, options.modifiers.flip.boundariesElement, options.modifiers.flip.padding); - popper.setAttribute('x-placement', placement); + _completeHide(relatedTarget) { + const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$4, relatedTarget); - // Apply `position` to popper before anything else because - // without the position applied we can't guarantee correct computations - setStyles(popper, { position: options.positionFixed ? 'fixed' : 'absolute' }); + if (hideEvent.defaultPrevented) { + return; + } // If this is a touch-enabled device we remove the extra + // empty mouseover listeners we added for iOS support - return options; - } - /** - * @function - * @memberof Popper.Utils - * @argument {Object} data - The data object generated by `update` method - * @argument {Boolean} shouldRound - If the offsets should be rounded at all - * @returns {Object} The popper's position offsets rounded - * - * The tale of pixel-perfect positioning. It's still not 100% perfect, but as - * good as it can be within reason. - * Discussion here: https://github.com/FezVrasta/popper.js/pull/715 - * - * Low DPI screens cause a popper to be blurry if not using full pixels (Safari - * as well on High DPI screens). - * - * Firefox prefers no rounding for positioning and does not have blurriness on - * high DPI screens. - * - * Only horizontal placement and left/right values need to be considered. - */ - function getRoundedOffsets(data, shouldRound) { - var _data$offsets = data.offsets, - popper = _data$offsets.popper, - reference = _data$offsets.reference; - var round = Math.round, - floor = Math.floor; - - var noRound = function noRound(v) { - return v; - }; + if ('ontouchstart' in document.documentElement) { + [].concat(...document.body.children).forEach(elem => EventHandler.off(elem, 'mouseover', noop)); + } - var referenceWidth = round(reference.width); - var popperWidth = round(popper.width); + if (this._popper) { + this._popper.destroy(); + } - var isVertical = ['left', 'right'].indexOf(data.placement) !== -1; - var isVariation = data.placement.indexOf('-') !== -1; - var sameWidthParity = referenceWidth % 2 === popperWidth % 2; - var bothOddWidth = referenceWidth % 2 === 1 && popperWidth % 2 === 1; + this._menu.classList.remove(CLASS_NAME_SHOW$6); - var horizontalToInteger = !shouldRound ? noRound : isVertical || isVariation || sameWidthParity ? round : floor; - var verticalToInteger = !shouldRound ? noRound : round; + this._element.classList.remove(CLASS_NAME_SHOW$6); - return { - left: horizontalToInteger(bothOddWidth && !isVariation && shouldRound ? popper.left - 1 : popper.left), - top: verticalToInteger(popper.top), - bottom: verticalToInteger(popper.bottom), - right: horizontalToInteger(popper.right) - }; - } + this._element.setAttribute('aria-expanded', 'false'); - var isFirefox = isBrowser && /Firefox/i.test(navigator.userAgent); + Manipulator.removeDataAttribute(this._menu, 'popper'); + EventHandler.trigger(this._element, EVENT_HIDDEN$4, relatedTarget); + } - /** - * @function - * @memberof Modifiers - * @argument {Object} data - The data object generated by `update` method - * @argument {Object} options - Modifiers configuration and options - * @returns {Object} The data object, properly modified - */ - function computeStyle(data, options) { - var x = options.x, - y = options.y; - var popper = data.offsets.popper; + _getConfig(config) { + config = { ...this.constructor.Default, + ...Manipulator.getDataAttributes(this._element), + ...config + }; + typeCheckConfig(NAME$9, config, this.constructor.DefaultType); - // Remove this legacy support in Popper.js v2 + if (typeof config.reference === 'object' && !isElement$1(config.reference) && typeof config.reference.getBoundingClientRect !== 'function') { + // Popper virtual elements require a getBoundingClientRect method + throw new TypeError(`${NAME$9.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`); + } - var legacyGpuAccelerationOption = find(data.instance.modifiers, function (modifier) { - return modifier.name === 'applyStyle'; - }).gpuAcceleration; - if (legacyGpuAccelerationOption !== undefined) { - console.warn('WARNING: `gpuAcceleration` option moved to `computeStyle` modifier and will not be supported in future versions of Popper.js!'); + return config; } - var gpuAcceleration = legacyGpuAccelerationOption !== undefined ? legacyGpuAccelerationOption : options.gpuAcceleration; - var offsetParent = getOffsetParent(data.instance.popper); - var offsetParentRect = getBoundingClientRect(offsetParent); + _createPopper(parent) { + if (typeof Popper === 'undefined') { + throw new TypeError('Bootstrap\'s dropdowns require Popper (https://popper.js.org)'); + } - // Styles - var styles = { - position: popper.position - }; + let referenceElement = this._element; - var offsets = getRoundedOffsets(data, window.devicePixelRatio < 2 || !isFirefox); - - var sideA = x === 'bottom' ? 'top' : 'bottom'; - var sideB = y === 'right' ? 'left' : 'right'; - - // if gpuAcceleration is set to `true` and transform is supported, - // we use `translate3d` to apply the position to the popper we - // automatically use the supported prefixed version if needed - var prefixedProperty = getSupportedPropertyName('transform'); - - // now, let's make a step back and look at this code closely (wtf?) - // If the content of the popper grows once it's been positioned, it - // may happen that the popper gets misplaced because of the new content - // overflowing its reference element - // To avoid this problem, we provide two options (x and y), which allow - // the consumer to define the offset origin. - // If we position a popper on top of a reference element, we can set - // `x` to `top` to make the popper grow towards its top instead of - // its bottom. - var left = void 0, - top = void 0; - if (sideA === 'bottom') { - // when offsetParent is the positioning is relative to the bottom of the screen (excluding the scrollbar) - // and not the bottom of the html element - if (offsetParent.nodeName === 'HTML') { - top = -offsetParent.clientHeight + offsets.bottom; - } else { - top = -offsetParentRect.height + offsets.bottom; + if (this._config.reference === 'parent') { + referenceElement = parent; + } else if (isElement$1(this._config.reference)) { + referenceElement = getElement(this._config.reference); + } else if (typeof this._config.reference === 'object') { + referenceElement = this._config.reference; } - } else { - top = offsets.top; - } - if (sideB === 'right') { - if (offsetParent.nodeName === 'HTML') { - left = -offsetParent.clientWidth + offsets.right; - } else { - left = -offsetParentRect.width + offsets.right; + + const popperConfig = this._getPopperConfig(); + + const isDisplayStatic = popperConfig.modifiers.find(modifier => modifier.name === 'applyStyles' && modifier.enabled === false); + this._popper = createPopper(referenceElement, this._menu, popperConfig); + + if (isDisplayStatic) { + Manipulator.setDataAttribute(this._menu, 'popper', 'static'); } - } else { - left = offsets.left; } - if (gpuAcceleration && prefixedProperty) { - styles[prefixedProperty] = 'translate3d(' + left + 'px, ' + top + 'px, 0)'; - styles[sideA] = 0; - styles[sideB] = 0; - styles.willChange = 'transform'; - } else { - // othwerise, we use the standard `top`, `left`, `bottom` and `right` properties - var invertTop = sideA === 'bottom' ? -1 : 1; - var invertLeft = sideB === 'right' ? -1 : 1; - styles[sideA] = top * invertTop; - styles[sideB] = left * invertLeft; - styles.willChange = sideA + ', ' + sideB; + + _isShown(element = this._element) { + return element.classList.contains(CLASS_NAME_SHOW$6); } - // Attributes - var attributes = { - 'x-placement': data.placement - }; + _getMenuElement() { + return SelectorEngine.next(this._element, SELECTOR_MENU)[0]; + } - // Update `data` attributes, styles and arrowStyles - data.attributes = _extends({}, attributes, data.attributes); - data.styles = _extends({}, styles, data.styles); - data.arrowStyles = _extends({}, data.offsets.arrow, data.arrowStyles); + _getPlacement() { + const parentDropdown = this._element.parentNode; - return data; - } + if (parentDropdown.classList.contains(CLASS_NAME_DROPEND)) { + return PLACEMENT_RIGHT; + } - /** - * Helper used to know if the given modifier depends from another one.
- * It checks if the needed modifier is listed and enabled. - * @method - * @memberof Popper.Utils - * @param {Array} modifiers - list of modifiers - * @param {String} requestingName - name of requesting modifier - * @param {String} requestedName - name of requested modifier - * @returns {Boolean} - */ - function isModifierRequired(modifiers, requestingName, requestedName) { - var requesting = find(modifiers, function (_ref) { - var name = _ref.name; - return name === requestingName; - }); + if (parentDropdown.classList.contains(CLASS_NAME_DROPSTART)) { + return PLACEMENT_LEFT; + } // We need to trim the value because custom properties can also include spaces - var isRequired = !!requesting && modifiers.some(function (modifier) { - return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order; - }); - if (!isRequired) { - var _requesting = '`' + requestingName + '`'; - var requested = '`' + requestedName + '`'; - console.warn(requested + ' modifier is required by ' + _requesting + ' modifier in order to work, be sure to include it before ' + _requesting + '!'); - } - return isRequired; - } + const isEnd = getComputedStyle(this._menu).getPropertyValue('--bs-position').trim() === 'end'; - /** - * @function - * @memberof Modifiers - * @argument {Object} data - The data object generated by update method - * @argument {Object} options - Modifiers configuration and options - * @returns {Object} The data object, properly modified - */ - function arrow(data, options) { - var _data$offsets$arrow; + if (parentDropdown.classList.contains(CLASS_NAME_DROPUP)) { + return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP; + } - // arrow depends on keepTogether in order to work - if (!isModifierRequired(data.instance.modifiers, 'arrow', 'keepTogether')) { - return data; + return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM; } - var arrowElement = options.element; + _detectNavbar() { + return this._element.closest(`.${CLASS_NAME_NAVBAR}`) !== null; + } - // if arrowElement is a string, suppose it's a CSS selector - if (typeof arrowElement === 'string') { - arrowElement = data.instance.popper.querySelector(arrowElement); + _getOffset() { + const { + offset + } = this._config; - // if arrowElement is not found, don't run the modifier - if (!arrowElement) { - return data; + if (typeof offset === 'string') { + return offset.split(',').map(val => Number.parseInt(val, 10)); } - } else { - // if the arrowElement isn't a query selector we must check that the - // provided DOM node is child of its popper node - if (!data.instance.popper.contains(arrowElement)) { - console.warn('WARNING: `arrow.element` must be child of its popper element!'); - return data; + + if (typeof offset === 'function') { + return popperData => offset(popperData, this._element); } + + return offset; } - var placement = data.placement.split('-')[0]; - var _data$offsets = data.offsets, - popper = _data$offsets.popper, - reference = _data$offsets.reference; + _getPopperConfig() { + const defaultBsPopperConfig = { + placement: this._getPlacement(), + modifiers: [{ + name: 'preventOverflow', + options: { + boundary: this._config.boundary + } + }, { + name: 'offset', + options: { + offset: this._getOffset() + } + }] + }; // Disable Popper if we have a static display - var isVertical = ['left', 'right'].indexOf(placement) !== -1; + if (this._config.display === 'static') { + defaultBsPopperConfig.modifiers = [{ + name: 'applyStyles', + enabled: false + }]; + } - var len = isVertical ? 'height' : 'width'; - var sideCapitalized = isVertical ? 'Top' : 'Left'; - var side = sideCapitalized.toLowerCase(); - var altSide = isVertical ? 'left' : 'top'; - var opSide = isVertical ? 'bottom' : 'right'; - var arrowElementSize = getOuterSizes(arrowElement)[len]; + return { ...defaultBsPopperConfig, + ...(typeof this._config.popperConfig === 'function' ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig) + }; + } - // - // extends keepTogether behavior making sure the popper and its - // reference have enough pixels in conjunction - // + _selectMenuItem({ + key, + target + }) { + const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(isVisible); - // top/left side - if (reference[opSide] - arrowElementSize < popper[side]) { - data.offsets.popper[side] -= popper[side] - (reference[opSide] - arrowElementSize); - } - // bottom/right side - if (reference[side] + arrowElementSize > popper[opSide]) { - data.offsets.popper[side] += reference[side] + arrowElementSize - popper[opSide]; - } - data.offsets.popper = getClientRect(data.offsets.popper); + if (!items.length) { + return; + } // if target isn't included in items (e.g. when expanding the dropdown) + // allow cycling to get the last item in case key equals ARROW_UP_KEY - // compute center of the popper - var center = reference[side] + reference[len] / 2 - arrowElementSize / 2; - // Compute the sideValue using the updated popper offsets - // take popper margin in account because we don't have this info available - var css = getStyleComputedProperty(data.instance.popper); - var popperMarginSide = parseFloat(css['margin' + sideCapitalized], 10); - var popperBorderSide = parseFloat(css['border' + sideCapitalized + 'Width'], 10); - var sideValue = center - data.offsets.popper[side] - popperMarginSide - popperBorderSide; + getNextActiveElement(items, target, key === ARROW_DOWN_KEY, !items.includes(target)).focus(); + } // Static - // prevent arrowElement from being placed not contiguously to its popper - sideValue = Math.max(Math.min(popper[len] - arrowElementSize, sideValue), 0); - data.arrowElement = arrowElement; - data.offsets.arrow = (_data$offsets$arrow = {}, defineProperty(_data$offsets$arrow, side, Math.round(sideValue)), defineProperty(_data$offsets$arrow, altSide, ''), _data$offsets$arrow); + static jQueryInterface(config) { + return this.each(function () { + const data = Dropdown.getOrCreateInstance(this, config); - return data; - } + if (typeof config !== 'string') { + return; + } - /** - * Get the opposite placement variation of the given one - * @method - * @memberof Popper.Utils - * @argument {String} placement variation - * @returns {String} flipped placement variation - */ - function getOppositeVariation(variation) { - if (variation === 'end') { - return 'start'; - } else if (variation === 'start') { - return 'end'; + if (typeof data[config] === 'undefined') { + throw new TypeError(`No method named "${config}"`); + } + + data[config](); + }); } - return variation; - } - /** - * List of accepted placements to use as values of the `placement` option.
- * Valid placements are: - * - `auto` - * - `top` - * - `right` - * - `bottom` - * - `left` - * - * Each placement can have a variation from this list: - * - `-start` - * - `-end` - * - * Variations are interpreted easily if you think of them as the left to right - * written languages. Horizontally (`top` and `bottom`), `start` is left and `end` - * is right.
- * Vertically (`left` and `right`), `start` is top and `end` is bottom. - * - * Some valid examples are: - * - `top-end` (on top of reference, right aligned) - * - `right-start` (on right of reference, top aligned) - * - `bottom` (on bottom, centered) - * - `auto-end` (on the side with more space available, alignment depends by placement) - * - * @static - * @type {Array} - * @enum {String} - * @readonly - * @method placements - * @memberof Popper - */ - var placements = ['auto-start', 'auto', 'auto-end', 'top-start', 'top', 'top-end', 'right-start', 'right', 'right-end', 'bottom-end', 'bottom', 'bottom-start', 'left-end', 'left', 'left-start']; + static clearMenus(event) { + if (event && (event.button === RIGHT_MOUSE_BUTTON || event.type === 'keyup' && event.key !== TAB_KEY$1)) { + return; + } - // Get rid of `auto` `auto-start` and `auto-end` - var validPlacements = placements.slice(3); + const toggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE$3); - /** - * Given an initial placement, returns all the subsequent placements - * clockwise (or counter-clockwise). - * - * @method - * @memberof Popper.Utils - * @argument {String} placement - A valid placement (it accepts variations) - * @argument {Boolean} counter - Set to true to walk the placements counterclockwise - * @returns {Array} placements including their variations - */ - function clockwise(placement) { - var counter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + for (let i = 0, len = toggles.length; i < len; i++) { + const context = Dropdown.getInstance(toggles[i]); - var index = validPlacements.indexOf(placement); - var arr = validPlacements.slice(index + 1).concat(validPlacements.slice(0, index)); - return counter ? arr.reverse() : arr; - } + if (!context || context._config.autoClose === false) { + continue; + } - var BEHAVIORS = { - FLIP: 'flip', - CLOCKWISE: 'clockwise', - COUNTERCLOCKWISE: 'counterclockwise' - }; + if (!context._isShown()) { + continue; + } - /** - * @function - * @memberof Modifiers - * @argument {Object} data - The data object generated by update method - * @argument {Object} options - Modifiers configuration and options - * @returns {Object} The data object, properly modified - */ - function flip(data, options) { - // if `inner` modifier is enabled, we can't use the `flip` modifier - if (isModifierEnabled(data.instance.modifiers, 'inner')) { - return data; - } + const relatedTarget = { + relatedTarget: context._element + }; - if (data.flipped && data.placement === data.originalPlacement) { - // seems like flip is trying to loop, probably there's not enough space on any of the flippable sides - return data; - } + if (event) { + const composedPath = event.composedPath(); + const isMenuTarget = composedPath.includes(context._menu); - var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, options.boundariesElement, data.positionFixed); + if (composedPath.includes(context._element) || context._config.autoClose === 'inside' && !isMenuTarget || context._config.autoClose === 'outside' && isMenuTarget) { + continue; + } // Tab navigation through the dropdown menu or events from contained inputs shouldn't close the menu - var placement = data.placement.split('-')[0]; - var placementOpposite = getOppositePlacement(placement); - var variation = data.placement.split('-')[1] || ''; - var flipOrder = []; + if (context._menu.contains(event.target) && (event.type === 'keyup' && event.key === TAB_KEY$1 || /input|select|option|textarea|form/i.test(event.target.tagName))) { + continue; + } - switch (options.behavior) { - case BEHAVIORS.FLIP: - flipOrder = [placement, placementOpposite]; - break; - case BEHAVIORS.CLOCKWISE: - flipOrder = clockwise(placement); - break; - case BEHAVIORS.COUNTERCLOCKWISE: - flipOrder = clockwise(placement, true); - break; - default: - flipOrder = options.behavior; - } + if (event.type === 'click') { + relatedTarget.clickEvent = event; + } + } - flipOrder.forEach(function (step, index) { - if (placement !== step || flipOrder.length === index + 1) { - return data; + context._completeHide(relatedTarget); } + } - placement = data.placement.split('-')[0]; - placementOpposite = getOppositePlacement(placement); + static getParentFromElement(element) { + return getElementFromSelector(element) || element.parentNode; + } - var popperOffsets = data.offsets.popper; - var refOffsets = data.offsets.reference; + static dataApiKeydownHandler(event) { + // If not input/textarea: + // - And not a key in REGEXP_KEYDOWN => not a dropdown command + // If input/textarea: + // - If space key => not a dropdown command + // - If key is other than escape + // - If key is not up or down => not a dropdown command + // - If trigger inside the menu => not a dropdown command + if (/input|textarea/i.test(event.target.tagName) ? event.key === SPACE_KEY || event.key !== ESCAPE_KEY$2 && (event.key !== ARROW_DOWN_KEY && event.key !== ARROW_UP_KEY || event.target.closest(SELECTOR_MENU)) : !REGEXP_KEYDOWN.test(event.key)) { + return; + } - // using floor because the reference offsets may contain decimals we are not going to consider here - var floor = Math.floor; - var overlapsRef = placement === 'left' && floor(popperOffsets.right) > floor(refOffsets.left) || placement === 'right' && floor(popperOffsets.left) < floor(refOffsets.right) || placement === 'top' && floor(popperOffsets.bottom) > floor(refOffsets.top) || placement === 'bottom' && floor(popperOffsets.top) < floor(refOffsets.bottom); + const isActive = this.classList.contains(CLASS_NAME_SHOW$6); - var overflowsLeft = floor(popperOffsets.left) < floor(boundaries.left); - var overflowsRight = floor(popperOffsets.right) > floor(boundaries.right); - var overflowsTop = floor(popperOffsets.top) < floor(boundaries.top); - var overflowsBottom = floor(popperOffsets.bottom) > floor(boundaries.bottom); + if (!isActive && event.key === ESCAPE_KEY$2) { + return; + } - var overflowsBoundaries = placement === 'left' && overflowsLeft || placement === 'right' && overflowsRight || placement === 'top' && overflowsTop || placement === 'bottom' && overflowsBottom; + event.preventDefault(); + event.stopPropagation(); - // flip the variation if required - var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; - var flippedVariation = !!options.flipVariations && (isVertical && variation === 'start' && overflowsLeft || isVertical && variation === 'end' && overflowsRight || !isVertical && variation === 'start' && overflowsTop || !isVertical && variation === 'end' && overflowsBottom); + if (isDisabled(this)) { + return; + } - if (overlapsRef || overflowsBoundaries || flippedVariation) { - // this boolean to detect any flip loop - data.flipped = true; + const getToggleButton = this.matches(SELECTOR_DATA_TOGGLE$3) ? this : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE$3)[0]; + const instance = Dropdown.getOrCreateInstance(getToggleButton); - if (overlapsRef || overflowsBoundaries) { - placement = flipOrder[index + 1]; - } + if (event.key === ESCAPE_KEY$2) { + instance.hide(); + return; + } - if (flippedVariation) { - variation = getOppositeVariation(variation); + if (event.key === ARROW_UP_KEY || event.key === ARROW_DOWN_KEY) { + if (!isActive) { + instance.show(); } - data.placement = placement + (variation ? '-' + variation : ''); + instance._selectMenuItem(event); - // this object contains `position`, we want to preserve it along with - // any additional property we may add in the future - data.offsets.popper = _extends({}, data.offsets.popper, getPopperOffsets(data.instance.popper, data.offsets.reference, data.placement)); + return; + } - data = runModifiers(data.instance.modifiers, data, 'flip'); + if (!isActive || event.key === SPACE_KEY) { + Dropdown.clearMenus(); } - }); - return data; + } + } + /** + * ------------------------------------------------------------------------ + * Data Api implementation + * ------------------------------------------------------------------------ + */ + + + EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_DATA_TOGGLE$3, Dropdown.dataApiKeydownHandler); + EventHandler.on(document, EVENT_KEYDOWN_DATA_API, SELECTOR_MENU, Dropdown.dataApiKeydownHandler); + EventHandler.on(document, EVENT_CLICK_DATA_API$3, Dropdown.clearMenus); + EventHandler.on(document, EVENT_KEYUP_DATA_API, Dropdown.clearMenus); + EventHandler.on(document, EVENT_CLICK_DATA_API$3, SELECTOR_DATA_TOGGLE$3, function (event) { + event.preventDefault(); + Dropdown.getOrCreateInstance(this).toggle(); + }); + /** + * ------------------------------------------------------------------------ + * jQuery + * ------------------------------------------------------------------------ + * add .Dropdown to jQuery only if jQuery is present + */ + + defineJQueryPlugin(Dropdown); /** - * @function - * @memberof Modifiers - * @argument {Object} data - The data object generated by update method - * @argument {Object} options - Modifiers configuration and options - * @returns {Object} The data object, properly modified + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): util/scrollBar.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- */ - function keepTogether(data) { - var _data$offsets = data.offsets, - popper = _data$offsets.popper, - reference = _data$offsets.reference; + const SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top'; + const SELECTOR_STICKY_CONTENT = '.sticky-top'; - var placement = data.placement.split('-')[0]; - var floor = Math.floor; - var isVertical = ['top', 'bottom'].indexOf(placement) !== -1; - var side = isVertical ? 'right' : 'bottom'; - var opSide = isVertical ? 'left' : 'top'; - var measurement = isVertical ? 'width' : 'height'; + class ScrollBarHelper { + constructor() { + this._element = document.body; + } - if (popper[side] < floor(reference[opSide])) { - data.offsets.popper[opSide] = floor(reference[opSide]) - popper[measurement]; + getWidth() { + // https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth#usage_notes + const documentWidth = document.documentElement.clientWidth; + return Math.abs(window.innerWidth - documentWidth); } - if (popper[opSide] > floor(reference[side])) { - data.offsets.popper[opSide] = floor(reference[side]); + + hide() { + const width = this.getWidth(); + + this._disableOverFlow(); // give padding to element to balance the hidden scrollbar width + + + this._setElementAttributes(this._element, 'paddingRight', calculatedValue => calculatedValue + width); // trick: We adjust positive paddingRight and negative marginRight to sticky-top elements to keep showing fullwidth + + + this._setElementAttributes(SELECTOR_FIXED_CONTENT, 'paddingRight', calculatedValue => calculatedValue + width); + + this._setElementAttributes(SELECTOR_STICKY_CONTENT, 'marginRight', calculatedValue => calculatedValue - width); } - return data; - } + _disableOverFlow() { + this._saveInitialAttribute(this._element, 'overflow'); - /** - * Converts a string containing value + unit into a px value number - * @function - * @memberof {modifiers~offset} - * @private - * @argument {String} str - Value + unit string - * @argument {String} measurement - `height` or `width` - * @argument {Object} popperOffsets - * @argument {Object} referenceOffsets - * @returns {Number|String} - * Value in pixels, or original string if no values were extracted - */ - function toValue(str, measurement, popperOffsets, referenceOffsets) { - // separate value from unit - var split = str.match(/((?:\-|\+)?\d*\.?\d*)(.*)/); - var value = +split[1]; - var unit = split[2]; - - // If it's not a number it's an operator, I guess - if (!value) { - return str; - } - - if (unit.indexOf('%') === 0) { - var element = void 0; - switch (unit) { - case '%p': - element = popperOffsets; - break; - case '%': - case '%r': - default: - element = referenceOffsets; - } - - var rect = getClientRect(element); - return rect[measurement] / 100 * value; - } else if (unit === 'vh' || unit === 'vw') { - // if is a vh or vw, we calculate the size based on the viewport - var size = void 0; - if (unit === 'vh') { - size = Math.max(document.documentElement.clientHeight, window.innerHeight || 0); - } else { - size = Math.max(document.documentElement.clientWidth, window.innerWidth || 0); - } - return size / 100 * value; - } else { - // if is an explicit pixel unit, we get rid of the unit and keep the value - // if is an implicit unit, it's px, and we return just the value - return value; + this._element.style.overflow = 'hidden'; } - } - /** - * Parse an `offset` string to extrapolate `x` and `y` numeric offsets. - * @function - * @memberof {modifiers~offset} - * @private - * @argument {String} offset - * @argument {Object} popperOffsets - * @argument {Object} referenceOffsets - * @argument {String} basePlacement - * @returns {Array} a two cells array with x and y offsets in numbers - */ - function parseOffset(offset, popperOffsets, referenceOffsets, basePlacement) { - var offsets = [0, 0]; - - // Use height if placement is left or right and index is 0 otherwise use width - // in this way the first offset will use an axis and the second one - // will use the other one - var useHeight = ['right', 'left'].indexOf(basePlacement) !== -1; - - // Split the offset string to obtain a list of values and operands - // The regex addresses values with the plus or minus sign in front (+10, -20, etc) - var fragments = offset.split(/(\+|\-)/).map(function (frag) { - return frag.trim(); - }); + _setElementAttributes(selector, styleProp, callback) { + const scrollbarWidth = this.getWidth(); - // Detect if the offset string contains a pair of values or a single one - // they could be separated by comma or space - var divider = fragments.indexOf(find(fragments, function (frag) { - return frag.search(/,|\s/) !== -1; - })); - - if (fragments[divider] && fragments[divider].indexOf(',') === -1) { - console.warn('Offsets separated by white space(s) are deprecated, use a comma (,) instead.'); - } - - // If divider is found, we divide the list of values and operands to divide - // them by ofset X and Y. - var splitRegex = /\s*,\s*|\s+/; - var ops = divider !== -1 ? [fragments.slice(0, divider).concat([fragments[divider].split(splitRegex)[0]]), [fragments[divider].split(splitRegex)[1]].concat(fragments.slice(divider + 1))] : [fragments]; - - // Convert the values with units to absolute pixels to allow our computations - ops = ops.map(function (op, index) { - // Most of the units rely on the orientation of the popper - var measurement = (index === 1 ? !useHeight : useHeight) ? 'height' : 'width'; - var mergeWithPrevious = false; - return op - // This aggregates any `+` or `-` sign that aren't considered operators - // e.g.: 10 + +5 => [10, +, +5] - .reduce(function (a, b) { - if (a[a.length - 1] === '' && ['+', '-'].indexOf(b) !== -1) { - a[a.length - 1] = b; - mergeWithPrevious = true; - return a; - } else if (mergeWithPrevious) { - a[a.length - 1] += b; - mergeWithPrevious = false; - return a; - } else { - return a.concat(b); + const manipulationCallBack = element => { + if (element !== this._element && window.innerWidth > element.clientWidth + scrollbarWidth) { + return; } - }, []) - // Here we convert the string values into number values (in px) - .map(function (str) { - return toValue(str, measurement, popperOffsets, referenceOffsets); - }); - }); - // Loop trough the offsets arrays and execute the operations - ops.forEach(function (op, index) { - op.forEach(function (frag, index2) { - if (isNumeric(frag)) { - offsets[index] += frag * (op[index2 - 1] === '-' ? -1 : 1); - } - }); - }); - return offsets; - } + this._saveInitialAttribute(element, styleProp); - /** - * @function - * @memberof Modifiers - * @argument {Object} data - The data object generated by update method - * @argument {Object} options - Modifiers configuration and options - * @argument {Number|String} options.offset=0 - * The offset value as described in the modifier description - * @returns {Object} The data object, properly modified - */ - function offset(data, _ref) { - var offset = _ref.offset; - var placement = data.placement, - _data$offsets = data.offsets, - popper = _data$offsets.popper, - reference = _data$offsets.reference; - - var basePlacement = placement.split('-')[0]; - - var offsets = void 0; - if (isNumeric(+offset)) { - offsets = [+offset, 0]; - } else { - offsets = parseOffset(offset, popper, reference, basePlacement); + const calculatedValue = window.getComputedStyle(element)[styleProp]; + element.style[styleProp] = `${callback(Number.parseFloat(calculatedValue))}px`; + }; + + this._applyManipulationCallback(selector, manipulationCallBack); } - if (basePlacement === 'left') { - popper.top += offsets[0]; - popper.left -= offsets[1]; - } else if (basePlacement === 'right') { - popper.top += offsets[0]; - popper.left += offsets[1]; - } else if (basePlacement === 'top') { - popper.left += offsets[0]; - popper.top -= offsets[1]; - } else if (basePlacement === 'bottom') { - popper.left += offsets[0]; - popper.top += offsets[1]; + reset() { + this._resetElementAttributes(this._element, 'overflow'); + + this._resetElementAttributes(this._element, 'paddingRight'); + + this._resetElementAttributes(SELECTOR_FIXED_CONTENT, 'paddingRight'); + + this._resetElementAttributes(SELECTOR_STICKY_CONTENT, 'marginRight'); } - data.popper = popper; - return data; - } + _saveInitialAttribute(element, styleProp) { + const actualValue = element.style[styleProp]; - /** - * @function - * @memberof Modifiers - * @argument {Object} data - The data object generated by `update` method - * @argument {Object} options - Modifiers configuration and options - * @returns {Object} The data object, properly modified - */ - function preventOverflow(data, options) { - var boundariesElement = options.boundariesElement || getOffsetParent(data.instance.popper); - - // If offsetParent is the reference element, we really want to - // go one step up and use the next offsetParent as reference to - // avoid to make this modifier completely useless and look like broken - if (data.instance.reference === boundariesElement) { - boundariesElement = getOffsetParent(boundariesElement); - } - - // NOTE: DOM access here - // resets the popper's position so that the document size can be calculated excluding - // the size of the popper element itself - var transformProp = getSupportedPropertyName('transform'); - var popperStyles = data.instance.popper.style; // assignment to help minification - var top = popperStyles.top, - left = popperStyles.left, - transform = popperStyles[transformProp]; - - popperStyles.top = ''; - popperStyles.left = ''; - popperStyles[transformProp] = ''; - - var boundaries = getBoundaries(data.instance.popper, data.instance.reference, options.padding, boundariesElement, data.positionFixed); - - // NOTE: DOM access here - // restores the original style properties after the offsets have been computed - popperStyles.top = top; - popperStyles.left = left; - popperStyles[transformProp] = transform; - - options.boundaries = boundaries; - - var order = options.priority; - var popper = data.offsets.popper; - - var check = { - primary: function primary(placement) { - var value = popper[placement]; - if (popper[placement] < boundaries[placement] && !options.escapeWithReference) { - value = Math.max(popper[placement], boundaries[placement]); - } - return defineProperty({}, placement, value); - }, - secondary: function secondary(placement) { - var mainSide = placement === 'right' ? 'left' : 'top'; - var value = popper[mainSide]; - if (popper[placement] > boundaries[placement] && !options.escapeWithReference) { - value = Math.min(popper[mainSide], boundaries[placement] - (placement === 'right' ? popper.width : popper.height)); - } - return defineProperty({}, mainSide, value); + if (actualValue) { + Manipulator.setDataAttribute(element, styleProp, actualValue); } - }; + } - order.forEach(function (placement) { - var side = ['left', 'top'].indexOf(placement) !== -1 ? 'primary' : 'secondary'; - popper = _extends({}, popper, check[side](placement)); - }); + _resetElementAttributes(selector, styleProp) { + const manipulationCallBack = element => { + const value = Manipulator.getDataAttribute(element, styleProp); - data.offsets.popper = popper; + if (typeof value === 'undefined') { + element.style.removeProperty(styleProp); + } else { + Manipulator.removeDataAttribute(element, styleProp); + element.style[styleProp] = value; + } + }; - return data; - } + this._applyManipulationCallback(selector, manipulationCallBack); + } - /** - * @function - * @memberof Modifiers - * @argument {Object} data - The data object generated by `update` method - * @argument {Object} options - Modifiers configuration and options - * @returns {Object} The data object, properly modified - */ - function shift(data) { - var placement = data.placement; - var basePlacement = placement.split('-')[0]; - var shiftvariation = placement.split('-')[1]; - - // if shift shiftvariation is specified, run the modifier - if (shiftvariation) { - var _data$offsets = data.offsets, - reference = _data$offsets.reference, - popper = _data$offsets.popper; - - var isVertical = ['bottom', 'top'].indexOf(basePlacement) !== -1; - var side = isVertical ? 'left' : 'top'; - var measurement = isVertical ? 'width' : 'height'; - - var shiftOffsets = { - start: defineProperty({}, side, reference[side]), - end: defineProperty({}, side, reference[side] + reference[measurement] - popper[measurement]) - }; + _applyManipulationCallback(selector, callBack) { + if (isElement$1(selector)) { + callBack(selector); + } else { + SelectorEngine.find(selector, this._element).forEach(callBack); + } + } - data.offsets.popper = _extends({}, popper, shiftOffsets[shiftvariation]); + isOverflowing() { + return this.getWidth() > 0; } - return data; } /** - * @function - * @memberof Modifiers - * @argument {Object} data - The data object generated by update method - * @argument {Object} options - Modifiers configuration and options - * @returns {Object} The data object, properly modified + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): util/backdrop.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * -------------------------------------------------------------------------- */ - function hide(data) { - if (!isModifierRequired(data.instance.modifiers, 'hide', 'preventOverflow')) { - return data; - } + const Default$7 = { + className: 'modal-backdrop', + isVisible: true, + // if false, we use the backdrop helper without adding any element to the dom + isAnimated: false, + rootElement: 'body', + // give the choice to place backdrop under different elements + clickCallback: null + }; + const DefaultType$7 = { + className: 'string', + isVisible: 'boolean', + isAnimated: 'boolean', + rootElement: '(element|string)', + clickCallback: '(function|null)' + }; + const NAME$8 = 'backdrop'; + const CLASS_NAME_FADE$4 = 'fade'; + const CLASS_NAME_SHOW$5 = 'show'; + const EVENT_MOUSEDOWN = `mousedown.bs.${NAME$8}`; - var refRect = data.offsets.reference; - var bound = find(data.instance.modifiers, function (modifier) { - return modifier.name === 'preventOverflow'; - }).boundaries; + class Backdrop { + constructor(config) { + this._config = this._getConfig(config); + this._isAppended = false; + this._element = null; + } - if (refRect.bottom < bound.top || refRect.left > bound.right || refRect.top > bound.bottom || refRect.right < bound.left) { - // Avoid unnecessary DOM access if visibility hasn't changed - if (data.hide === true) { - return data; + show(callback) { + if (!this._config.isVisible) { + execute(callback); + return; } - data.hide = true; - data.attributes['x-out-of-boundaries'] = ''; - } else { - // Avoid unnecessary DOM access if visibility hasn't changed - if (data.hide === false) { - return data; + this._append(); + + if (this._config.isAnimated) { + reflow(this._getElement()); } - data.hide = false; - data.attributes['x-out-of-boundaries'] = false; + this._getElement().classList.add(CLASS_NAME_SHOW$5); + + this._emulateAnimation(() => { + execute(callback); + }); } - return data; - } + hide(callback) { + if (!this._config.isVisible) { + execute(callback); + return; + } - /** - * @function - * @memberof Modifiers - * @argument {Object} data - The data object generated by `update` method - * @argument {Object} options - Modifiers configuration and options - * @returns {Object} The data object, properly modified - */ - function inner(data) { - var placement = data.placement; - var basePlacement = placement.split('-')[0]; - var _data$offsets = data.offsets, - popper = _data$offsets.popper, - reference = _data$offsets.reference; + this._getElement().classList.remove(CLASS_NAME_SHOW$5); - var isHoriz = ['left', 'right'].indexOf(basePlacement) !== -1; + this._emulateAnimation(() => { + this.dispose(); + execute(callback); + }); + } // Private - var subtractLength = ['top', 'left'].indexOf(basePlacement) === -1; - popper[isHoriz ? 'left' : 'top'] = reference[basePlacement] - (subtractLength ? popper[isHoriz ? 'width' : 'height'] : 0); + _getElement() { + if (!this._element) { + const backdrop = document.createElement('div'); + backdrop.className = this._config.className; - data.placement = getOppositePlacement(placement); - data.offsets.popper = getClientRect(popper); + if (this._config.isAnimated) { + backdrop.classList.add(CLASS_NAME_FADE$4); + } - return data; - } + this._element = backdrop; + } - /** - * Modifier function, each modifier can have a function of this type assigned - * to its `fn` property.
- * These functions will be called on each update, this means that you must - * make sure they are performant enough to avoid performance bottlenecks. - * - * @function ModifierFn - * @argument {dataObject} data - The data object generated by `update` method - * @argument {Object} options - Modifiers configuration and options - * @returns {dataObject} The data object, properly modified - */ + return this._element; + } - /** - * Modifiers are plugins used to alter the behavior of your poppers.
- * Popper.js uses a set of 9 modifiers to provide all the basic functionalities - * needed by the library. - * - * Usually you don't want to override the `order`, `fn` and `onLoad` props. - * All the other properties are configurations that could be tweaked. - * @namespace modifiers - */ - var modifiers = { - /** - * Modifier used to shift the popper on the start or end of its reference - * element.
- * It will read the variation of the `placement` property.
- * It can be one either `-end` or `-start`. - * @memberof modifiers - * @inner - */ - shift: { - /** @prop {number} order=100 - Index used to define the order of execution */ - order: 100, - /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ - enabled: true, - /** @prop {ModifierFn} */ - fn: shift - }, + _getConfig(config) { + config = { ...Default$7, + ...(typeof config === 'object' ? config : {}) + }; // use getElement() with the default "body" to get a fresh Element on each instantiation - /** - * The `offset` modifier can shift your popper on both its axis. - * - * It accepts the following units: - * - `px` or unit-less, interpreted as pixels - * - `%` or `%r`, percentage relative to the length of the reference element - * - `%p`, percentage relative to the length of the popper element - * - `vw`, CSS viewport width unit - * - `vh`, CSS viewport height unit - * - * For length is intended the main axis relative to the placement of the popper.
- * This means that if the placement is `top` or `bottom`, the length will be the - * `width`. In case of `left` or `right`, it will be the `height`. - * - * You can provide a single value (as `Number` or `String`), or a pair of values - * as `String` divided by a comma or one (or more) white spaces.
- * The latter is a deprecated method because it leads to confusion and will be - * removed in v2.
- * Additionally, it accepts additions and subtractions between different units. - * Note that multiplications and divisions aren't supported. - * - * Valid examples are: - * ``` - * 10 - * '10%' - * '10, 10' - * '10%, 10' - * '10 + 10%' - * '10 - 5vh + 3%' - * '-10px + 5vh, 5px - 6%' - * ``` - * > **NB**: If you desire to apply offsets to your poppers in a way that may make them overlap - * > with their reference element, unfortunately, you will have to disable the `flip` modifier. - * > You can read more on this at this [issue](https://github.com/FezVrasta/popper.js/issues/373). - * - * @memberof modifiers - * @inner - */ - offset: { - /** @prop {number} order=200 - Index used to define the order of execution */ - order: 200, - /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ - enabled: true, - /** @prop {ModifierFn} */ - fn: offset, - /** @prop {Number|String} offset=0 - * The offset value as described in the modifier description - */ - offset: 0 - }, + config.rootElement = getElement(config.rootElement); + typeCheckConfig(NAME$8, config, DefaultType$7); + return config; + } - /** - * Modifier used to prevent the popper from being positioned outside the boundary. - * - * A scenario exists where the reference itself is not within the boundaries.
- * We can say it has "escaped the boundaries" — or just "escaped".
- * In this case we need to decide whether the popper should either: - * - * - detach from the reference and remain "trapped" in the boundaries, or - * - if it should ignore the boundary and "escape with its reference" - * - * When `escapeWithReference` is set to`true` and reference is completely - * outside its boundaries, the popper will overflow (or completely leave) - * the boundaries in order to remain attached to the edge of the reference. - * - * @memberof modifiers - * @inner - */ - preventOverflow: { - /** @prop {number} order=300 - Index used to define the order of execution */ - order: 300, - /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ - enabled: true, - /** @prop {ModifierFn} */ - fn: preventOverflow, - /** - * @prop {Array} [priority=['left','right','top','bottom']] - * Popper will try to prevent overflow following these priorities by default, - * then, it could overflow on the left and on top of the `boundariesElement` - */ - priority: ['left', 'right', 'top', 'bottom'], - /** - * @prop {number} padding=5 - * Amount of pixel used to define a minimum distance between the boundaries - * and the popper. This makes sure the popper always has a little padding - * between the edges of its container - */ - padding: 5, - /** - * @prop {String|HTMLElement} boundariesElement='scrollParent' - * Boundaries used by the modifier. Can be `scrollParent`, `window`, - * `viewport` or any DOM element. - */ - boundariesElement: 'scrollParent' - }, + _append() { + if (this._isAppended) { + return; + } - /** - * Modifier used to make sure the reference and its popper stay near each other - * without leaving any gap between the two. Especially useful when the arrow is - * enabled and you want to ensure that it points to its reference element. - * It cares only about the first axis. You can still have poppers with margin - * between the popper and its reference element. - * @memberof modifiers - * @inner - */ - keepTogether: { - /** @prop {number} order=400 - Index used to define the order of execution */ - order: 400, - /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ - enabled: true, - /** @prop {ModifierFn} */ - fn: keepTogether - }, + this._config.rootElement.append(this._getElement()); - /** - * This modifier is used to move the `arrowElement` of the popper to make - * sure it is positioned between the reference element and its popper element. - * It will read the outer size of the `arrowElement` node to detect how many - * pixels of conjunction are needed. - * - * It has no effect if no `arrowElement` is provided. - * @memberof modifiers - * @inner - */ - arrow: { - /** @prop {number} order=500 - Index used to define the order of execution */ - order: 500, - /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ - enabled: true, - /** @prop {ModifierFn} */ - fn: arrow, - /** @prop {String|HTMLElement} element='[x-arrow]' - Selector or node used as arrow */ - element: '[x-arrow]' - }, + EventHandler.on(this._getElement(), EVENT_MOUSEDOWN, () => { + execute(this._config.clickCallback); + }); + this._isAppended = true; + } - /** - * Modifier used to flip the popper's placement when it starts to overlap its - * reference element. - * - * Requires the `preventOverflow` modifier before it in order to work. - * - * **NOTE:** this modifier will interrupt the current update cycle and will - * restart it if it detects the need to flip the placement. - * @memberof modifiers - * @inner - */ - flip: { - /** @prop {number} order=600 - Index used to define the order of execution */ - order: 600, - /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ - enabled: true, - /** @prop {ModifierFn} */ - fn: flip, - /** - * @prop {String|Array} behavior='flip' - * The behavior used to change the popper's placement. It can be one of - * `flip`, `clockwise`, `counterclockwise` or an array with a list of valid - * placements (with optional variations) - */ - behavior: 'flip', - /** - * @prop {number} padding=5 - * The popper will flip if it hits the edges of the `boundariesElement` - */ - padding: 5, - /** - * @prop {String|HTMLElement} boundariesElement='viewport' - * The element which will define the boundaries of the popper position. - * The popper will never be placed outside of the defined boundaries - * (except if `keepTogether` is enabled) - */ - boundariesElement: 'viewport' - }, + dispose() { + if (!this._isAppended) { + return; + } - /** - * Modifier used to make the popper flow toward the inner of the reference element. - * By default, when this modifier is disabled, the popper will be placed outside - * the reference element. - * @memberof modifiers - * @inner - */ - inner: { - /** @prop {number} order=700 - Index used to define the order of execution */ - order: 700, - /** @prop {Boolean} enabled=false - Whether the modifier is enabled or not */ - enabled: false, - /** @prop {ModifierFn} */ - fn: inner - }, + EventHandler.off(this._element, EVENT_MOUSEDOWN); - /** - * Modifier used to hide the popper when its reference element is outside of the - * popper boundaries. It will set a `x-out-of-boundaries` attribute which can - * be used to hide with a CSS selector the popper when its reference is - * out of boundaries. - * - * Requires the `preventOverflow` modifier before it in order to work. - * @memberof modifiers - * @inner - */ - hide: { - /** @prop {number} order=800 - Index used to define the order of execution */ - order: 800, - /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ - enabled: true, - /** @prop {ModifierFn} */ - fn: hide - }, + this._element.remove(); - /** - * Computes the style that will be applied to the popper element to gets - * properly positioned. - * - * Note that this modifier will not touch the DOM, it just prepares the styles - * so that `applyStyle` modifier can apply it. This separation is useful - * in case you need to replace `applyStyle` with a custom implementation. - * - * This modifier has `850` as `order` value to maintain backward compatibility - * with previous versions of Popper.js. Expect the modifiers ordering method - * to change in future major versions of the library. - * - * @memberof modifiers - * @inner - */ - computeStyle: { - /** @prop {number} order=850 - Index used to define the order of execution */ - order: 850, - /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ - enabled: true, - /** @prop {ModifierFn} */ - fn: computeStyle, - /** - * @prop {Boolean} gpuAcceleration=true - * If true, it uses the CSS 3D transformation to position the popper. - * Otherwise, it will use the `top` and `left` properties - */ - gpuAcceleration: true, - /** - * @prop {string} [x='bottom'] - * Where to anchor the X axis (`bottom` or `top`). AKA X offset origin. - * Change this if your popper should grow in a direction different from `bottom` - */ - x: 'bottom', - /** - * @prop {string} [x='left'] - * Where to anchor the Y axis (`left` or `right`). AKA Y offset origin. - * Change this if your popper should grow in a direction different from `right` - */ - y: 'right' - }, + this._isAppended = false; + } - /** - * Applies the computed styles to the popper element. - * - * All the DOM manipulations are limited to this modifier. This is useful in case - * you want to integrate Popper.js inside a framework or view library and you - * want to delegate all the DOM manipulations to it. - * - * Note that if you disable this modifier, you must make sure the popper element - * has its position set to `absolute` before Popper.js can do its work! - * - * Just disable this modifier and define your own to achieve the desired effect. - * - * @memberof modifiers - * @inner - */ - applyStyle: { - /** @prop {number} order=900 - Index used to define the order of execution */ - order: 900, - /** @prop {Boolean} enabled=true - Whether the modifier is enabled or not */ - enabled: true, - /** @prop {ModifierFn} */ - fn: applyStyle, - /** @prop {Function} */ - onLoad: applyStyleOnLoad, - /** - * @deprecated since version 1.10.0, the property moved to `computeStyle` modifier - * @prop {Boolean} gpuAcceleration=true - * If true, it uses the CSS 3D transformation to position the popper. - * Otherwise, it will use the `top` and `left` properties - */ - gpuAcceleration: undefined + _emulateAnimation(callback) { + executeAfterTransition(callback, this._getElement(), this._config.isAnimated); } - }; - /** - * The `dataObject` is an object containing all the information used by Popper.js. - * This object is passed to modifiers and to the `onCreate` and `onUpdate` callbacks. - * @name dataObject - * @property {Object} data.instance The Popper.js instance - * @property {String} data.placement Placement applied to popper - * @property {String} data.originalPlacement Placement originally defined on init - * @property {Boolean} data.flipped True if popper has been flipped by flip modifier - * @property {Boolean} data.hide True if the reference element is out of boundaries, useful to know when to hide the popper - * @property {HTMLElement} data.arrowElement Node used as arrow by arrow modifier - * @property {Object} data.styles Any CSS property defined here will be applied to the popper. It expects the JavaScript nomenclature (eg. `marginBottom`) - * @property {Object} data.arrowStyles Any CSS property defined here will be applied to the popper arrow. It expects the JavaScript nomenclature (eg. `marginBottom`) - * @property {Object} data.boundaries Offsets of the popper boundaries - * @property {Object} data.offsets The measurements of popper, reference and arrow elements - * @property {Object} data.offsets.popper `top`, `left`, `width`, `height` values - * @property {Object} data.offsets.reference `top`, `left`, `width`, `height` values - * @property {Object} data.offsets.arrow] `top` and `left` offsets, only one of them will be different from 0 - */ + } /** - * Default options provided to Popper.js constructor.
- * These can be overridden using the `options` argument of Popper.js.
- * To override an option, simply pass an object with the same - * structure of the `options` object, as the 3rd argument. For example: - * ``` - * new Popper(ref, pop, { - * modifiers: { - * preventOverflow: { enabled: false } - * } - * }) - * ``` - * @type {Object} - * @static - * @memberof Popper + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): util/focustrap.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * -------------------------------------------------------------------------- */ - var Defaults = { - /** - * Popper's placement. - * @prop {Popper.placements} placement='bottom' - */ - placement: 'bottom', - - /** - * Set this to true if you want popper to position it self in 'fixed' mode - * @prop {Boolean} positionFixed=false - */ - positionFixed: false, - - /** - * Whether events (resize, scroll) are initially enabled. - * @prop {Boolean} eventsEnabled=true - */ - eventsEnabled: true, - - /** - * Set to true if you want to automatically remove the popper when - * you call the `destroy` method. - * @prop {Boolean} removeOnDestroy=false - */ - removeOnDestroy: false, - - /** - * Callback called when the popper is created.
- * By default, it is set to no-op.
- * Access Popper.js instance with `data.instance`. - * @prop {onCreate} - */ - onCreate: function onCreate() {}, - - /** - * Callback called when the popper is updated. This callback is not called - * on the initialization/creation of the popper, but only on subsequent - * updates.
- * By default, it is set to no-op.
- * Access Popper.js instance with `data.instance`. - * @prop {onUpdate} - */ - onUpdate: function onUpdate() {}, - - /** - * List of modifiers used to modify the offsets before they are applied to the popper. - * They provide most of the functionalities of Popper.js. - * @prop {modifiers} - */ - modifiers: modifiers + const Default$6 = { + trapElement: null, + // The element to trap focus inside of + autofocus: true }; + const DefaultType$6 = { + trapElement: 'element', + autofocus: 'boolean' + }; + const NAME$7 = 'focustrap'; + const DATA_KEY$7 = 'bs.focustrap'; + const EVENT_KEY$7 = `.${DATA_KEY$7}`; + const EVENT_FOCUSIN$1 = `focusin${EVENT_KEY$7}`; + const EVENT_KEYDOWN_TAB = `keydown.tab${EVENT_KEY$7}`; + const TAB_KEY = 'Tab'; + const TAB_NAV_FORWARD = 'forward'; + const TAB_NAV_BACKWARD = 'backward'; + + class FocusTrap { + constructor(config) { + this._config = this._getConfig(config); + this._isActive = false; + this._lastTabNavDirection = null; + } - /** - * @callback onCreate - * @param {dataObject} data - */ + activate() { + const { + trapElement, + autofocus + } = this._config; - /** - * @callback onUpdate - * @param {dataObject} data - */ + if (this._isActive) { + return; + } - // Utils - // Methods - var Popper = function () { - /** - * Creates a new Popper.js instance. - * @class Popper - * @param {HTMLElement|referenceObject} reference - The reference element used to position the popper - * @param {HTMLElement} popper - The HTML element used as the popper - * @param {Object} options - Your custom options to override the ones defined in [Defaults](#defaults) - * @return {Object} instance - The generated Popper.js instance - */ - function Popper(reference, popper) { - var _this = this; - - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - classCallCheck(this, Popper); - - this.scheduleUpdate = function () { - return requestAnimationFrame(_this.update); - }; + if (autofocus) { + trapElement.focus(); + } - // make update() debounced, so that it only runs at most once-per-tick - this.update = debounce(this.update.bind(this)); + EventHandler.off(document, EVENT_KEY$7); // guard against infinite focus loop - // with {} we create a new object with the options inside it - this.options = _extends({}, Popper.Defaults, options); + EventHandler.on(document, EVENT_FOCUSIN$1, event => this._handleFocusin(event)); + EventHandler.on(document, EVENT_KEYDOWN_TAB, event => this._handleKeydown(event)); + this._isActive = true; + } - // init state - this.state = { - isDestroyed: false, - isCreated: false, - scrollParents: [] - }; + deactivate() { + if (!this._isActive) { + return; + } - // get reference and popper elements (allow jQuery wrappers) - this.reference = reference && reference.jquery ? reference[0] : reference; - this.popper = popper && popper.jquery ? popper[0] : popper; + this._isActive = false; + EventHandler.off(document, EVENT_KEY$7); + } // Private - // Deep merge modifiers options - this.options.modifiers = {}; - Object.keys(_extends({}, Popper.Defaults.modifiers, options.modifiers)).forEach(function (name) { - _this.options.modifiers[name] = _extends({}, Popper.Defaults.modifiers[name] || {}, options.modifiers ? options.modifiers[name] : {}); - }); - // Refactoring modifiers' list (Object => Array) - this.modifiers = Object.keys(this.options.modifiers).map(function (name) { - return _extends({ - name: name - }, _this.options.modifiers[name]); - }) - // sort the modifiers by order - .sort(function (a, b) { - return a.order - b.order; - }); + _handleFocusin(event) { + const { + target + } = event; + const { + trapElement + } = this._config; - // modifiers have the ability to execute arbitrary code when Popper.js get inited - // such code is executed in the same order of its modifier - // they could add new properties to their options configuration - // BE AWARE: don't add options to `options.modifiers.name` but to `modifierOptions`! - this.modifiers.forEach(function (modifierOptions) { - if (modifierOptions.enabled && isFunction(modifierOptions.onLoad)) { - modifierOptions.onLoad(_this.reference, _this.popper, _this.options, modifierOptions, _this.state); - } - }); + if (target === document || target === trapElement || trapElement.contains(target)) { + return; + } - // fire the first update to position the popper in the right place - this.update(); + const elements = SelectorEngine.focusableChildren(trapElement); - var eventsEnabled = this.options.eventsEnabled; - if (eventsEnabled) { - // setup event listeners, they will take care of update the position in specific situations - this.enableEventListeners(); + if (elements.length === 0) { + trapElement.focus(); + } else if (this._lastTabNavDirection === TAB_NAV_BACKWARD) { + elements[elements.length - 1].focus(); + } else { + elements[0].focus(); } - - this.state.eventsEnabled = eventsEnabled; } - // We can't use class properties because they don't get listed in the - // class prototype and break stuff like Sinon stubs - - - createClass(Popper, [{ - key: 'update', - value: function update$$1() { - return update.call(this); - } - }, { - key: 'destroy', - value: function destroy$$1() { - return destroy.call(this); - } - }, { - key: 'enableEventListeners', - value: function enableEventListeners$$1() { - return enableEventListeners.call(this); - } - }, { - key: 'disableEventListeners', - value: function disableEventListeners$$1() { - return disableEventListeners.call(this); + _handleKeydown(event) { + if (event.key !== TAB_KEY) { + return; } - /** - * Schedules an update. It will run on the next UI update available. - * @method scheduleUpdate - * @memberof Popper - */ - + this._lastTabNavDirection = event.shiftKey ? TAB_NAV_BACKWARD : TAB_NAV_FORWARD; + } - /** - * Collection of utilities useful when writing custom modifiers. - * Starting from version 1.7, this method is available only if you - * include `popper-utils.js` before `popper.js`. - * - * **DEPRECATION**: This way to access PopperUtils is deprecated - * and will be removed in v2! Use the PopperUtils module directly instead. - * Due to the high instability of the methods contained in Utils, we can't - * guarantee them to follow semver. Use them at your own risk! - * @static - * @private - * @type {Object} - * @deprecated since version 1.8 - * @member Utils - * @memberof Popper - */ + _getConfig(config) { + config = { ...Default$6, + ...(typeof config === 'object' ? config : {}) + }; + typeCheckConfig(NAME$7, config, DefaultType$6); + return config; + } - }]); - return Popper; - }(); + } /** - * The `referenceObject` is an object that provides an interface compatible with Popper.js - * and lets you use it as replacement of a real DOM node.
- * You can use this method to position a popper relatively to a set of coordinates - * in case you don't have a DOM node to use as reference. - * - * ``` - * new Popper(referenceObject, popperNode); - * ``` - * - * NB: This feature isn't supported in Internet Explorer 10. - * @name referenceObject - * @property {Function} data.getBoundingClientRect - * A function that returns a set of coordinates compatible with the native `getBoundingClientRect` method. - * @property {number} data.clientWidth - * An ES6 getter that will return the width of the virtual reference element. - * @property {number} data.clientHeight - * An ES6 getter that will return the height of the virtual reference element. + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): modal.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- */ - - - Popper.Utils = (typeof window !== 'undefined' ? window : global).PopperUtils; - Popper.placements = placements; - Popper.Defaults = Defaults; - /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ - var NAME$4 = 'dropdown'; - var VERSION$4 = '4.3.1'; - var DATA_KEY$4 = 'bs.dropdown'; - var EVENT_KEY$4 = "." + DATA_KEY$4; - var DATA_API_KEY$4 = '.data-api'; - var JQUERY_NO_CONFLICT$4 = $.fn[NAME$4]; - var ESCAPE_KEYCODE = 27; // KeyboardEvent.which value for Escape (Esc) key - - var SPACE_KEYCODE = 32; // KeyboardEvent.which value for space key - - var TAB_KEYCODE = 9; // KeyboardEvent.which value for tab key - - var ARROW_UP_KEYCODE = 38; // KeyboardEvent.which value for up arrow key - - var ARROW_DOWN_KEYCODE = 40; // KeyboardEvent.which value for down arrow key - - var RIGHT_MOUSE_BUTTON_WHICH = 3; // MouseEvent.which value for the right button (assuming a right-handed mouse) - - var REGEXP_KEYDOWN = new RegExp(ARROW_UP_KEYCODE + "|" + ARROW_DOWN_KEYCODE + "|" + ESCAPE_KEYCODE); - var Event$4 = { - HIDE: "hide" + EVENT_KEY$4, - HIDDEN: "hidden" + EVENT_KEY$4, - SHOW: "show" + EVENT_KEY$4, - SHOWN: "shown" + EVENT_KEY$4, - CLICK: "click" + EVENT_KEY$4, - CLICK_DATA_API: "click" + EVENT_KEY$4 + DATA_API_KEY$4, - KEYDOWN_DATA_API: "keydown" + EVENT_KEY$4 + DATA_API_KEY$4, - KEYUP_DATA_API: "keyup" + EVENT_KEY$4 + DATA_API_KEY$4 - }; - var ClassName$4 = { - DISABLED: 'disabled', - SHOW: 'show', - DROPUP: 'dropup', - DROPRIGHT: 'dropright', - DROPLEFT: 'dropleft', - MENURIGHT: 'dropdown-menu-right', - MENULEFT: 'dropdown-menu-left', - POSITION_STATIC: 'position-static' - }; - var Selector$4 = { - DATA_TOGGLE: '[data-toggle="dropdown"]', - FORM_CHILD: '.dropdown form', - MENU: '.dropdown-menu', - NAVBAR_NAV: '.navbar-nav', - VISIBLE_ITEMS: '.dropdown-menu .dropdown-item:not(.disabled):not(:disabled)' - }; - var AttachmentMap = { - TOP: 'top-start', - TOPEND: 'top-end', - BOTTOM: 'bottom-start', - BOTTOMEND: 'bottom-end', - RIGHT: 'right-start', - RIGHTEND: 'right-end', - LEFT: 'left-start', - LEFTEND: 'left-end' - }; - var Default$2 = { - offset: 0, - flip: true, - boundary: 'scrollParent', - reference: 'toggle', - display: 'dynamic' + const NAME$6 = 'modal'; + const DATA_KEY$6 = 'bs.modal'; + const EVENT_KEY$6 = `.${DATA_KEY$6}`; + const DATA_API_KEY$3 = '.data-api'; + const ESCAPE_KEY$1 = 'Escape'; + const Default$5 = { + backdrop: true, + keyboard: true, + focus: true }; - var DefaultType$2 = { - offset: '(number|string|function)', - flip: 'boolean', - boundary: '(string|element)', - reference: '(string|element)', - display: 'string' - /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ - */ - + const DefaultType$5 = { + backdrop: '(boolean|string)', + keyboard: 'boolean', + focus: 'boolean' }; + const EVENT_HIDE$3 = `hide${EVENT_KEY$6}`; + const EVENT_HIDE_PREVENTED = `hidePrevented${EVENT_KEY$6}`; + const EVENT_HIDDEN$3 = `hidden${EVENT_KEY$6}`; + const EVENT_SHOW$3 = `show${EVENT_KEY$6}`; + const EVENT_SHOWN$3 = `shown${EVENT_KEY$6}`; + const EVENT_RESIZE = `resize${EVENT_KEY$6}`; + const EVENT_CLICK_DISMISS = `click.dismiss${EVENT_KEY$6}`; + const EVENT_KEYDOWN_DISMISS$1 = `keydown.dismiss${EVENT_KEY$6}`; + const EVENT_MOUSEUP_DISMISS = `mouseup.dismiss${EVENT_KEY$6}`; + const EVENT_MOUSEDOWN_DISMISS = `mousedown.dismiss${EVENT_KEY$6}`; + const EVENT_CLICK_DATA_API$2 = `click${EVENT_KEY$6}${DATA_API_KEY$3}`; + const CLASS_NAME_OPEN = 'modal-open'; + const CLASS_NAME_FADE$3 = 'fade'; + const CLASS_NAME_SHOW$4 = 'show'; + const CLASS_NAME_STATIC = 'modal-static'; + const SELECTOR_DIALOG = '.modal-dialog'; + const SELECTOR_MODAL_BODY = '.modal-body'; + const SELECTOR_DATA_TOGGLE$2 = '[data-bs-toggle="modal"]'; + /** + * ------------------------------------------------------------------------ + * Class Definition + * ------------------------------------------------------------------------ + */ - var Dropdown = - /*#__PURE__*/ - function () { - function Dropdown(element, config) { - this._element = element; - this._popper = null; + class Modal extends BaseComponent { + constructor(element, config) { + super(element); this._config = this._getConfig(config); - this._menu = this._getMenuElement(); - this._inNavbar = this._detectNavbar(); - - this._addEventListeners(); + this._dialog = SelectorEngine.findOne(SELECTOR_DIALOG, this._element); + this._backdrop = this._initializeBackDrop(); + this._focustrap = this._initializeFocusTrap(); + this._isShown = false; + this._ignoreBackdropClick = false; + this._isTransitioning = false; + this._scrollBar = new ScrollBarHelper(); } // Getters - var _proto = Dropdown.prototype; - - // Public - _proto.toggle = function toggle() { - if (this._element.disabled || $(this._element).hasClass(ClassName$4.DISABLED)) { - return; - } + static get Default() { + return Default$5; + } - var parent = Dropdown._getParentFromElement(this._element); + static get NAME() { + return NAME$6; + } // Public - var isActive = $(this._menu).hasClass(ClassName$4.SHOW); - Dropdown._clearMenus(); + toggle(relatedTarget) { + return this._isShown ? this.hide() : this.show(relatedTarget); + } - if (isActive) { + show(relatedTarget) { + if (this._isShown || this._isTransitioning) { return; } - var relatedTarget = { - relatedTarget: this._element - }; - var showEvent = $.Event(Event$4.SHOW, relatedTarget); - $(parent).trigger(showEvent); + const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$3, { + relatedTarget + }); - if (showEvent.isDefaultPrevented()) { + if (showEvent.defaultPrevented) { return; - } // Disable totally Popper.js for Dropdown in Navbar + } + this._isShown = true; - if (!this._inNavbar) { - /** - * Check for Popper dependency - * Popper - https://popper.js.org - */ - if (typeof Popper === 'undefined') { - throw new TypeError('Bootstrap\'s dropdowns require Popper.js (https://popper.js.org/)'); - } + if (this._isAnimated()) { + this._isTransitioning = true; + } - var referenceElement = this._element; + this._scrollBar.hide(); - if (this._config.reference === 'parent') { - referenceElement = parent; - } else if (Util.isElement(this._config.reference)) { - referenceElement = this._config.reference; // Check if it's jQuery element + document.body.classList.add(CLASS_NAME_OPEN); - if (typeof this._config.reference.jquery !== 'undefined') { - referenceElement = this._config.reference[0]; - } - } // If boundary is not `scrollParent`, then set position to `static` - // to allow the menu to "escape" the scroll parent's boundaries - // https://github.com/twbs/bootstrap/issues/24251 + this._adjustDialog(); + this._setEscapeEvent(); - if (this._config.boundary !== 'scrollParent') { - $(parent).addClass(ClassName$4.POSITION_STATIC); - } + this._setResizeEvent(); - this._popper = new Popper(referenceElement, this._menu, this._getPopperConfig()); - } // If this is a touch-enabled device we add extra - // empty mouseover listeners to the body's immediate children; - // only needed because of broken event delegation on iOS - // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html + EventHandler.on(this._dialog, EVENT_MOUSEDOWN_DISMISS, () => { + EventHandler.one(this._element, EVENT_MOUSEUP_DISMISS, event => { + if (event.target === this._element) { + this._ignoreBackdropClick = true; + } + }); + }); + this._showBackdrop(() => this._showElement(relatedTarget)); + } - if ('ontouchstart' in document.documentElement && $(parent).closest(Selector$4.NAVBAR_NAV).length === 0) { - $(document.body).children().on('mouseover', null, $.noop); + hide() { + if (!this._isShown || this._isTransitioning) { + return; } - this._element.focus(); - - this._element.setAttribute('aria-expanded', true); - - $(this._menu).toggleClass(ClassName$4.SHOW); - $(parent).toggleClass(ClassName$4.SHOW).trigger($.Event(Event$4.SHOWN, relatedTarget)); - }; + const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$3); - _proto.show = function show() { - if (this._element.disabled || $(this._element).hasClass(ClassName$4.DISABLED) || $(this._menu).hasClass(ClassName$4.SHOW)) { + if (hideEvent.defaultPrevented) { return; } - var relatedTarget = { - relatedTarget: this._element - }; - var showEvent = $.Event(Event$4.SHOW, relatedTarget); - - var parent = Dropdown._getParentFromElement(this._element); + this._isShown = false; - $(parent).trigger(showEvent); + const isAnimated = this._isAnimated(); - if (showEvent.isDefaultPrevented()) { - return; + if (isAnimated) { + this._isTransitioning = true; } - $(this._menu).toggleClass(ClassName$4.SHOW); - $(parent).toggleClass(ClassName$4.SHOW).trigger($.Event(Event$4.SHOWN, relatedTarget)); - }; - - _proto.hide = function hide() { - if (this._element.disabled || $(this._element).hasClass(ClassName$4.DISABLED) || !$(this._menu).hasClass(ClassName$4.SHOW)) { - return; - } + this._setEscapeEvent(); - var relatedTarget = { - relatedTarget: this._element - }; - var hideEvent = $.Event(Event$4.HIDE, relatedTarget); + this._setResizeEvent(); - var parent = Dropdown._getParentFromElement(this._element); + this._focustrap.deactivate(); - $(parent).trigger(hideEvent); + this._element.classList.remove(CLASS_NAME_SHOW$4); - if (hideEvent.isDefaultPrevented()) { - return; - } + EventHandler.off(this._element, EVENT_CLICK_DISMISS); + EventHandler.off(this._dialog, EVENT_MOUSEDOWN_DISMISS); - $(this._menu).toggleClass(ClassName$4.SHOW); - $(parent).toggleClass(ClassName$4.SHOW).trigger($.Event(Event$4.HIDDEN, relatedTarget)); - }; + this._queueCallback(() => this._hideModal(), this._element, isAnimated); + } - _proto.dispose = function dispose() { - $.removeData(this._element, DATA_KEY$4); - $(this._element).off(EVENT_KEY$4); - this._element = null; - this._menu = null; + dispose() { + [window, this._dialog].forEach(htmlElement => EventHandler.off(htmlElement, EVENT_KEY$6)); - if (this._popper !== null) { - this._popper.destroy(); + this._backdrop.dispose(); - this._popper = null; - } - }; + this._focustrap.deactivate(); - _proto.update = function update() { - this._inNavbar = this._detectNavbar(); + super.dispose(); + } - if (this._popper !== null) { - this._popper.scheduleUpdate(); - } + handleUpdate() { + this._adjustDialog(); } // Private - ; - _proto._addEventListeners = function _addEventListeners() { - var _this = this; - $(this._element).on(Event$4.CLICK, function (event) { - event.preventDefault(); - event.stopPropagation(); + _initializeBackDrop() { + return new Backdrop({ + isVisible: Boolean(this._config.backdrop), + // 'static' option will be translated to true, and booleans will keep their value + isAnimated: this._isAnimated() + }); + } - _this.toggle(); + _initializeFocusTrap() { + return new FocusTrap({ + trapElement: this._element }); - }; + } - _proto._getConfig = function _getConfig(config) { - config = _objectSpread({}, this.constructor.Default, $(this._element).data(), config); - Util.typeCheckConfig(NAME$4, config, this.constructor.DefaultType); + _getConfig(config) { + config = { ...Default$5, + ...Manipulator.getDataAttributes(this._element), + ...(typeof config === 'object' ? config : {}) + }; + typeCheckConfig(NAME$6, config, DefaultType$5); return config; - }; - - _proto._getMenuElement = function _getMenuElement() { - if (!this._menu) { - var parent = Dropdown._getParentFromElement(this._element); + } - if (parent) { - this._menu = parent.querySelector(Selector$4.MENU); - } - } + _showElement(relatedTarget) { + const isAnimated = this._isAnimated(); - return this._menu; - }; + const modalBody = SelectorEngine.findOne(SELECTOR_MODAL_BODY, this._dialog); - _proto._getPlacement = function _getPlacement() { - var $parentDropdown = $(this._element.parentNode); - var placement = AttachmentMap.BOTTOM; // Handle dropup + if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) { + // Don't move modal's DOM position + document.body.append(this._element); + } - if ($parentDropdown.hasClass(ClassName$4.DROPUP)) { - placement = AttachmentMap.TOP; + this._element.style.display = 'block'; - if ($(this._menu).hasClass(ClassName$4.MENURIGHT)) { - placement = AttachmentMap.TOPEND; - } - } else if ($parentDropdown.hasClass(ClassName$4.DROPRIGHT)) { - placement = AttachmentMap.RIGHT; - } else if ($parentDropdown.hasClass(ClassName$4.DROPLEFT)) { - placement = AttachmentMap.LEFT; - } else if ($(this._menu).hasClass(ClassName$4.MENURIGHT)) { - placement = AttachmentMap.BOTTOMEND; - } + this._element.removeAttribute('aria-hidden'); - return placement; - }; + this._element.setAttribute('aria-modal', true); - _proto._detectNavbar = function _detectNavbar() { - return $(this._element).closest('.navbar').length > 0; - }; + this._element.setAttribute('role', 'dialog'); - _proto._getOffset = function _getOffset() { - var _this2 = this; + this._element.scrollTop = 0; - var offset = {}; + if (modalBody) { + modalBody.scrollTop = 0; + } - if (typeof this._config.offset === 'function') { - offset.fn = function (data) { - data.offsets = _objectSpread({}, data.offsets, _this2._config.offset(data.offsets, _this2._element) || {}); - return data; - }; - } else { - offset.offset = this._config.offset; + if (isAnimated) { + reflow(this._element); } - return offset; - }; + this._element.classList.add(CLASS_NAME_SHOW$4); - _proto._getPopperConfig = function _getPopperConfig() { - var popperConfig = { - placement: this._getPlacement(), - modifiers: { - offset: this._getOffset(), - flip: { - enabled: this._config.flip - }, - preventOverflow: { - boundariesElement: this._config.boundary - } - } // Disable Popper.js if we have a static display + const transitionComplete = () => { + if (this._config.focus) { + this._focustrap.activate(); + } + this._isTransitioning = false; + EventHandler.trigger(this._element, EVENT_SHOWN$3, { + relatedTarget + }); }; - if (this._config.display === 'static') { - popperConfig.modifiers.applyStyle = { - enabled: false - }; - } + this._queueCallback(transitionComplete, this._dialog, isAnimated); + } - return popperConfig; - } // Static - ; + _setEscapeEvent() { + if (this._isShown) { + EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS$1, event => { + if (this._config.keyboard && event.key === ESCAPE_KEY$1) { + event.preventDefault(); + this.hide(); + } else if (!this._config.keyboard && event.key === ESCAPE_KEY$1) { + this._triggerBackdropTransition(); + } + }); + } else { + EventHandler.off(this._element, EVENT_KEYDOWN_DISMISS$1); + } + } - Dropdown._jQueryInterface = function _jQueryInterface(config) { - return this.each(function () { - var data = $(this).data(DATA_KEY$4); + _setResizeEvent() { + if (this._isShown) { + EventHandler.on(window, EVENT_RESIZE, () => this._adjustDialog()); + } else { + EventHandler.off(window, EVENT_RESIZE); + } + } - var _config = typeof config === 'object' ? config : null; + _hideModal() { + this._element.style.display = 'none'; - if (!data) { - data = new Dropdown(this, _config); - $(this).data(DATA_KEY$4, data); - } + this._element.setAttribute('aria-hidden', true); - if (typeof config === 'string') { - if (typeof data[config] === 'undefined') { - throw new TypeError("No method named \"" + config + "\""); - } + this._element.removeAttribute('aria-modal'); - data[config](); - } - }); - }; + this._element.removeAttribute('role'); - Dropdown._clearMenus = function _clearMenus(event) { - if (event && (event.which === RIGHT_MOUSE_BUTTON_WHICH || event.type === 'keyup' && event.which !== TAB_KEYCODE)) { - return; - } + this._isTransitioning = false; - var toggles = [].slice.call(document.querySelectorAll(Selector$4.DATA_TOGGLE)); + this._backdrop.hide(() => { + document.body.classList.remove(CLASS_NAME_OPEN); - for (var i = 0, len = toggles.length; i < len; i++) { - var parent = Dropdown._getParentFromElement(toggles[i]); + this._resetAdjustments(); - var context = $(toggles[i]).data(DATA_KEY$4); - var relatedTarget = { - relatedTarget: toggles[i] - }; + this._scrollBar.reset(); - if (event && event.type === 'click') { - relatedTarget.clickEvent = event; - } + EventHandler.trigger(this._element, EVENT_HIDDEN$3); + }); + } - if (!context) { - continue; + _showBackdrop(callback) { + EventHandler.on(this._element, EVENT_CLICK_DISMISS, event => { + if (this._ignoreBackdropClick) { + this._ignoreBackdropClick = false; + return; } - var dropdownMenu = context._menu; - - if (!$(parent).hasClass(ClassName$4.SHOW)) { - continue; + if (event.target !== event.currentTarget) { + return; } - if (event && (event.type === 'click' && /input|textarea/i.test(event.target.tagName) || event.type === 'keyup' && event.which === TAB_KEYCODE) && $.contains(parent, event.target)) { - continue; + if (this._config.backdrop === true) { + this.hide(); + } else if (this._config.backdrop === 'static') { + this._triggerBackdropTransition(); } + }); - var hideEvent = $.Event(Event$4.HIDE, relatedTarget); - $(parent).trigger(hideEvent); - - if (hideEvent.isDefaultPrevented()) { - continue; - } // If this is a touch-enabled device we remove the extra - // empty mouseover listeners we added for iOS support - - - if ('ontouchstart' in document.documentElement) { - $(document.body).children().off('mouseover', null, $.noop); - } + this._backdrop.show(callback); + } - toggles[i].setAttribute('aria-expanded', 'false'); - $(dropdownMenu).removeClass(ClassName$4.SHOW); - $(parent).removeClass(ClassName$4.SHOW).trigger($.Event(Event$4.HIDDEN, relatedTarget)); - } - }; + _isAnimated() { + return this._element.classList.contains(CLASS_NAME_FADE$3); + } - Dropdown._getParentFromElement = function _getParentFromElement(element) { - var parent; - var selector = Util.getSelectorFromElement(element); + _triggerBackdropTransition() { + const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED); - if (selector) { - parent = document.querySelector(selector); + if (hideEvent.defaultPrevented) { + return; } - return parent || element.parentNode; - } // eslint-disable-next-line complexity - ; + const { + classList, + scrollHeight, + style + } = this._element; + const isModalOverflowing = scrollHeight > document.documentElement.clientHeight; // return if the following background transition hasn't yet completed - Dropdown._dataApiKeydownHandler = function _dataApiKeydownHandler(event) { - // If not input/textarea: - // - And not a key in REGEXP_KEYDOWN => not a dropdown command - // If input/textarea: - // - If space key => not a dropdown command - // - If key is other than escape - // - If key is not up or down => not a dropdown command - // - If trigger inside the menu => not a dropdown command - if (/input|textarea/i.test(event.target.tagName) ? event.which === SPACE_KEYCODE || event.which !== ESCAPE_KEYCODE && (event.which !== ARROW_DOWN_KEYCODE && event.which !== ARROW_UP_KEYCODE || $(event.target).closest(Selector$4.MENU).length) : !REGEXP_KEYDOWN.test(event.which)) { + if (!isModalOverflowing && style.overflowY === 'hidden' || classList.contains(CLASS_NAME_STATIC)) { return; } - event.preventDefault(); - event.stopPropagation(); - - if (this.disabled || $(this).hasClass(ClassName$4.DISABLED)) { - return; + if (!isModalOverflowing) { + style.overflowY = 'hidden'; } - var parent = Dropdown._getParentFromElement(this); + classList.add(CLASS_NAME_STATIC); - var isActive = $(parent).hasClass(ClassName$4.SHOW); + this._queueCallback(() => { + classList.remove(CLASS_NAME_STATIC); - if (!isActive || isActive && (event.which === ESCAPE_KEYCODE || event.which === SPACE_KEYCODE)) { - if (event.which === ESCAPE_KEYCODE) { - var toggle = parent.querySelector(Selector$4.DATA_TOGGLE); - $(toggle).trigger('focus'); + if (!isModalOverflowing) { + this._queueCallback(() => { + style.overflowY = ''; + }, this._dialog); } + }, this._dialog); + + this._element.focus(); + } // ---------------------------------------------------------------------- + // the following methods are used to handle overflowing modals + // ---------------------------------------------------------------------- - $(this).trigger('click'); - return; - } - var items = [].slice.call(parent.querySelectorAll(Selector$4.VISIBLE_ITEMS)); + _adjustDialog() { + const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight; - if (items.length === 0) { - return; - } + const scrollbarWidth = this._scrollBar.getWidth(); - var index = items.indexOf(event.target); + const isBodyOverflowing = scrollbarWidth > 0; - if (event.which === ARROW_UP_KEYCODE && index > 0) { - // Up - index--; + if (!isBodyOverflowing && isModalOverflowing && !isRTL() || isBodyOverflowing && !isModalOverflowing && isRTL()) { + this._element.style.paddingLeft = `${scrollbarWidth}px`; } - if (event.which === ARROW_DOWN_KEYCODE && index < items.length - 1) { - // Down - index++; + if (isBodyOverflowing && !isModalOverflowing && !isRTL() || !isBodyOverflowing && isModalOverflowing && isRTL()) { + this._element.style.paddingRight = `${scrollbarWidth}px`; } + } - if (index < 0) { - index = 0; - } + _resetAdjustments() { + this._element.style.paddingLeft = ''; + this._element.style.paddingRight = ''; + } // Static - items[index].focus(); - }; - _createClass(Dropdown, null, [{ - key: "VERSION", - get: function get() { - return VERSION$4; - } - }, { - key: "Default", - get: function get() { - return Default$2; - } - }, { - key: "DefaultType", - get: function get() { - return DefaultType$2; - } - }]); + static jQueryInterface(config, relatedTarget) { + return this.each(function () { + const data = Modal.getOrCreateInstance(this, config); + + if (typeof config !== 'string') { + return; + } + + if (typeof data[config] === 'undefined') { + throw new TypeError(`No method named "${config}"`); + } + + data[config](relatedTarget); + }); + } - return Dropdown; - }(); + } /** * ------------------------------------------------------------------------ * Data Api implementation @@ -4584,619 +4880,340 @@ */ - $(document).on(Event$4.KEYDOWN_DATA_API, Selector$4.DATA_TOGGLE, Dropdown._dataApiKeydownHandler).on(Event$4.KEYDOWN_DATA_API, Selector$4.MENU, Dropdown._dataApiKeydownHandler).on(Event$4.CLICK_DATA_API + " " + Event$4.KEYUP_DATA_API, Dropdown._clearMenus).on(Event$4.CLICK_DATA_API, Selector$4.DATA_TOGGLE, function (event) { - event.preventDefault(); - event.stopPropagation(); + EventHandler.on(document, EVENT_CLICK_DATA_API$2, SELECTOR_DATA_TOGGLE$2, function (event) { + const target = getElementFromSelector(this); + + if (['A', 'AREA'].includes(this.tagName)) { + event.preventDefault(); + } + + EventHandler.one(target, EVENT_SHOW$3, showEvent => { + if (showEvent.defaultPrevented) { + // only register focus restorer if modal will actually get shown + return; + } - Dropdown._jQueryInterface.call($(this), 'toggle'); - }).on(Event$4.CLICK_DATA_API, Selector$4.FORM_CHILD, function (e) { - e.stopPropagation(); + EventHandler.one(target, EVENT_HIDDEN$3, () => { + if (isVisible(this)) { + this.focus(); + } + }); + }); + const data = Modal.getOrCreateInstance(target); + data.toggle(this); }); + enableDismissTrigger(Modal); /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ + * add .Modal to jQuery only if jQuery is present */ - $.fn[NAME$4] = Dropdown._jQueryInterface; - $.fn[NAME$4].Constructor = Dropdown; - - $.fn[NAME$4].noConflict = function () { - $.fn[NAME$4] = JQUERY_NO_CONFLICT$4; - return Dropdown._jQueryInterface; - }; + defineJQueryPlugin(Modal); + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): offcanvas.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) + * -------------------------------------------------------------------------- + */ /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ - var NAME$5 = 'modal'; - var VERSION$5 = '4.3.1'; - var DATA_KEY$5 = 'bs.modal'; - var EVENT_KEY$5 = "." + DATA_KEY$5; - var DATA_API_KEY$5 = '.data-api'; - var JQUERY_NO_CONFLICT$5 = $.fn[NAME$5]; - var ESCAPE_KEYCODE$1 = 27; // KeyboardEvent.which value for Escape (Esc) key - - var Default$3 = { + const NAME$5 = 'offcanvas'; + const DATA_KEY$5 = 'bs.offcanvas'; + const EVENT_KEY$5 = `.${DATA_KEY$5}`; + const DATA_API_KEY$2 = '.data-api'; + const EVENT_LOAD_DATA_API$1 = `load${EVENT_KEY$5}${DATA_API_KEY$2}`; + const ESCAPE_KEY = 'Escape'; + const Default$4 = { backdrop: true, keyboard: true, - focus: true, - show: true + scroll: false }; - var DefaultType$3 = { - backdrop: '(boolean|string)', + const DefaultType$4 = { + backdrop: 'boolean', keyboard: 'boolean', - focus: 'boolean', - show: 'boolean' - }; - var Event$5 = { - HIDE: "hide" + EVENT_KEY$5, - HIDDEN: "hidden" + EVENT_KEY$5, - SHOW: "show" + EVENT_KEY$5, - SHOWN: "shown" + EVENT_KEY$5, - FOCUSIN: "focusin" + EVENT_KEY$5, - RESIZE: "resize" + EVENT_KEY$5, - CLICK_DISMISS: "click.dismiss" + EVENT_KEY$5, - KEYDOWN_DISMISS: "keydown.dismiss" + EVENT_KEY$5, - MOUSEUP_DISMISS: "mouseup.dismiss" + EVENT_KEY$5, - MOUSEDOWN_DISMISS: "mousedown.dismiss" + EVENT_KEY$5, - CLICK_DATA_API: "click" + EVENT_KEY$5 + DATA_API_KEY$5 - }; - var ClassName$5 = { - SCROLLABLE: 'modal-dialog-scrollable', - SCROLLBAR_MEASURER: 'modal-scrollbar-measure', - BACKDROP: 'modal-backdrop', - OPEN: 'modal-open', - FADE: 'fade', - SHOW: 'show' - }; - var Selector$5 = { - DIALOG: '.modal-dialog', - MODAL_BODY: '.modal-body', - DATA_TOGGLE: '[data-toggle="modal"]', - DATA_DISMISS: '[data-dismiss="modal"]', - FIXED_CONTENT: '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top', - STICKY_CONTENT: '.sticky-top' - /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ - */ - + scroll: 'boolean' }; + const CLASS_NAME_SHOW$3 = 'show'; + const CLASS_NAME_BACKDROP = 'offcanvas-backdrop'; + const OPEN_SELECTOR = '.offcanvas.show'; + const EVENT_SHOW$2 = `show${EVENT_KEY$5}`; + const EVENT_SHOWN$2 = `shown${EVENT_KEY$5}`; + const EVENT_HIDE$2 = `hide${EVENT_KEY$5}`; + const EVENT_HIDDEN$2 = `hidden${EVENT_KEY$5}`; + const EVENT_CLICK_DATA_API$1 = `click${EVENT_KEY$5}${DATA_API_KEY$2}`; + const EVENT_KEYDOWN_DISMISS = `keydown.dismiss${EVENT_KEY$5}`; + const SELECTOR_DATA_TOGGLE$1 = '[data-bs-toggle="offcanvas"]'; + /** + * ------------------------------------------------------------------------ + * Class Definition + * ------------------------------------------------------------------------ + */ - var Modal = - /*#__PURE__*/ - function () { - function Modal(element, config) { + class Offcanvas extends BaseComponent { + constructor(element, config) { + super(element); this._config = this._getConfig(config); - this._element = element; - this._dialog = element.querySelector(Selector$5.DIALOG); - this._backdrop = null; this._isShown = false; - this._isBodyOverflowing = false; - this._ignoreBackdropClick = false; - this._isTransitioning = false; - this._scrollbarWidth = 0; + this._backdrop = this._initializeBackDrop(); + this._focustrap = this._initializeFocusTrap(); + + this._addEventListeners(); } // Getters - var _proto = Modal.prototype; + static get NAME() { + return NAME$5; + } - // Public - _proto.toggle = function toggle(relatedTarget) { - return this._isShown ? this.hide() : this.show(relatedTarget); - }; + static get Default() { + return Default$4; + } // Public - _proto.show = function show(relatedTarget) { - var _this = this; - if (this._isShown || this._isTransitioning) { - return; - } + toggle(relatedTarget) { + return this._isShown ? this.hide() : this.show(relatedTarget); + } - if ($(this._element).hasClass(ClassName$5.FADE)) { - this._isTransitioning = true; + show(relatedTarget) { + if (this._isShown) { + return; } - var showEvent = $.Event(Event$5.SHOW, { - relatedTarget: relatedTarget + const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$2, { + relatedTarget }); - $(this._element).trigger(showEvent); - if (this._isShown || showEvent.isDefaultPrevented()) { + if (showEvent.defaultPrevented) { return; } this._isShown = true; + this._element.style.visibility = 'visible'; - this._checkScrollbar(); + this._backdrop.show(); - this._setScrollbar(); + if (!this._config.scroll) { + new ScrollBarHelper().hide(); + } - this._adjustDialog(); + this._element.removeAttribute('aria-hidden'); - this._setEscapeEvent(); + this._element.setAttribute('aria-modal', true); - this._setResizeEvent(); + this._element.setAttribute('role', 'dialog'); - $(this._element).on(Event$5.CLICK_DISMISS, Selector$5.DATA_DISMISS, function (event) { - return _this.hide(event); - }); - $(this._dialog).on(Event$5.MOUSEDOWN_DISMISS, function () { - $(_this._element).one(Event$5.MOUSEUP_DISMISS, function (event) { - if ($(event.target).is(_this._element)) { - _this._ignoreBackdropClick = true; - } - }); - }); + this._element.classList.add(CLASS_NAME_SHOW$3); - this._showBackdrop(function () { - return _this._showElement(relatedTarget); - }); - }; + const completeCallBack = () => { + if (!this._config.scroll) { + this._focustrap.activate(); + } - _proto.hide = function hide(event) { - var _this2 = this; + EventHandler.trigger(this._element, EVENT_SHOWN$2, { + relatedTarget + }); + }; - if (event) { - event.preventDefault(); - } + this._queueCallback(completeCallBack, this._element, true); + } - if (!this._isShown || this._isTransitioning) { + hide() { + if (!this._isShown) { return; } - var hideEvent = $.Event(Event$5.HIDE); - $(this._element).trigger(hideEvent); + const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$2); - if (!this._isShown || hideEvent.isDefaultPrevented()) { + if (hideEvent.defaultPrevented) { return; } - this._isShown = false; - var transition = $(this._element).hasClass(ClassName$5.FADE); - - if (transition) { - this._isTransitioning = true; - } - - this._setEscapeEvent(); - - this._setResizeEvent(); - - $(document).off(Event$5.FOCUSIN); - $(this._element).removeClass(ClassName$5.SHOW); - $(this._element).off(Event$5.CLICK_DISMISS); - $(this._dialog).off(Event$5.MOUSEDOWN_DISMISS); - - if (transition) { - var transitionDuration = Util.getTransitionDurationFromElement(this._element); - $(this._element).one(Util.TRANSITION_END, function (event) { - return _this2._hideModal(event); - }).emulateTransitionEnd(transitionDuration); - } else { - this._hideModal(); - } - }; - - _proto.dispose = function dispose() { - [window, this._element, this._dialog].forEach(function (htmlElement) { - return $(htmlElement).off(EVENT_KEY$5); - }); - /** - * `document` has 2 events `Event.FOCUSIN` and `Event.CLICK_DATA_API` - * Do not move `document` in `htmlElements` array - * It will remove `Event.CLICK_DATA_API` event that should remain - */ - - $(document).off(Event$5.FOCUSIN); - $.removeData(this._element, DATA_KEY$5); - this._config = null; - this._element = null; - this._dialog = null; - this._backdrop = null; - this._isShown = null; - this._isBodyOverflowing = null; - this._ignoreBackdropClick = null; - this._isTransitioning = null; - this._scrollbarWidth = null; - }; - - _proto.handleUpdate = function handleUpdate() { - this._adjustDialog(); - } // Private - ; - - _proto._getConfig = function _getConfig(config) { - config = _objectSpread({}, Default$3, config); - Util.typeCheckConfig(NAME$5, config, DefaultType$3); - return config; - }; - - _proto._showElement = function _showElement(relatedTarget) { - var _this3 = this; - - var transition = $(this._element).hasClass(ClassName$5.FADE); - - if (!this._element.parentNode || this._element.parentNode.nodeType !== Node.ELEMENT_NODE) { - // Don't move modal's DOM position - document.body.appendChild(this._element); - } + this._focustrap.deactivate(); - this._element.style.display = 'block'; + this._element.blur(); - this._element.removeAttribute('aria-hidden'); + this._isShown = false; - this._element.setAttribute('aria-modal', true); + this._element.classList.remove(CLASS_NAME_SHOW$3); - if ($(this._dialog).hasClass(ClassName$5.SCROLLABLE)) { - this._dialog.querySelector(Selector$5.MODAL_BODY).scrollTop = 0; - } else { - this._element.scrollTop = 0; - } + this._backdrop.hide(); - if (transition) { - Util.reflow(this._element); - } + const completeCallback = () => { + this._element.setAttribute('aria-hidden', true); - $(this._element).addClass(ClassName$5.SHOW); + this._element.removeAttribute('aria-modal'); - if (this._config.focus) { - this._enforceFocus(); - } + this._element.removeAttribute('role'); - var shownEvent = $.Event(Event$5.SHOWN, { - relatedTarget: relatedTarget - }); + this._element.style.visibility = 'hidden'; - var transitionComplete = function transitionComplete() { - if (_this3._config.focus) { - _this3._element.focus(); + if (!this._config.scroll) { + new ScrollBarHelper().reset(); } - _this3._isTransitioning = false; - $(_this3._element).trigger(shownEvent); + EventHandler.trigger(this._element, EVENT_HIDDEN$2); }; - if (transition) { - var transitionDuration = Util.getTransitionDurationFromElement(this._dialog); - $(this._dialog).one(Util.TRANSITION_END, transitionComplete).emulateTransitionEnd(transitionDuration); - } else { - transitionComplete(); - } - }; - - _proto._enforceFocus = function _enforceFocus() { - var _this4 = this; - - $(document).off(Event$5.FOCUSIN) // Guard against infinite focus loop - .on(Event$5.FOCUSIN, function (event) { - if (document !== event.target && _this4._element !== event.target && $(_this4._element).has(event.target).length === 0) { - _this4._element.focus(); - } - }); - }; - - _proto._setEscapeEvent = function _setEscapeEvent() { - var _this5 = this; - - if (this._isShown && this._config.keyboard) { - $(this._element).on(Event$5.KEYDOWN_DISMISS, function (event) { - if (event.which === ESCAPE_KEYCODE$1) { - event.preventDefault(); - - _this5.hide(); - } - }); - } else if (!this._isShown) { - $(this._element).off(Event$5.KEYDOWN_DISMISS); - } - }; - - _proto._setResizeEvent = function _setResizeEvent() { - var _this6 = this; - - if (this._isShown) { - $(window).on(Event$5.RESIZE, function (event) { - return _this6.handleUpdate(event); - }); - } else { - $(window).off(Event$5.RESIZE); - } - }; - - _proto._hideModal = function _hideModal() { - var _this7 = this; - - this._element.style.display = 'none'; - - this._element.setAttribute('aria-hidden', true); + this._queueCallback(completeCallback, this._element, true); + } - this._element.removeAttribute('aria-modal'); + dispose() { + this._backdrop.dispose(); - this._isTransitioning = false; + this._focustrap.deactivate(); - this._showBackdrop(function () { - $(document.body).removeClass(ClassName$5.OPEN); + super.dispose(); + } // Private - _this7._resetAdjustments(); - _this7._resetScrollbar(); + _getConfig(config) { + config = { ...Default$4, + ...Manipulator.getDataAttributes(this._element), + ...(typeof config === 'object' ? config : {}) + }; + typeCheckConfig(NAME$5, config, DefaultType$4); + return config; + } - $(_this7._element).trigger(Event$5.HIDDEN); + _initializeBackDrop() { + return new Backdrop({ + className: CLASS_NAME_BACKDROP, + isVisible: this._config.backdrop, + isAnimated: true, + rootElement: this._element.parentNode, + clickCallback: () => this.hide() }); - }; - - _proto._removeBackdrop = function _removeBackdrop() { - if (this._backdrop) { - $(this._backdrop).remove(); - this._backdrop = null; - } - }; - - _proto._showBackdrop = function _showBackdrop(callback) { - var _this8 = this; - - var animate = $(this._element).hasClass(ClassName$5.FADE) ? ClassName$5.FADE : ''; - - if (this._isShown && this._config.backdrop) { - this._backdrop = document.createElement('div'); - this._backdrop.className = ClassName$5.BACKDROP; - - if (animate) { - this._backdrop.classList.add(animate); - } - - $(this._backdrop).appendTo(document.body); - $(this._element).on(Event$5.CLICK_DISMISS, function (event) { - if (_this8._ignoreBackdropClick) { - _this8._ignoreBackdropClick = false; - return; - } - - if (event.target !== event.currentTarget) { - return; - } + } - if (_this8._config.backdrop === 'static') { - _this8._element.focus(); - } else { - _this8.hide(); - } - }); + _initializeFocusTrap() { + return new FocusTrap({ + trapElement: this._element + }); + } - if (animate) { - Util.reflow(this._backdrop); + _addEventListeners() { + EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS, event => { + if (this._config.keyboard && event.key === ESCAPE_KEY) { + this.hide(); } + }); + } // Static - $(this._backdrop).addClass(ClassName$5.SHOW); - if (!callback) { - return; - } + static jQueryInterface(config) { + return this.each(function () { + const data = Offcanvas.getOrCreateInstance(this, config); - if (!animate) { - callback(); + if (typeof config !== 'string') { return; } - var backdropTransitionDuration = Util.getTransitionDurationFromElement(this._backdrop); - $(this._backdrop).one(Util.TRANSITION_END, callback).emulateTransitionEnd(backdropTransitionDuration); - } else if (!this._isShown && this._backdrop) { - $(this._backdrop).removeClass(ClassName$5.SHOW); - - var callbackRemove = function callbackRemove() { - _this8._removeBackdrop(); - - if (callback) { - callback(); - } - }; - - if ($(this._element).hasClass(ClassName$5.FADE)) { - var _backdropTransitionDuration = Util.getTransitionDurationFromElement(this._backdrop); - - $(this._backdrop).one(Util.TRANSITION_END, callbackRemove).emulateTransitionEnd(_backdropTransitionDuration); - } else { - callbackRemove(); + if (data[config] === undefined || config.startsWith('_') || config === 'constructor') { + throw new TypeError(`No method named "${config}"`); } - } else if (callback) { - callback(); - } - } // ---------------------------------------------------------------------- - // the following methods are used to handle overflowing modals - // todo (fat): these should probably be refactored out of modal.js - // ---------------------------------------------------------------------- - ; - - _proto._adjustDialog = function _adjustDialog() { - var isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight; - - if (!this._isBodyOverflowing && isModalOverflowing) { - this._element.style.paddingLeft = this._scrollbarWidth + "px"; - } - - if (this._isBodyOverflowing && !isModalOverflowing) { - this._element.style.paddingRight = this._scrollbarWidth + "px"; - } - }; - _proto._resetAdjustments = function _resetAdjustments() { - this._element.style.paddingLeft = ''; - this._element.style.paddingRight = ''; - }; + data[config](this); + }); + } - _proto._checkScrollbar = function _checkScrollbar() { - var rect = document.body.getBoundingClientRect(); - this._isBodyOverflowing = rect.left + rect.right < window.innerWidth; - this._scrollbarWidth = this._getScrollbarWidth(); - }; + } + /** + * ------------------------------------------------------------------------ + * Data Api implementation + * ------------------------------------------------------------------------ + */ - _proto._setScrollbar = function _setScrollbar() { - var _this9 = this; - if (this._isBodyOverflowing) { - // Note: DOMNode.style.paddingRight returns the actual value or '' if not set - // while $(DOMNode).css('padding-right') returns the calculated value or 0 if not set - var fixedContent = [].slice.call(document.querySelectorAll(Selector$5.FIXED_CONTENT)); - var stickyContent = [].slice.call(document.querySelectorAll(Selector$5.STICKY_CONTENT)); // Adjust fixed content padding + EventHandler.on(document, EVENT_CLICK_DATA_API$1, SELECTOR_DATA_TOGGLE$1, function (event) { + const target = getElementFromSelector(this); - $(fixedContent).each(function (index, element) { - var actualPadding = element.style.paddingRight; - var calculatedPadding = $(element).css('padding-right'); - $(element).data('padding-right', actualPadding).css('padding-right', parseFloat(calculatedPadding) + _this9._scrollbarWidth + "px"); - }); // Adjust sticky content margin + if (['A', 'AREA'].includes(this.tagName)) { + event.preventDefault(); + } - $(stickyContent).each(function (index, element) { - var actualMargin = element.style.marginRight; - var calculatedMargin = $(element).css('margin-right'); - $(element).data('margin-right', actualMargin).css('margin-right', parseFloat(calculatedMargin) - _this9._scrollbarWidth + "px"); - }); // Adjust body padding + if (isDisabled(this)) { + return; + } - var actualPadding = document.body.style.paddingRight; - var calculatedPadding = $(document.body).css('padding-right'); - $(document.body).data('padding-right', actualPadding).css('padding-right', parseFloat(calculatedPadding) + this._scrollbarWidth + "px"); + EventHandler.one(target, EVENT_HIDDEN$2, () => { + // focus on trigger when it is closed + if (isVisible(this)) { + this.focus(); } + }); // avoid conflict when clicking a toggler of an offcanvas, while another is open - $(document.body).addClass(ClassName$5.OPEN); - }; - - _proto._resetScrollbar = function _resetScrollbar() { - // Restore fixed content padding - var fixedContent = [].slice.call(document.querySelectorAll(Selector$5.FIXED_CONTENT)); - $(fixedContent).each(function (index, element) { - var padding = $(element).data('padding-right'); - $(element).removeData('padding-right'); - element.style.paddingRight = padding ? padding : ''; - }); // Restore sticky content - - var elements = [].slice.call(document.querySelectorAll("" + Selector$5.STICKY_CONTENT)); - $(elements).each(function (index, element) { - var margin = $(element).data('margin-right'); - - if (typeof margin !== 'undefined') { - $(element).css('margin-right', margin).removeData('margin-right'); - } - }); // Restore body padding - - var padding = $(document.body).data('padding-right'); - $(document.body).removeData('padding-right'); - document.body.style.paddingRight = padding ? padding : ''; - }; - - _proto._getScrollbarWidth = function _getScrollbarWidth() { - // thx d.walsh - var scrollDiv = document.createElement('div'); - scrollDiv.className = ClassName$5.SCROLLBAR_MEASURER; - document.body.appendChild(scrollDiv); - var scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth; - document.body.removeChild(scrollDiv); - return scrollbarWidth; - } // Static - ; - - Modal._jQueryInterface = function _jQueryInterface(config, relatedTarget) { - return this.each(function () { - var data = $(this).data(DATA_KEY$5); - - var _config = _objectSpread({}, Default$3, $(this).data(), typeof config === 'object' && config ? config : {}); + const allReadyOpen = SelectorEngine.findOne(OPEN_SELECTOR); - if (!data) { - data = new Modal(this, _config); - $(this).data(DATA_KEY$5, data); - } + if (allReadyOpen && allReadyOpen !== target) { + Offcanvas.getInstance(allReadyOpen).hide(); + } - if (typeof config === 'string') { - if (typeof data[config] === 'undefined') { - throw new TypeError("No method named \"" + config + "\""); - } + const data = Offcanvas.getOrCreateInstance(target); + data.toggle(this); + }); + EventHandler.on(window, EVENT_LOAD_DATA_API$1, () => SelectorEngine.find(OPEN_SELECTOR).forEach(el => Offcanvas.getOrCreateInstance(el).show())); + enableDismissTrigger(Offcanvas); + /** + * ------------------------------------------------------------------------ + * jQuery + * ------------------------------------------------------------------------ + */ - data[config](relatedTarget); - } else if (_config.show) { - data.show(relatedTarget); - } - }); - }; + defineJQueryPlugin(Offcanvas); - _createClass(Modal, null, [{ - key: "VERSION", - get: function get() { - return VERSION$5; - } - }, { - key: "Default", - get: function get() { - return Default$3; - } - }]); + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): util/sanitizer.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + const uriAttrs = new Set(['background', 'cite', 'href', 'itemtype', 'longdesc', 'poster', 'src', 'xlink:href']); + const ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i; + /** + * A pattern that recognizes a commonly useful subset of URLs that are safe. + * + * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts + */ - return Modal; - }(); + const SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^#&/:?]*(?:[#/?]|$))/i; /** - * ------------------------------------------------------------------------ - * Data Api implementation - * ------------------------------------------------------------------------ + * A pattern that matches safe data URLs. Only matches image, video and audio types. + * + * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts */ + const DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[\d+/a-z]+=*$/i; - $(document).on(Event$5.CLICK_DATA_API, Selector$5.DATA_TOGGLE, function (event) { - var _this10 = this; + const allowedAttribute = (attr, allowedAttributeList) => { + const attrName = attr.nodeName.toLowerCase(); - var target; - var selector = Util.getSelectorFromElement(this); + if (allowedAttributeList.includes(attrName)) { + if (uriAttrs.has(attrName)) { + return Boolean(SAFE_URL_PATTERN.test(attr.nodeValue) || DATA_URL_PATTERN.test(attr.nodeValue)); + } - if (selector) { - target = document.querySelector(selector); + return true; } - var config = $(target).data(DATA_KEY$5) ? 'toggle' : _objectSpread({}, $(target).data(), $(this).data()); - - if (this.tagName === 'A' || this.tagName === 'AREA') { - event.preventDefault(); - } + const regExp = allowedAttributeList.filter(attrRegex => attrRegex instanceof RegExp); // Check if a regular expression validates the attribute. - var $target = $(target).one(Event$5.SHOW, function (showEvent) { - if (showEvent.isDefaultPrevented()) { - // Only register focus restorer if modal will actually get shown - return; + for (let i = 0, len = regExp.length; i < len; i++) { + if (regExp[i].test(attrName)) { + return true; } + } - $target.one(Event$5.HIDDEN, function () { - if ($(_this10).is(':visible')) { - _this10.focus(); - } - }); - }); - - Modal._jQueryInterface.call($(target), config, this); - }); - /** - * ------------------------------------------------------------------------ - * jQuery - * ------------------------------------------------------------------------ - */ - - $.fn[NAME$5] = Modal._jQueryInterface; - $.fn[NAME$5].Constructor = Modal; - - $.fn[NAME$5].noConflict = function () { - $.fn[NAME$5] = JQUERY_NO_CONFLICT$5; - return Modal._jQueryInterface; + return false; }; - /** - * -------------------------------------------------------------------------- - * Bootstrap (v4.3.1): tools/sanitizer.js - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) - * -------------------------------------------------------------------------- - */ - var uriAttrs = ['background', 'cite', 'href', 'itemtype', 'longdesc', 'poster', 'src', 'xlink:href']; - var ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i; - var DefaultWhitelist = { + const DefaultAllowlist = { // Global attributes allowed on any supplied element below. '*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN], a: ['target', 'href', 'title', 'rel'], @@ -5215,7 +5232,7 @@ h5: [], h6: [], i: [], - img: ['src', 'alt', 'title', 'width', 'height'], + img: ['src', 'srcset', 'alt', 'title', 'width', 'height'], li: [], ol: [], p: [], @@ -5228,48 +5245,9 @@ strong: [], u: [], ul: [] - /** - * A pattern that recognizes a commonly useful subset of URLs that are safe. - * - * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts - */ - }; - var SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi; - /** - * A pattern that matches safe data URLs. Only matches image, video and audio types. - * - * Shoutout to Angular 7 https://github.com/angular/angular/blob/7.2.4/packages/core/src/sanitization/url_sanitizer.ts - */ - - var DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+/]+=*$/i; - - function allowedAttribute(attr, allowedAttributeList) { - var attrName = attr.nodeName.toLowerCase(); - - if (allowedAttributeList.indexOf(attrName) !== -1) { - if (uriAttrs.indexOf(attrName) !== -1) { - return Boolean(attr.nodeValue.match(SAFE_URL_PATTERN) || attr.nodeValue.match(DATA_URL_PATTERN)); - } - - return true; - } - - var regExp = allowedAttributeList.filter(function (attrRegex) { - return attrRegex instanceof RegExp; - }); // Check if a regular expression validates the attribute. - - for (var i = 0, l = regExp.length; i < l; i++) { - if (attrName.match(regExp[i])) { - return true; - } - } - - return false; - } - - function sanitizeHtml(unsafeHtml, whiteList, sanitizeFn) { - if (unsafeHtml.length === 0) { + function sanitizeHtml(unsafeHtml, allowList, sanitizeFn) { + if (!unsafeHtml.length) { return unsafeHtml; } @@ -5277,53 +5255,50 @@ return sanitizeFn(unsafeHtml); } - var domParser = new window.DOMParser(); - var createdDocument = domParser.parseFromString(unsafeHtml, 'text/html'); - var whitelistKeys = Object.keys(whiteList); - var elements = [].slice.call(createdDocument.body.querySelectorAll('*')); + const domParser = new window.DOMParser(); + const createdDocument = domParser.parseFromString(unsafeHtml, 'text/html'); + const allowlistKeys = Object.keys(allowList); + const elements = [].concat(...createdDocument.body.querySelectorAll('*')); - var _loop = function _loop(i, len) { - var el = elements[i]; - var elName = el.nodeName.toLowerCase(); + for (let i = 0, len = elements.length; i < len; i++) { + const el = elements[i]; + const elName = el.nodeName.toLowerCase(); - if (whitelistKeys.indexOf(el.nodeName.toLowerCase()) === -1) { - el.parentNode.removeChild(el); - return "continue"; + if (!allowlistKeys.includes(elName)) { + el.remove(); + continue; } - var attributeList = [].slice.call(el.attributes); - var whitelistedAttributes = [].concat(whiteList['*'] || [], whiteList[elName] || []); - attributeList.forEach(function (attr) { - if (!allowedAttribute(attr, whitelistedAttributes)) { + const attributeList = [].concat(...el.attributes); + const allowedAttributes = [].concat(allowList['*'] || [], allowList[elName] || []); + attributeList.forEach(attr => { + if (!allowedAttribute(attr, allowedAttributes)) { el.removeAttribute(attr.nodeName); } }); - }; - - for (var i = 0, len = elements.length; i < len; i++) { - var _ret = _loop(i, len); - - if (_ret === "continue") continue; } return createdDocument.body.innerHTML; } + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): tooltip.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ - var NAME$6 = 'tooltip'; - var VERSION$6 = '4.3.1'; - var DATA_KEY$6 = 'bs.tooltip'; - var EVENT_KEY$6 = "." + DATA_KEY$6; - var JQUERY_NO_CONFLICT$6 = $.fn[NAME$6]; - var CLASS_PREFIX = 'bs-tooltip'; - var BSCLS_PREFIX_REGEX = new RegExp("(^|\\s)" + CLASS_PREFIX + "\\S+", 'g'); - var DISALLOWED_ATTRIBUTES = ['sanitize', 'whiteList', 'sanitizeFn']; - var DefaultType$4 = { + const NAME$4 = 'tooltip'; + const DATA_KEY$4 = 'bs.tooltip'; + const EVENT_KEY$4 = `.${DATA_KEY$4}`; + const CLASS_PREFIX$1 = 'bs-tooltip'; + const DISALLOWED_ATTRIBUTES = new Set(['sanitize', 'allowList', 'sanitizeFn']); + const DefaultType$3 = { animation: 'boolean', template: 'string', title: '(string|element|function)', @@ -5332,88 +5307,79 @@ html: 'boolean', selector: '(string|boolean)', placement: '(string|function)', - offset: '(number|string|function)', + offset: '(array|string|function)', container: '(string|element|boolean)', - fallbackPlacement: '(string|array)', + fallbackPlacements: 'array', boundary: '(string|element)', + customClass: '(string|function)', sanitize: 'boolean', sanitizeFn: '(null|function)', - whiteList: 'object' + allowList: 'object', + popperConfig: '(null|object|function)' }; - var AttachmentMap$1 = { + const AttachmentMap = { AUTO: 'auto', TOP: 'top', - RIGHT: 'right', + RIGHT: isRTL() ? 'left' : 'right', BOTTOM: 'bottom', - LEFT: 'left' + LEFT: isRTL() ? 'right' : 'left' }; - var Default$4 = { + const Default$3 = { animation: true, - template: '', + template: '', trigger: 'hover focus', title: '', delay: 0, html: false, selector: false, placement: 'top', - offset: 0, + offset: [0, 0], container: false, - fallbackPlacement: 'flip', - boundary: 'scrollParent', + fallbackPlacements: ['top', 'right', 'bottom', 'left'], + boundary: 'clippingParents', + customClass: '', sanitize: true, sanitizeFn: null, - whiteList: DefaultWhitelist + allowList: DefaultAllowlist, + popperConfig: null }; - var HoverState = { - SHOW: 'show', - OUT: 'out' - }; - var Event$6 = { - HIDE: "hide" + EVENT_KEY$6, - HIDDEN: "hidden" + EVENT_KEY$6, - SHOW: "show" + EVENT_KEY$6, - SHOWN: "shown" + EVENT_KEY$6, - INSERTED: "inserted" + EVENT_KEY$6, - CLICK: "click" + EVENT_KEY$6, - FOCUSIN: "focusin" + EVENT_KEY$6, - FOCUSOUT: "focusout" + EVENT_KEY$6, - MOUSEENTER: "mouseenter" + EVENT_KEY$6, - MOUSELEAVE: "mouseleave" + EVENT_KEY$6 - }; - var ClassName$6 = { - FADE: 'fade', - SHOW: 'show' - }; - var Selector$6 = { - TOOLTIP: '.tooltip', - TOOLTIP_INNER: '.tooltip-inner', - ARROW: '.arrow' - }; - var Trigger = { - HOVER: 'hover', - FOCUS: 'focus', - CLICK: 'click', - MANUAL: 'manual' - /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ - */ - + const Event$2 = { + HIDE: `hide${EVENT_KEY$4}`, + HIDDEN: `hidden${EVENT_KEY$4}`, + SHOW: `show${EVENT_KEY$4}`, + SHOWN: `shown${EVENT_KEY$4}`, + INSERTED: `inserted${EVENT_KEY$4}`, + CLICK: `click${EVENT_KEY$4}`, + FOCUSIN: `focusin${EVENT_KEY$4}`, + FOCUSOUT: `focusout${EVENT_KEY$4}`, + MOUSEENTER: `mouseenter${EVENT_KEY$4}`, + MOUSELEAVE: `mouseleave${EVENT_KEY$4}` }; + const CLASS_NAME_FADE$2 = 'fade'; + const CLASS_NAME_MODAL = 'modal'; + const CLASS_NAME_SHOW$2 = 'show'; + const HOVER_STATE_SHOW = 'show'; + const HOVER_STATE_OUT = 'out'; + const SELECTOR_TOOLTIP_INNER = '.tooltip-inner'; + const SELECTOR_MODAL = `.${CLASS_NAME_MODAL}`; + const EVENT_MODAL_HIDE = 'hide.bs.modal'; + const TRIGGER_HOVER = 'hover'; + const TRIGGER_FOCUS = 'focus'; + const TRIGGER_CLICK = 'click'; + const TRIGGER_MANUAL = 'manual'; + /** + * ------------------------------------------------------------------------ + * Class Definition + * ------------------------------------------------------------------------ + */ - var Tooltip = - /*#__PURE__*/ - function () { - function Tooltip(element, config) { - /** - * Check for Popper dependency - * Popper - https://popper.js.org - */ + class Tooltip extends BaseComponent { + constructor(element, config) { if (typeof Popper === 'undefined') { - throw new TypeError('Bootstrap\'s tooltips require Popper.js (https://popper.js.org/)'); - } // private + throw new TypeError('Bootstrap\'s tooltips require Popper (https://popper.js.org)'); + } + super(element); // private this._isEnabled = true; this._timeout = 0; @@ -5421,42 +5387,49 @@ this._activeTrigger = {}; this._popper = null; // Protected - this.element = element; - this.config = this._getConfig(config); + this._config = this._getConfig(config); this.tip = null; this._setListeners(); } // Getters - var _proto = Tooltip.prototype; + static get Default() { + return Default$3; + } + + static get NAME() { + return NAME$4; + } + + static get Event() { + return Event$2; + } + + static get DefaultType() { + return DefaultType$3; + } // Public + - // Public - _proto.enable = function enable() { + enable() { this._isEnabled = true; - }; + } - _proto.disable = function disable() { + disable() { this._isEnabled = false; - }; + } - _proto.toggleEnabled = function toggleEnabled() { + toggleEnabled() { this._isEnabled = !this._isEnabled; - }; + } - _proto.toggle = function toggle(event) { + toggle(event) { if (!this._isEnabled) { return; } if (event) { - var dataKey = this.constructor.DATA_KEY; - var context = $(event.currentTarget).data(dataKey); - - if (!context) { - context = new this.constructor(event.currentTarget, this._getDelegateConfig()); - $(event.currentTarget).data(dataKey, context); - } + const context = this._initializeOnDelegatedTarget(event); context._activeTrigger.click = !context._activeTrigger.click; @@ -5466,7 +5439,7 @@ context._leave(null, context); } } else { - if ($(this.getTipElement()).hasClass(ClassName$6.SHOW)) { + if (this.getTipElement().classList.contains(CLASS_NAME_SHOW$2)) { this._leave(null, this); return; @@ -5474,367 +5447,400 @@ this._enter(null, this); } - }; + } - _proto.dispose = function dispose() { + dispose() { clearTimeout(this._timeout); - $.removeData(this.element, this.constructor.DATA_KEY); - $(this.element).off(this.constructor.EVENT_KEY); - $(this.element).closest('.modal').off('hide.bs.modal'); + EventHandler.off(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler); if (this.tip) { - $(this.tip).remove(); + this.tip.remove(); } - this._isEnabled = null; - this._timeout = null; - this._hoverState = null; - this._activeTrigger = null; - - if (this._popper !== null) { + if (this._popper) { this._popper.destroy(); } - this._popper = null; - this.element = null; - this.config = null; - this.tip = null; - }; - - _proto.show = function show() { - var _this = this; + super.dispose(); + } - if ($(this.element).css('display') === 'none') { + show() { + if (this._element.style.display === 'none') { throw new Error('Please use show on visible elements'); } - var showEvent = $.Event(this.constructor.Event.SHOW); + if (!(this.isWithContent() && this._isEnabled)) { + return; + } - if (this.isWithContent() && this._isEnabled) { - $(this.element).trigger(showEvent); - var shadowRoot = Util.findShadowRoot(this.element); - var isInTheDom = $.contains(shadowRoot !== null ? shadowRoot : this.element.ownerDocument.documentElement, this.element); + const showEvent = EventHandler.trigger(this._element, this.constructor.Event.SHOW); + const shadowRoot = findShadowRoot(this._element); + const isInTheDom = shadowRoot === null ? this._element.ownerDocument.documentElement.contains(this._element) : shadowRoot.contains(this._element); - if (showEvent.isDefaultPrevented() || !isInTheDom) { - return; - } + if (showEvent.defaultPrevented || !isInTheDom) { + return; + } - var tip = this.getTipElement(); - var tipId = Util.getUID(this.constructor.NAME); - tip.setAttribute('id', tipId); - this.element.setAttribute('aria-describedby', tipId); - this.setContent(); + const tip = this.getTipElement(); + const tipId = getUID(this.constructor.NAME); + tip.setAttribute('id', tipId); - if (this.config.animation) { - $(tip).addClass(ClassName$6.FADE); - } + this._element.setAttribute('aria-describedby', tipId); - var placement = typeof this.config.placement === 'function' ? this.config.placement.call(this, tip, this.element) : this.config.placement; + if (this._config.animation) { + tip.classList.add(CLASS_NAME_FADE$2); + } - var attachment = this._getAttachment(placement); + const placement = typeof this._config.placement === 'function' ? this._config.placement.call(this, tip, this._element) : this._config.placement; - this.addAttachmentClass(attachment); + const attachment = this._getAttachment(placement); - var container = this._getContainer(); + this._addAttachmentClass(attachment); - $(tip).data(this.constructor.DATA_KEY, this); + const { + container + } = this._config; + Data.set(tip, this.constructor.DATA_KEY, this); - if (!$.contains(this.element.ownerDocument.documentElement, this.tip)) { - $(tip).appendTo(container); - } + if (!this._element.ownerDocument.documentElement.contains(this.tip)) { + container.append(tip); + EventHandler.trigger(this._element, this.constructor.Event.INSERTED); + } - $(this.element).trigger(this.constructor.Event.INSERTED); - this._popper = new Popper(this.element, tip, { - placement: attachment, - modifiers: { - offset: this._getOffset(), - flip: { - behavior: this.config.fallbackPlacement - }, - arrow: { - element: Selector$6.ARROW - }, - preventOverflow: { - boundariesElement: this.config.boundary - } - }, - onCreate: function onCreate(data) { - if (data.originalPlacement !== data.placement) { - _this._handlePopperPlacementChange(data); - } - }, - onUpdate: function onUpdate(data) { - return _this._handlePopperPlacementChange(data); - } - }); - $(tip).addClass(ClassName$6.SHOW); // If this is a touch-enabled device we add extra - // empty mouseover listeners to the body's immediate children; - // only needed because of broken event delegation on iOS - // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html + if (this._popper) { + this._popper.update(); + } else { + this._popper = createPopper(this._element, tip, this._getPopperConfig(attachment)); + } - if ('ontouchstart' in document.documentElement) { - $(document.body).children().on('mouseover', null, $.noop); - } + tip.classList.add(CLASS_NAME_SHOW$2); - var complete = function complete() { - if (_this.config.animation) { - _this._fixTransition(); - } + const customClass = this._resolvePossibleFunction(this._config.customClass); + + if (customClass) { + tip.classList.add(...customClass.split(' ')); + } // If this is a touch-enabled device we add extra + // empty mouseover listeners to the body's immediate children; + // only needed because of broken event delegation on iOS + // https://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html - var prevHoverState = _this._hoverState; - _this._hoverState = null; - $(_this.element).trigger(_this.constructor.Event.SHOWN); - if (prevHoverState === HoverState.OUT) { - _this._leave(null, _this); - } - }; + if ('ontouchstart' in document.documentElement) { + [].concat(...document.body.children).forEach(element => { + EventHandler.on(element, 'mouseover', noop); + }); + } - if ($(this.tip).hasClass(ClassName$6.FADE)) { - var transitionDuration = Util.getTransitionDurationFromElement(this.tip); - $(this.tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration); - } else { - complete(); + const complete = () => { + const prevHoverState = this._hoverState; + this._hoverState = null; + EventHandler.trigger(this._element, this.constructor.Event.SHOWN); + + if (prevHoverState === HOVER_STATE_OUT) { + this._leave(null, this); } + }; + + const isAnimated = this.tip.classList.contains(CLASS_NAME_FADE$2); + + this._queueCallback(complete, this.tip, isAnimated); + } + + hide() { + if (!this._popper) { + return; } - }; - _proto.hide = function hide(callback) { - var _this2 = this; + const tip = this.getTipElement(); - var tip = this.getTipElement(); - var hideEvent = $.Event(this.constructor.Event.HIDE); + const complete = () => { + if (this._isWithActiveTrigger()) { + return; + } - var complete = function complete() { - if (_this2._hoverState !== HoverState.SHOW && tip.parentNode) { - tip.parentNode.removeChild(tip); + if (this._hoverState !== HOVER_STATE_SHOW) { + tip.remove(); } - _this2._cleanTipClass(); + this._cleanTipClass(); - _this2.element.removeAttribute('aria-describedby'); + this._element.removeAttribute('aria-describedby'); - $(_this2.element).trigger(_this2.constructor.Event.HIDDEN); + EventHandler.trigger(this._element, this.constructor.Event.HIDDEN); - if (_this2._popper !== null) { - _this2._popper.destroy(); - } + if (this._popper) { + this._popper.destroy(); - if (callback) { - callback(); + this._popper = null; } }; - $(this.element).trigger(hideEvent); + const hideEvent = EventHandler.trigger(this._element, this.constructor.Event.HIDE); - if (hideEvent.isDefaultPrevented()) { + if (hideEvent.defaultPrevented) { return; } - $(tip).removeClass(ClassName$6.SHOW); // If this is a touch-enabled device we remove the extra + tip.classList.remove(CLASS_NAME_SHOW$2); // If this is a touch-enabled device we remove the extra // empty mouseover listeners we added for iOS support if ('ontouchstart' in document.documentElement) { - $(document.body).children().off('mouseover', null, $.noop); + [].concat(...document.body.children).forEach(element => EventHandler.off(element, 'mouseover', noop)); } - this._activeTrigger[Trigger.CLICK] = false; - this._activeTrigger[Trigger.FOCUS] = false; - this._activeTrigger[Trigger.HOVER] = false; + this._activeTrigger[TRIGGER_CLICK] = false; + this._activeTrigger[TRIGGER_FOCUS] = false; + this._activeTrigger[TRIGGER_HOVER] = false; + const isAnimated = this.tip.classList.contains(CLASS_NAME_FADE$2); - if ($(this.tip).hasClass(ClassName$6.FADE)) { - var transitionDuration = Util.getTransitionDurationFromElement(tip); - $(tip).one(Util.TRANSITION_END, complete).emulateTransitionEnd(transitionDuration); - } else { - complete(); - } + this._queueCallback(complete, this.tip, isAnimated); this._hoverState = ''; - }; + } - _proto.update = function update() { + update() { if (this._popper !== null) { - this._popper.scheduleUpdate(); + this._popper.update(); } } // Protected - ; - _proto.isWithContent = function isWithContent() { + + isWithContent() { return Boolean(this.getTitle()); - }; + } - _proto.addAttachmentClass = function addAttachmentClass(attachment) { - $(this.getTipElement()).addClass(CLASS_PREFIX + "-" + attachment); - }; + getTipElement() { + if (this.tip) { + return this.tip; + } - _proto.getTipElement = function getTipElement() { - this.tip = this.tip || $(this.config.template)[0]; + const element = document.createElement('div'); + element.innerHTML = this._config.template; + const tip = element.children[0]; + this.setContent(tip); + tip.classList.remove(CLASS_NAME_FADE$2, CLASS_NAME_SHOW$2); + this.tip = tip; return this.tip; - }; + } - _proto.setContent = function setContent() { - var tip = this.getTipElement(); - this.setElementContent($(tip.querySelectorAll(Selector$6.TOOLTIP_INNER)), this.getTitle()); - $(tip).removeClass(ClassName$6.FADE + " " + ClassName$6.SHOW); - }; + setContent(tip) { + this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TOOLTIP_INNER); + } + + _sanitizeAndSetContent(template, content, selector) { + const templateElement = SelectorEngine.findOne(selector, template); + + if (!content && templateElement) { + templateElement.remove(); + return; + } // we use append for html objects to maintain js events - _proto.setElementContent = function setElementContent($element, content) { - if (typeof content === 'object' && (content.nodeType || content.jquery)) { - // Content is a DOM node or a jQuery - if (this.config.html) { - if (!$(content).parent().is($element)) { - $element.empty().append(content); + + this.setElementContent(templateElement, content); + } + + setElementContent(element, content) { + if (element === null) { + return; + } + + if (isElement$1(content)) { + content = getElement(content); // content is a DOM node or a jQuery + + if (this._config.html) { + if (content.parentNode !== element) { + element.innerHTML = ''; + element.append(content); } } else { - $element.text($(content).text()); + element.textContent = content.textContent; } return; } - if (this.config.html) { - if (this.config.sanitize) { - content = sanitizeHtml(content, this.config.whiteList, this.config.sanitizeFn); + if (this._config.html) { + if (this._config.sanitize) { + content = sanitizeHtml(content, this._config.allowList, this._config.sanitizeFn); } - $element.html(content); + element.innerHTML = content; } else { - $element.text(content); + element.textContent = content; } - }; + } + + getTitle() { + const title = this._element.getAttribute('data-bs-original-title') || this._config.title; + + return this._resolvePossibleFunction(title); + } - _proto.getTitle = function getTitle() { - var title = this.element.getAttribute('data-original-title'); + updateAttachment(attachment) { + if (attachment === 'right') { + return 'end'; + } - if (!title) { - title = typeof this.config.title === 'function' ? this.config.title.call(this.element) : this.config.title; + if (attachment === 'left') { + return 'start'; } - return title; + return attachment; } // Private - ; - _proto._getOffset = function _getOffset() { - var _this3 = this; - var offset = {}; + _initializeOnDelegatedTarget(event, context) { + return context || this.constructor.getOrCreateInstance(event.delegateTarget, this._getDelegateConfig()); + } - if (typeof this.config.offset === 'function') { - offset.fn = function (data) { - data.offsets = _objectSpread({}, data.offsets, _this3.config.offset(data.offsets, _this3.element) || {}); - return data; - }; - } else { - offset.offset = this.config.offset; + _getOffset() { + const { + offset + } = this._config; + + if (typeof offset === 'string') { + return offset.split(',').map(val => Number.parseInt(val, 10)); + } + + if (typeof offset === 'function') { + return popperData => offset(popperData, this._element); } return offset; - }; + } - _proto._getContainer = function _getContainer() { - if (this.config.container === false) { - return document.body; - } + _resolvePossibleFunction(content) { + return typeof content === 'function' ? content.call(this._element) : content; + } - if (Util.isElement(this.config.container)) { - return $(this.config.container); - } + _getPopperConfig(attachment) { + const defaultBsPopperConfig = { + placement: attachment, + modifiers: [{ + name: 'flip', + options: { + fallbackPlacements: this._config.fallbackPlacements + } + }, { + name: 'offset', + options: { + offset: this._getOffset() + } + }, { + name: 'preventOverflow', + options: { + boundary: this._config.boundary + } + }, { + name: 'arrow', + options: { + element: `.${this.constructor.NAME}-arrow` + } + }, { + name: 'onChange', + enabled: true, + phase: 'afterWrite', + fn: data => this._handlePopperPlacementChange(data) + }], + onFirstUpdate: data => { + if (data.options.placement !== data.placement) { + this._handlePopperPlacementChange(data); + } + } + }; + return { ...defaultBsPopperConfig, + ...(typeof this._config.popperConfig === 'function' ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig) + }; + } - return $(document).find(this.config.container); - }; + _addAttachmentClass(attachment) { + this.getTipElement().classList.add(`${this._getBasicClassPrefix()}-${this.updateAttachment(attachment)}`); + } - _proto._getAttachment = function _getAttachment(placement) { - return AttachmentMap$1[placement.toUpperCase()]; - }; + _getAttachment(placement) { + return AttachmentMap[placement.toUpperCase()]; + } - _proto._setListeners = function _setListeners() { - var _this4 = this; + _setListeners() { + const triggers = this._config.trigger.split(' '); - var triggers = this.config.trigger.split(' '); - triggers.forEach(function (trigger) { + triggers.forEach(trigger => { if (trigger === 'click') { - $(_this4.element).on(_this4.constructor.Event.CLICK, _this4.config.selector, function (event) { - return _this4.toggle(event); - }); - } else if (trigger !== Trigger.MANUAL) { - var eventIn = trigger === Trigger.HOVER ? _this4.constructor.Event.MOUSEENTER : _this4.constructor.Event.FOCUSIN; - var eventOut = trigger === Trigger.HOVER ? _this4.constructor.Event.MOUSELEAVE : _this4.constructor.Event.FOCUSOUT; - $(_this4.element).on(eventIn, _this4.config.selector, function (event) { - return _this4._enter(event); - }).on(eventOut, _this4.config.selector, function (event) { - return _this4._leave(event); - }); + EventHandler.on(this._element, this.constructor.Event.CLICK, this._config.selector, event => this.toggle(event)); + } else if (trigger !== TRIGGER_MANUAL) { + const eventIn = trigger === TRIGGER_HOVER ? this.constructor.Event.MOUSEENTER : this.constructor.Event.FOCUSIN; + const eventOut = trigger === TRIGGER_HOVER ? this.constructor.Event.MOUSELEAVE : this.constructor.Event.FOCUSOUT; + EventHandler.on(this._element, eventIn, this._config.selector, event => this._enter(event)); + EventHandler.on(this._element, eventOut, this._config.selector, event => this._leave(event)); } }); - $(this.element).closest('.modal').on('hide.bs.modal', function () { - if (_this4.element) { - _this4.hide(); + + this._hideModalHandler = () => { + if (this._element) { + this.hide(); } - }); + }; - if (this.config.selector) { - this.config = _objectSpread({}, this.config, { + EventHandler.on(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler); + + if (this._config.selector) { + this._config = { ...this._config, trigger: 'manual', selector: '' - }); + }; } else { this._fixTitle(); } - }; + } - _proto._fixTitle = function _fixTitle() { - var titleType = typeof this.element.getAttribute('data-original-title'); + _fixTitle() { + const title = this._element.getAttribute('title'); - if (this.element.getAttribute('title') || titleType !== 'string') { - this.element.setAttribute('data-original-title', this.element.getAttribute('title') || ''); - this.element.setAttribute('title', ''); - } - }; + const originalTitleType = typeof this._element.getAttribute('data-bs-original-title'); + + if (title || originalTitleType !== 'string') { + this._element.setAttribute('data-bs-original-title', title || ''); - _proto._enter = function _enter(event, context) { - var dataKey = this.constructor.DATA_KEY; - context = context || $(event.currentTarget).data(dataKey); + if (title && !this._element.getAttribute('aria-label') && !this._element.textContent) { + this._element.setAttribute('aria-label', title); + } - if (!context) { - context = new this.constructor(event.currentTarget, this._getDelegateConfig()); - $(event.currentTarget).data(dataKey, context); + this._element.setAttribute('title', ''); } + } + + _enter(event, context) { + context = this._initializeOnDelegatedTarget(event, context); if (event) { - context._activeTrigger[event.type === 'focusin' ? Trigger.FOCUS : Trigger.HOVER] = true; + context._activeTrigger[event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER] = true; } - if ($(context.getTipElement()).hasClass(ClassName$6.SHOW) || context._hoverState === HoverState.SHOW) { - context._hoverState = HoverState.SHOW; + if (context.getTipElement().classList.contains(CLASS_NAME_SHOW$2) || context._hoverState === HOVER_STATE_SHOW) { + context._hoverState = HOVER_STATE_SHOW; return; } clearTimeout(context._timeout); - context._hoverState = HoverState.SHOW; + context._hoverState = HOVER_STATE_SHOW; - if (!context.config.delay || !context.config.delay.show) { + if (!context._config.delay || !context._config.delay.show) { context.show(); return; } - context._timeout = setTimeout(function () { - if (context._hoverState === HoverState.SHOW) { + context._timeout = setTimeout(() => { + if (context._hoverState === HOVER_STATE_SHOW) { context.show(); } - }, context.config.delay.show); - }; - - _proto._leave = function _leave(event, context) { - var dataKey = this.constructor.DATA_KEY; - context = context || $(event.currentTarget).data(dataKey); + }, context._config.delay.show); + } - if (!context) { - context = new this.constructor(event.currentTarget, this._getDelegateConfig()); - $(event.currentTarget).data(dataKey, context); - } + _leave(event, context) { + context = this._initializeOnDelegatedTarget(event, context); if (event) { - context._activeTrigger[event.type === 'focusout' ? Trigger.FOCUS : Trigger.HOVER] = false; + context._activeTrigger[event.type === 'focusout' ? TRIGGER_FOCUS : TRIGGER_HOVER] = context._element.contains(event.relatedTarget); } if (context._isWithActiveTrigger()) { @@ -5842,38 +5848,42 @@ } clearTimeout(context._timeout); - context._hoverState = HoverState.OUT; + context._hoverState = HOVER_STATE_OUT; - if (!context.config.delay || !context.config.delay.hide) { + if (!context._config.delay || !context._config.delay.hide) { context.hide(); return; } - context._timeout = setTimeout(function () { - if (context._hoverState === HoverState.OUT) { + context._timeout = setTimeout(() => { + if (context._hoverState === HOVER_STATE_OUT) { context.hide(); } - }, context.config.delay.hide); - }; + }, context._config.delay.hide); + } - _proto._isWithActiveTrigger = function _isWithActiveTrigger() { - for (var trigger in this._activeTrigger) { + _isWithActiveTrigger() { + for (const trigger in this._activeTrigger) { if (this._activeTrigger[trigger]) { return true; } } return false; - }; + } - _proto._getConfig = function _getConfig(config) { - var dataAttributes = $(this.element).data(); - Object.keys(dataAttributes).forEach(function (dataAttr) { - if (DISALLOWED_ATTRIBUTES.indexOf(dataAttr) !== -1) { + _getConfig(config) { + const dataAttributes = Manipulator.getDataAttributes(this._element); + Object.keys(dataAttributes).forEach(dataAttr => { + if (DISALLOWED_ATTRIBUTES.has(dataAttr)) { delete dataAttributes[dataAttr]; } }); - config = _objectSpread({}, this.constructor.Default, dataAttributes, typeof config === 'object' && config ? config : {}); + config = { ...this.constructor.Default, + ...dataAttributes, + ...(typeof config === 'object' && config ? config : {}) + }; + config.container = config.container === false ? document.body : getElement(config.container); if (typeof config.delay === 'number') { config.delay = { @@ -5890,505 +5900,337 @@ config.content = config.content.toString(); } - Util.typeCheckConfig(NAME$6, config, this.constructor.DefaultType); + typeCheckConfig(NAME$4, config, this.constructor.DefaultType); if (config.sanitize) { - config.template = sanitizeHtml(config.template, config.whiteList, config.sanitizeFn); + config.template = sanitizeHtml(config.template, config.allowList, config.sanitizeFn); } return config; - }; + } - _proto._getDelegateConfig = function _getDelegateConfig() { - var config = {}; + _getDelegateConfig() { + const config = {}; - if (this.config) { - for (var key in this.config) { - if (this.constructor.Default[key] !== this.config[key]) { - config[key] = this.config[key]; - } + for (const key in this._config) { + if (this.constructor.Default[key] !== this._config[key]) { + config[key] = this._config[key]; } - } + } // In the future can be replaced with: + // const keysWithDifferentValues = Object.entries(this._config).filter(entry => this.constructor.Default[entry[0]] !== this._config[entry[0]]) + // `Object.fromEntries(keysWithDifferentValues)` + return config; - }; + } - _proto._cleanTipClass = function _cleanTipClass() { - var $tip = $(this.getTipElement()); - var tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX); + _cleanTipClass() { + const tip = this.getTipElement(); + const basicClassPrefixRegex = new RegExp(`(^|\\s)${this._getBasicClassPrefix()}\\S+`, 'g'); + const tabClass = tip.getAttribute('class').match(basicClassPrefixRegex); - if (tabClass !== null && tabClass.length) { - $tip.removeClass(tabClass.join('')); + if (tabClass !== null && tabClass.length > 0) { + tabClass.map(token => token.trim()).forEach(tClass => tip.classList.remove(tClass)); } - }; - - _proto._handlePopperPlacementChange = function _handlePopperPlacementChange(popperData) { - var popperInstance = popperData.instance; - this.tip = popperInstance.popper; - - this._cleanTipClass(); + } - this.addAttachmentClass(this._getAttachment(popperData.placement)); - }; + _getBasicClassPrefix() { + return CLASS_PREFIX$1; + } - _proto._fixTransition = function _fixTransition() { - var tip = this.getTipElement(); - var initConfigAnimation = this.config.animation; + _handlePopperPlacementChange(popperData) { + const { + state + } = popperData; - if (tip.getAttribute('x-placement') !== null) { + if (!state) { return; } - $(tip).removeClass(ClassName$6.FADE); - this.config.animation = false; - this.hide(); - this.show(); - this.config.animation = initConfigAnimation; - } // Static - ; + this.tip = state.elements.popper; - Tooltip._jQueryInterface = function _jQueryInterface(config) { - return this.each(function () { - var data = $(this).data(DATA_KEY$6); + this._cleanTipClass(); - var _config = typeof config === 'object' && config; + this._addAttachmentClass(this._getAttachment(state.placement)); + } // Static - if (!data && /dispose|hide/.test(config)) { - return; - } - if (!data) { - data = new Tooltip(this, _config); - $(this).data(DATA_KEY$6, data); - } + static jQueryInterface(config) { + return this.each(function () { + const data = Tooltip.getOrCreateInstance(this, config); if (typeof config === 'string') { if (typeof data[config] === 'undefined') { - throw new TypeError("No method named \"" + config + "\""); + throw new TypeError(`No method named "${config}"`); } data[config](); } }); - }; + } - _createClass(Tooltip, null, [{ - key: "VERSION", - get: function get() { - return VERSION$6; - } - }, { - key: "Default", - get: function get() { - return Default$4; - } - }, { - key: "NAME", - get: function get() { - return NAME$6; - } - }, { - key: "DATA_KEY", - get: function get() { - return DATA_KEY$6; - } - }, { - key: "Event", - get: function get() { - return Event$6; - } - }, { - key: "EVENT_KEY", - get: function get() { - return EVENT_KEY$6; - } - }, { - key: "DefaultType", - get: function get() { - return DefaultType$4; - } - }]); - - return Tooltip; - }(); + } /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ + * add .Tooltip to jQuery only if jQuery is present */ - $.fn[NAME$6] = Tooltip._jQueryInterface; - $.fn[NAME$6].Constructor = Tooltip; - - $.fn[NAME$6].noConflict = function () { - $.fn[NAME$6] = JQUERY_NO_CONFLICT$6; - return Tooltip._jQueryInterface; - }; + defineJQueryPlugin(Tooltip); + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): popover.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ - */ - - var NAME$7 = 'popover'; - var VERSION$7 = '4.3.1'; - var DATA_KEY$7 = 'bs.popover'; - var EVENT_KEY$7 = "." + DATA_KEY$7; - var JQUERY_NO_CONFLICT$7 = $.fn[NAME$7]; - var CLASS_PREFIX$1 = 'bs-popover'; - var BSCLS_PREFIX_REGEX$1 = new RegExp("(^|\\s)" + CLASS_PREFIX$1 + "\\S+", 'g'); - - var Default$5 = _objectSpread({}, Tooltip.Default, { - placement: 'right', - trigger: 'click', - content: '', - template: '' - }); - - var DefaultType$5 = _objectSpread({}, Tooltip.DefaultType, { - content: '(string|element|function)' - }); + */ - var ClassName$7 = { - FADE: 'fade', - SHOW: 'show' + const NAME$3 = 'popover'; + const DATA_KEY$3 = 'bs.popover'; + const EVENT_KEY$3 = `.${DATA_KEY$3}`; + const CLASS_PREFIX = 'bs-popover'; + const Default$2 = { ...Tooltip.Default, + placement: 'right', + offset: [0, 8], + trigger: 'click', + content: '', + template: '' }; - var Selector$7 = { - TITLE: '.popover-header', - CONTENT: '.popover-body' + const DefaultType$2 = { ...Tooltip.DefaultType, + content: '(string|element|function)' }; - var Event$7 = { - HIDE: "hide" + EVENT_KEY$7, - HIDDEN: "hidden" + EVENT_KEY$7, - SHOW: "show" + EVENT_KEY$7, - SHOWN: "shown" + EVENT_KEY$7, - INSERTED: "inserted" + EVENT_KEY$7, - CLICK: "click" + EVENT_KEY$7, - FOCUSIN: "focusin" + EVENT_KEY$7, - FOCUSOUT: "focusout" + EVENT_KEY$7, - MOUSEENTER: "mouseenter" + EVENT_KEY$7, - MOUSELEAVE: "mouseleave" + EVENT_KEY$7 - /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ - */ - + const Event$1 = { + HIDE: `hide${EVENT_KEY$3}`, + HIDDEN: `hidden${EVENT_KEY$3}`, + SHOW: `show${EVENT_KEY$3}`, + SHOWN: `shown${EVENT_KEY$3}`, + INSERTED: `inserted${EVENT_KEY$3}`, + CLICK: `click${EVENT_KEY$3}`, + FOCUSIN: `focusin${EVENT_KEY$3}`, + FOCUSOUT: `focusout${EVENT_KEY$3}`, + MOUSEENTER: `mouseenter${EVENT_KEY$3}`, + MOUSELEAVE: `mouseleave${EVENT_KEY$3}` }; + const SELECTOR_TITLE = '.popover-header'; + const SELECTOR_CONTENT = '.popover-body'; + /** + * ------------------------------------------------------------------------ + * Class Definition + * ------------------------------------------------------------------------ + */ - var Popover = - /*#__PURE__*/ - function (_Tooltip) { - _inheritsLoose(Popover, _Tooltip); - - function Popover() { - return _Tooltip.apply(this, arguments) || this; + class Popover extends Tooltip { + // Getters + static get Default() { + return Default$2; } - var _proto = Popover.prototype; - - // Overrides - _proto.isWithContent = function isWithContent() { - return this.getTitle() || this._getContent(); - }; - - _proto.addAttachmentClass = function addAttachmentClass(attachment) { - $(this.getTipElement()).addClass(CLASS_PREFIX$1 + "-" + attachment); - }; + static get NAME() { + return NAME$3; + } - _proto.getTipElement = function getTipElement() { - this.tip = this.tip || $(this.config.template)[0]; - return this.tip; - }; + static get Event() { + return Event$1; + } - _proto.setContent = function setContent() { - var $tip = $(this.getTipElement()); // We use append for html objects to maintain js events + static get DefaultType() { + return DefaultType$2; + } // Overrides - this.setElementContent($tip.find(Selector$7.TITLE), this.getTitle()); - var content = this._getContent(); + isWithContent() { + return this.getTitle() || this._getContent(); + } - if (typeof content === 'function') { - content = content.call(this.element); - } + setContent(tip) { + this._sanitizeAndSetContent(tip, this.getTitle(), SELECTOR_TITLE); - this.setElementContent($tip.find(Selector$7.CONTENT), content); - $tip.removeClass(ClassName$7.FADE + " " + ClassName$7.SHOW); + this._sanitizeAndSetContent(tip, this._getContent(), SELECTOR_CONTENT); } // Private - ; - _proto._getContent = function _getContent() { - return this.element.getAttribute('data-content') || this.config.content; - }; - _proto._cleanTipClass = function _cleanTipClass() { - var $tip = $(this.getTipElement()); - var tabClass = $tip.attr('class').match(BSCLS_PREFIX_REGEX$1); + _getContent() { + return this._resolvePossibleFunction(this._config.content); + } - if (tabClass !== null && tabClass.length > 0) { - $tip.removeClass(tabClass.join('')); - } + _getBasicClassPrefix() { + return CLASS_PREFIX; } // Static - ; - - Popover._jQueryInterface = function _jQueryInterface(config) { - return this.each(function () { - var data = $(this).data(DATA_KEY$7); - - var _config = typeof config === 'object' ? config : null; - if (!data && /dispose|hide/.test(config)) { - return; - } - if (!data) { - data = new Popover(this, _config); - $(this).data(DATA_KEY$7, data); - } + static jQueryInterface(config) { + return this.each(function () { + const data = Popover.getOrCreateInstance(this, config); if (typeof config === 'string') { if (typeof data[config] === 'undefined') { - throw new TypeError("No method named \"" + config + "\""); + throw new TypeError(`No method named "${config}"`); } data[config](); } }); - }; + } - _createClass(Popover, null, [{ - key: "VERSION", - // Getters - get: function get() { - return VERSION$7; - } - }, { - key: "Default", - get: function get() { - return Default$5; - } - }, { - key: "NAME", - get: function get() { - return NAME$7; - } - }, { - key: "DATA_KEY", - get: function get() { - return DATA_KEY$7; - } - }, { - key: "Event", - get: function get() { - return Event$7; - } - }, { - key: "EVENT_KEY", - get: function get() { - return EVENT_KEY$7; - } - }, { - key: "DefaultType", - get: function get() { - return DefaultType$5; - } - }]); - - return Popover; - }(Tooltip); + } /** * ------------------------------------------------------------------------ * jQuery * ------------------------------------------------------------------------ + * add .Popover to jQuery only if jQuery is present */ - $.fn[NAME$7] = Popover._jQueryInterface; - $.fn[NAME$7].Constructor = Popover; - - $.fn[NAME$7].noConflict = function () { - $.fn[NAME$7] = JQUERY_NO_CONFLICT$7; - return Popover._jQueryInterface; - }; + defineJQueryPlugin(Popover); + /** + * -------------------------------------------------------------------------- + * Bootstrap (v5.1.0): scrollspy.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ /** * ------------------------------------------------------------------------ * Constants * ------------------------------------------------------------------------ */ - var NAME$8 = 'scrollspy'; - var VERSION$8 = '4.3.1'; - var DATA_KEY$8 = 'bs.scrollspy'; - var EVENT_KEY$8 = "." + DATA_KEY$8; - var DATA_API_KEY$6 = '.data-api'; - var JQUERY_NO_CONFLICT$8 = $.fn[NAME$8]; - var Default$6 = { + const NAME$2 = 'scrollspy'; + const DATA_KEY$2 = 'bs.scrollspy'; + const EVENT_KEY$2 = `.${DATA_KEY$2}`; + const DATA_API_KEY$1 = '.data-api'; + const Default$1 = { offset: 10, method: 'auto', target: '' }; - var DefaultType$6 = { + const DefaultType$1 = { offset: 'number', method: 'string', target: '(string|element)' }; - var Event$8 = { - ACTIVATE: "activate" + EVENT_KEY$8, - SCROLL: "scroll" + EVENT_KEY$8, - LOAD_DATA_API: "load" + EVENT_KEY$8 + DATA_API_KEY$6 - }; - var ClassName$8 = { - DROPDOWN_ITEM: 'dropdown-item', - DROPDOWN_MENU: 'dropdown-menu', - ACTIVE: 'active' - }; - var Selector$8 = { - DATA_SPY: '[data-spy="scroll"]', - ACTIVE: '.active', - NAV_LIST_GROUP: '.nav, .list-group', - NAV_LINKS: '.nav-link', - NAV_ITEMS: '.nav-item', - LIST_ITEMS: '.list-group-item', - DROPDOWN: '.dropdown', - DROPDOWN_ITEMS: '.dropdown-item', - DROPDOWN_TOGGLE: '.dropdown-toggle' - }; - var OffsetMethod = { - OFFSET: 'offset', - POSITION: 'position' - /** - * ------------------------------------------------------------------------ - * Class Definition - * ------------------------------------------------------------------------ - */ - - }; - - var ScrollSpy = - /*#__PURE__*/ - function () { - function ScrollSpy(element, config) { - var _this = this; + const EVENT_ACTIVATE = `activate${EVENT_KEY$2}`; + const EVENT_SCROLL = `scroll${EVENT_KEY$2}`; + const EVENT_LOAD_DATA_API = `load${EVENT_KEY$2}${DATA_API_KEY$1}`; + const CLASS_NAME_DROPDOWN_ITEM = 'dropdown-item'; + const CLASS_NAME_ACTIVE$1 = 'active'; + const SELECTOR_DATA_SPY = '[data-bs-spy="scroll"]'; + const SELECTOR_NAV_LIST_GROUP$1 = '.nav, .list-group'; + const SELECTOR_NAV_LINKS = '.nav-link'; + const SELECTOR_NAV_ITEMS = '.nav-item'; + const SELECTOR_LIST_ITEMS = '.list-group-item'; + const SELECTOR_LINK_ITEMS = `${SELECTOR_NAV_LINKS}, ${SELECTOR_LIST_ITEMS}, .${CLASS_NAME_DROPDOWN_ITEM}`; + const SELECTOR_DROPDOWN$1 = '.dropdown'; + const SELECTOR_DROPDOWN_TOGGLE$1 = '.dropdown-toggle'; + const METHOD_OFFSET = 'offset'; + const METHOD_POSITION = 'position'; + /** + * ------------------------------------------------------------------------ + * Class Definition + * ------------------------------------------------------------------------ + */ - this._element = element; - this._scrollElement = element.tagName === 'BODY' ? window : element; + class ScrollSpy extends BaseComponent { + constructor(element, config) { + super(element); + this._scrollElement = this._element.tagName === 'BODY' ? window : this._element; this._config = this._getConfig(config); - this._selector = this._config.target + " " + Selector$8.NAV_LINKS + "," + (this._config.target + " " + Selector$8.LIST_ITEMS + ",") + (this._config.target + " " + Selector$8.DROPDOWN_ITEMS); this._offsets = []; this._targets = []; this._activeTarget = null; this._scrollHeight = 0; - $(this._scrollElement).on(Event$8.SCROLL, function (event) { - return _this._process(event); - }); + EventHandler.on(this._scrollElement, EVENT_SCROLL, () => this._process()); this.refresh(); this._process(); } // Getters - var _proto = ScrollSpy.prototype; + static get Default() { + return Default$1; + } + + static get NAME() { + return NAME$2; + } // Public - // Public - _proto.refresh = function refresh() { - var _this2 = this; - var autoMethod = this._scrollElement === this._scrollElement.window ? OffsetMethod.OFFSET : OffsetMethod.POSITION; - var offsetMethod = this._config.method === 'auto' ? autoMethod : this._config.method; - var offsetBase = offsetMethod === OffsetMethod.POSITION ? this._getScrollTop() : 0; + refresh() { + const autoMethod = this._scrollElement === this._scrollElement.window ? METHOD_OFFSET : METHOD_POSITION; + const offsetMethod = this._config.method === 'auto' ? autoMethod : this._config.method; + const offsetBase = offsetMethod === METHOD_POSITION ? this._getScrollTop() : 0; this._offsets = []; this._targets = []; this._scrollHeight = this._getScrollHeight(); - var targets = [].slice.call(document.querySelectorAll(this._selector)); - targets.map(function (element) { - var target; - var targetSelector = Util.getSelectorFromElement(element); - - if (targetSelector) { - target = document.querySelector(targetSelector); - } + const targets = SelectorEngine.find(SELECTOR_LINK_ITEMS, this._config.target); + targets.map(element => { + const targetSelector = getSelectorFromElement(element); + const target = targetSelector ? SelectorEngine.findOne(targetSelector) : null; if (target) { - var targetBCR = target.getBoundingClientRect(); + const targetBCR = target.getBoundingClientRect(); if (targetBCR.width || targetBCR.height) { - // TODO (fat): remove sketch reliance on jQuery position/offset - return [$(target)[offsetMethod]().top + offsetBase, targetSelector]; + return [Manipulator[offsetMethod](target).top + offsetBase, targetSelector]; } } return null; - }).filter(function (item) { - return item; - }).sort(function (a, b) { - return a[0] - b[0]; - }).forEach(function (item) { - _this2._offsets.push(item[0]); - - _this2._targets.push(item[1]); + }).filter(item => item).sort((a, b) => a[0] - b[0]).forEach(item => { + this._offsets.push(item[0]); + + this._targets.push(item[1]); }); - }; + } - _proto.dispose = function dispose() { - $.removeData(this._element, DATA_KEY$8); - $(this._scrollElement).off(EVENT_KEY$8); - this._element = null; - this._scrollElement = null; - this._config = null; - this._selector = null; - this._offsets = null; - this._targets = null; - this._activeTarget = null; - this._scrollHeight = null; + dispose() { + EventHandler.off(this._scrollElement, EVENT_KEY$2); + super.dispose(); } // Private - ; - _proto._getConfig = function _getConfig(config) { - config = _objectSpread({}, Default$6, typeof config === 'object' && config ? config : {}); - if (typeof config.target !== 'string') { - var id = $(config.target).attr('id'); - - if (!id) { - id = Util.getUID(NAME$8); - $(config.target).attr('id', id); - } - - config.target = "#" + id; - } - - Util.typeCheckConfig(NAME$8, config, DefaultType$6); + _getConfig(config) { + config = { ...Default$1, + ...Manipulator.getDataAttributes(this._element), + ...(typeof config === 'object' && config ? config : {}) + }; + config.target = getElement(config.target) || document.documentElement; + typeCheckConfig(NAME$2, config, DefaultType$1); return config; - }; + } - _proto._getScrollTop = function _getScrollTop() { + _getScrollTop() { return this._scrollElement === window ? this._scrollElement.pageYOffset : this._scrollElement.scrollTop; - }; + } - _proto._getScrollHeight = function _getScrollHeight() { + _getScrollHeight() { return this._scrollElement.scrollHeight || Math.max(document.body.scrollHeight, document.documentElement.scrollHeight); - }; + } - _proto._getOffsetHeight = function _getOffsetHeight() { + _getOffsetHeight() { return this._scrollElement === window ? window.innerHeight : this._scrollElement.getBoundingClientRect().height; - }; + } - _proto._process = function _process() { - var scrollTop = this._getScrollTop() + this._config.offset; + _process() { + const scrollTop = this._getScrollTop() + this._config.offset; - var scrollHeight = this._getScrollHeight(); + const scrollHeight = this._getScrollHeight(); - var maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight(); + const maxScroll = this._config.offset + scrollHeight - this._getOffsetHeight(); if (this._scrollHeight !== scrollHeight) { this.refresh(); } if (scrollTop >= maxScroll) { - var target = this._targets[this._targets.length - 1]; + const target = this._targets[this._targets.length - 1]; if (this._activeTarget !== target) { this._activate(target); @@ -6405,90 +6247,65 @@ return; } - var offsetLength = this._offsets.length; - - for (var i = offsetLength; i--;) { - var isActiveTarget = this._activeTarget !== this._targets[i] && scrollTop >= this._offsets[i] && (typeof this._offsets[i + 1] === 'undefined' || scrollTop < this._offsets[i + 1]); + for (let i = this._offsets.length; i--;) { + const isActiveTarget = this._activeTarget !== this._targets[i] && scrollTop >= this._offsets[i] && (typeof this._offsets[i + 1] === 'undefined' || scrollTop < this._offsets[i + 1]); if (isActiveTarget) { this._activate(this._targets[i]); } } - }; + } - _proto._activate = function _activate(target) { + _activate(target) { this._activeTarget = target; this._clear(); - var queries = this._selector.split(',').map(function (selector) { - return selector + "[data-target=\"" + target + "\"]," + selector + "[href=\"" + target + "\"]"; - }); - - var $link = $([].slice.call(document.querySelectorAll(queries.join(',')))); + const queries = SELECTOR_LINK_ITEMS.split(',').map(selector => `${selector}[data-bs-target="${target}"],${selector}[href="${target}"]`); + const link = SelectorEngine.findOne(queries.join(','), this._config.target); + link.classList.add(CLASS_NAME_ACTIVE$1); - if ($link.hasClass(ClassName$8.DROPDOWN_ITEM)) { - $link.closest(Selector$8.DROPDOWN).find(Selector$8.DROPDOWN_TOGGLE).addClass(ClassName$8.ACTIVE); - $link.addClass(ClassName$8.ACTIVE); + if (link.classList.contains(CLASS_NAME_DROPDOWN_ITEM)) { + SelectorEngine.findOne(SELECTOR_DROPDOWN_TOGGLE$1, link.closest(SELECTOR_DROPDOWN$1)).classList.add(CLASS_NAME_ACTIVE$1); } else { - // Set triggered link as active - $link.addClass(ClassName$8.ACTIVE); // Set triggered links parents as active - // With both