diff --git a/.editorconfig b/.editorconfig index 7d87f5a..5465255 100644 --- a/.editorconfig +++ b/.editorconfig @@ -38,17 +38,71 @@ dotnet_diagnostic.CS8524.severity = none # IDE0044: Add readonly modifier dotnet_diagnostic.IDE0044.severity = silent -# IDE0090: Use new(...) syntax -dotnet_diagnostic.IDE0090.severity = silent - # actual nice code formatting rules (Allman style) [*.cs] csharp_new_line_before_open_brace = all indent_size = 4 +csharp_indent_labels = one_less_than_current +csharp_using_directive_placement = outside_namespace:suggestion +csharp_prefer_simple_using_statement = true:suggestion +csharp_prefer_braces = true:silent +csharp_style_namespace_declarations = file_scoped:warning +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_top_level_statements = true:silent +csharp_style_prefer_primary_constructors = true:suggestion +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_lambdas = true:silent +csharp_style_expression_bodied_local_functions = false:silent +csharp_style_throw_expression = true:suggestion +csharp_style_prefer_null_check_over_type_check = true:suggestion +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_prefer_local_over_anonymous_function = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion +csharp_style_prefer_tuple_swap = true:suggestion +csharp_style_prefer_utf8_string_literals = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion # book formatting rules (K&R) to save space +# SYSLIB1045: Convert to 'GeneratedRegexAttribute'. +dotnet_diagnostic.SYSLIB1045.severity = silent + +# CA1822: Mark members as static +dotnet_diagnostic.CA1822.severity = silent + [*.csxx] csharp_new_line_before_open_brace = none indent_size = 2 + +[*.{cs,vb}] +dotnet_style_operator_placement_when_wrapping = beginning_of_line +tab_width = 4 +indent_size = 4 +end_of_line = crlf +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_auto_properties = true:error +dotnet_style_object_initializer = true:suggestion +dotnet_style_prefer_collection_expression = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:silent +dotnet_style_prefer_conditional_expression_over_return = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion +dotnet_style_namespace_match_folder = true:suggestion + +# IDE0045: Convert to conditional expression +dotnet_diagnostic.IDE0045.severity = silent diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..013007b --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "dotnet.preferCSharpExtension": true +} \ No newline at end of file diff --git a/CH02/Algorithms/Algorithms.csproj b/CH02/Algorithms/Algorithms.csproj index dbc1517..61718a1 100644 --- a/CH02/Algorithms/Algorithms.csproj +++ b/CH02/Algorithms/Algorithms.csproj @@ -1,7 +1,3 @@ - - net6.0 - - diff --git a/CH02/Algorithms/Structs.cs b/CH02/Algorithms/Structs.cs index bd22e4c..fca71f5 100644 --- a/CH02/Algorithms/Structs.cs +++ b/CH02/Algorithms/Structs.cs @@ -9,7 +9,7 @@ private struct Point public int X; public int Y; - public override string ToString() => $"X:{X},Y:{Y}"; + public override readonly string? ToString() => $"X:{X},Y:{Y}"; } public static void Main() diff --git a/CH02/Arrays/Arrays.cs b/CH02/Arrays/Arrays.cs index 5621c88..152ef83 100644 --- a/CH02/Arrays/Arrays.cs +++ b/CH02/Arrays/Arrays.cs @@ -4,11 +4,13 @@ namespace Arrays; public class Arrays { + private static readonly int[] values = [1, 2, 3, 4]; + public static int ArrayVsList() { - var a = new int[] { 1, 2, 3, 4 }; + var a = values; int sum1 = a[0] + a[1] + a[2] + a[3]; - var b = new List(new int[] { 1, 2, 3, 4 }); + var b = new List(values); int sum2 = b[0] + b[1] + b[2] + b[2]; return sum1 + sum2; } diff --git a/CH02/Arrays/Arrays.csproj b/CH02/Arrays/Arrays.csproj index 56293bc..778fafb 100644 --- a/CH02/Arrays/Arrays.csproj +++ b/CH02/Arrays/Arrays.csproj @@ -1,6 +1,5 @@  - net6.0 Exe diff --git a/CH02/HashCode/HashCode.csproj b/CH02/HashCode/HashCode.csproj index 4b9482e..f60575d 100644 --- a/CH02/HashCode/HashCode.csproj +++ b/CH02/HashCode/HashCode.csproj @@ -1,11 +1,10 @@  - - net6.0 - Library - false - - - - - + + Library + false + + + + + \ No newline at end of file diff --git a/CH02/HashCode/HashCodeTest.cs b/CH02/HashCode/HashCodeTest.cs index 1a78b3e..a0efcdf 100644 --- a/CH02/HashCode/HashCodeTest.cs +++ b/CH02/HashCode/HashCodeTest.cs @@ -2,7 +2,7 @@ { public int Halue { get; set; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is HashCodeTest test && Halue == test.Halue; diff --git a/CH02/HashCode/ProperGetHashCode.cs b/CH02/HashCode/ProperGetHashCode.cs index c986ba2..bfda784 100644 --- a/CH02/HashCode/ProperGetHashCode.cs +++ b/CH02/HashCode/ProperGetHashCode.cs @@ -6,7 +6,7 @@ public override int GetHashCode() { return (int)(((TopicId & 0xFFFF) << 16) - ^ (TopicId & 0xFFFF0000 >> 16) + ^ (TopicId & (0xFFFF0000 >> 16)) ^ EntryId); } } \ No newline at end of file diff --git a/CH02/Nullability/DbId.cs b/CH02/Nullability/DbId.cs index dbe29c6..e2e023a 100644 --- a/CH02/Nullability/DbId.cs +++ b/CH02/Nullability/DbId.cs @@ -6,21 +6,18 @@ public class DbId : IEquatable public DbId(int id) { - if (id <= 0) - { - throw new ArgumentOutOfRangeException(nameof(id)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(id); Value = id; } public override string ToString() => Value.ToString(); - public override bool Equals(object obj) + public override bool Equals(object? obj) { return Equals(obj as DbId); } - public bool Equals(DbId other) => other?.Value == Value; + public bool Equals(DbId? other) => other?.Value == Value; public override int GetHashCode() { @@ -38,23 +35,14 @@ public override int GetHashCode() } } -public class EntryId : DbId +public class EntryId(int id) : DbId(id) { - public EntryId(int id) : base(id) - { - } } -public class TopicId : DbId +public class TopicId(int id) : DbId(id) { - public TopicId(int id) : base(id) - { - } } -public class UserId : DbId +public class UserId(int id) : DbId(id) { - public UserId(int id) : base(id) - { - } } \ No newline at end of file diff --git a/CH02/Nullability/Nullability.csproj b/CH02/Nullability/Nullability.csproj index 007f9ef..b1b8374 100644 --- a/CH02/Nullability/Nullability.csproj +++ b/CH02/Nullability/Nullability.csproj @@ -1,9 +1,5 @@  - - net6.0 - - diff --git a/CH02/Nullability/Person.cs b/CH02/Nullability/Person.cs index be74d45..53f2953 100644 --- a/CH02/Nullability/Person.cs +++ b/CH02/Nullability/Person.cs @@ -15,28 +15,19 @@ internal class ConferenceRegistration #pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. -internal class ConferenceRegistration2 +internal class ConferenceRegistration2( + string firstName, + string? middleName, + string lastName, + string email, + string campaignSource = "organic") { - public string CampaignSource { get; private set; } - public string FirstName { get; private set; } - public string? MiddleName { get; private set; } - public string LastName { get; private set; } - public string Email { get; private set; } - public DateTimeOffset CreatedOn { get; private set; } = DateTime.Now; - - public ConferenceRegistration2( - string firstName, - string? middleName, - string lastName, - string email, - string? campaignSource = null) - { - FirstName = firstName; - MiddleName = middleName; - LastName = lastName; - Email = email; - CampaignSource = campaignSource ?? "organic"; - } + public string CampaignSource { get; } = campaignSource; + public string FirstName { get; } = firstName; + public string? MiddleName { get; } = middleName; + public string LastName { get; } = lastName; + public string Email { get; } = email; + public DateTimeOffset CreatedOn { get; } = DateTime.Now; } internal class ConferenceRegistration3 diff --git a/CH02/Nullability/TopicService.cs b/CH02/Nullability/TopicService.cs index 137e95e..eb0fbe6 100644 --- a/CH02/Nullability/TopicService.cs +++ b/CH02/Nullability/TopicService.cs @@ -12,21 +12,12 @@ public interface IUser bool Authorized(string role); } -public class TopicService +public class TopicService(IDatabase db, IUser user) { - private IDatabase db; - private IUser user; - public MoveResult MoveContents(TopicId from, TopicId to) { - if (from is null) - { - throw new ArgumentNullException(nameof(from)); - } - if (to is null) - { - throw new ArgumentNullException(nameof(to)); - } + ArgumentNullException.ThrowIfNull(from); + ArgumentNullException.ThrowIfNull(to); if (!user.Authorized("move_contents")) { return MoveResult.Unauthorized; diff --git a/CH02/ReferenceVsValueTypes/ReferenceVsValueTypes.csproj b/CH02/ReferenceVsValueTypes/ReferenceVsValueTypes.csproj index 7495460..6a70a1a 100644 --- a/CH02/ReferenceVsValueTypes/ReferenceVsValueTypes.csproj +++ b/CH02/ReferenceVsValueTypes/ReferenceVsValueTypes.csproj @@ -2,7 +2,6 @@ Exe - net6.0 diff --git a/CH02/Strings/Locales.cs b/CH02/Strings/Locales.cs index 8ed71f6..27638f7 100644 --- a/CH02/Strings/Locales.cs +++ b/CH02/Strings/Locales.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; class Locales { @@ -8,6 +6,7 @@ public bool isGif(string fileName) { return fileName.ToLower().EndsWith(".gif"); } + public bool isGifFast(string fileName) { return fileName.EndsWith(".gif", StringComparison.OrdinalIgnoreCase); diff --git a/CH02/Strings/Strings.csproj b/CH02/Strings/Strings.csproj index fff7812..c632161 100644 --- a/CH02/Strings/Strings.csproj +++ b/CH02/Strings/Strings.csproj @@ -1,7 +1,3 @@  - - net6.0 - - diff --git a/CH02/Supercalifragilisticexpialidocious/Program.cs b/CH02/Supercalifragilisticexpialidocious/Program.cs index 52855f4..58ac075 100644 --- a/CH02/Supercalifragilisticexpialidocious/Program.cs +++ b/CH02/Supercalifragilisticexpialidocious/Program.cs @@ -14,7 +14,7 @@ public static void Main() } // URL format is https://supercalifragilisticexpialidocious.io/ - public string GetShortCodeStr(string url) + public string? GetShortCodeStr(string url) { const string urlValidationPattern = @"^https?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$"; if (!Regex.IsMatch(url, urlValidationPattern)) @@ -28,7 +28,7 @@ public string GetShortCodeStr(string url) } // URL format is https://supercalifragilisticexpialidocious.io/ - public string GetShortCodeUri(Uri url) + public string? GetShortCodeUri(Uri url) { string path = url.AbsolutePath; if (path.Contains('/')) @@ -38,9 +38,9 @@ public string GetShortCodeUri(Uri url) return path; } - public void IPLoopback() + public static void IPLoopback() { - var testAddress = IPAddress.Loopback; + _ = IPAddress.Loopback; } public void BirthDateCalculator() diff --git a/CH02/Supercalifragilisticexpialidocious/Supercalifragilisticexpialidocious.csproj b/CH02/Supercalifragilisticexpialidocious/Supercalifragilisticexpialidocious.csproj index 3980c74..7cabd8d 100644 --- a/CH02/Supercalifragilisticexpialidocious/Supercalifragilisticexpialidocious.csproj +++ b/CH02/Supercalifragilisticexpialidocious/Supercalifragilisticexpialidocious.csproj @@ -1,12 +1,11 @@  - - Exe - net6.0 - + + Exe + - - - + + + diff --git a/CH02/ValidationContext/Arrow.cs b/CH02/ValidationContext/Arrow.cs index 532e771..38238cf 100644 --- a/CH02/ValidationContext/Arrow.cs +++ b/CH02/ValidationContext/Arrow.cs @@ -2,10 +2,10 @@ internal class Arrow { - public int Sum1(int a, int b) + public static int Sum1(int a, int b) { return a + b; } - public int Sum2(int a, int b) => a + b; + public static int Sum2(int a, int b) => a + b; } \ No newline at end of file diff --git a/CH02/ValidationContext/DbId.cs b/CH02/ValidationContext/DbId.cs index 823e5d9..a3c703a 100644 --- a/CH02/ValidationContext/DbId.cs +++ b/CH02/ValidationContext/DbId.cs @@ -6,10 +6,7 @@ public class DbId public DbId(int id) { - if (id <= 0) - { - throw new ArgumentOutOfRangeException(nameof(id)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(id); Value = id; } @@ -17,7 +14,7 @@ public DbId(int id) public override int GetHashCode() => Value; - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is DbId other && other.Value == Value; } @@ -32,24 +29,15 @@ public override bool Equals(object obj) return !a.Equals(b); } - public class PostId : DbId + public class PostId(int id) : DbId(id) { - public PostId(int id) : base(id) - { - } } - public class TopicId : DbId + public class TopicId(int id) : DbId(id) { - public TopicId(int id) : base(id) - { - } } - public class UserId : DbId + public class UserId(int id) : DbId(id) { - public UserId(int id) : base(id) - { - } } } \ No newline at end of file diff --git a/CH02/ValidationContext/ParameterTypes.cs b/CH02/ValidationContext/ParameterTypes.cs index 623b6c1..c9c9f61 100644 --- a/CH02/ValidationContext/ParameterTypes.cs +++ b/CH02/ValidationContext/ParameterTypes.cs @@ -1,34 +1,29 @@ -public struct TopicId +public struct TopicId(int id) { - public int Id { get; private set; } - - public TopicId(int id) - { - this.Id = id; - } + public int Id { get; private set; } = id; } partial class ParameterTypes { - public int Move(int from, int to) + public static int Move(int from, int to) { // ... some cryptic code here return 0; } - public int MoveContents(int fromTopicId, int toTopicId) + public static int MoveContents(int fromTopicId, int toTopicId) { // ... some cryptic code here return 0; } - public MoveResult MoveContentsB(int fromTopicId, int toTopicId) + public static MoveResult MoveContentsB(int fromTopicId, int toTopicId) { // ... still quite a code here return MoveResult.Success; } - public MoveResult MoveContentsC(TopicId from, TopicId to) + public static MoveResult MoveContentsC(TopicId from, TopicId to) { // ... still quite a code here return MoveResult.Success; diff --git a/CH02/ValidationContext/PostId.cs b/CH02/ValidationContext/PostId.cs index 3cb3e3c..0dd453e 100644 --- a/CH02/ValidationContext/PostId.cs +++ b/CH02/ValidationContext/PostId.cs @@ -6,10 +6,7 @@ public class PostId : IEquatable public PostId(int id) { - if (id <= 0) - { - throw new ArgumentOutOfRangeException(nameof(id)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(id); Value = id; } @@ -17,12 +14,12 @@ public PostId(int id) public override int GetHashCode() => Value; - public override bool Equals(object obj) + public override bool Equals(object? obj) { return Equals(obj as PostId); } - public bool Equals(PostId other) => other?.Value == Value; + public bool Equals(PostId? other) => other?.Value == Value; public static bool operator ==(PostId a, PostId b) { diff --git a/CH02/ValidationContext/ValidationContext.csproj b/CH02/ValidationContext/ValidationContext.csproj index fff7812..c632161 100644 --- a/CH02/ValidationContext/ValidationContext.csproj +++ b/CH02/ValidationContext/ValidationContext.csproj @@ -1,7 +1,3 @@  - - net6.0 - - diff --git a/CH03/ClassesVsStructs/ClassesVsStructs.csproj b/CH03/ClassesVsStructs/ClassesVsStructs.csproj index dbc1517..c96f78e 100644 --- a/CH03/ClassesVsStructs/ClassesVsStructs.csproj +++ b/CH03/ClassesVsStructs/ClassesVsStructs.csproj @@ -1,7 +1,11 @@ - - net6.0 + + 9999 + + + + 9999 diff --git a/CH03/ClassesVsStructs/Identifier.cs b/CH03/ClassesVsStructs/Identifier.cs index bbfd976..1aca869 100644 --- a/CH03/ClassesVsStructs/Identifier.cs +++ b/CH03/ClassesVsStructs/Identifier.cs @@ -2,46 +2,28 @@ namespace Class { - public class Id + public class Id(int value) { - public int Value { get; private set; } - - public Id(int value) - { - this.Value = value; - } + public int Value { get; private set; } = value; } - public class Person + public class Person(int id, string firstName, string lastName, + string city) { - public int Id { get; private set; } - public string FirstName { get; private set; } - public string LastName { get; private set; } - public string City { get; private set; } - - public Person(int id, string firstName, string lastName, - string city) - { - Id = id; - FirstName = firstName; - LastName = lastName; - City = city; - } + public int Id { get; private set; } = id; + public string FirstName { get; private set; } = firstName; + public string LastName { get; private set; } = lastName; + public string City { get; private set; } = city; } } namespace Struct { - public struct Id + public struct Id(int value) { - public int Value { get; private set; } + public int Value { get; private set; } = value; - public Id(int value) - { - this.Value = value; - } - - private void testMethod() + public static void TestMethod() { var a = new Person(42, "Sedat", "Kapanoglu", "San Francisco"); var b = a; @@ -51,20 +33,12 @@ private void testMethod() } } - public struct Person + public struct Person(int id, string firstName, string lastName, + string city) { - public int Id { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string City { get; set; } - - public Person(int id, string firstName, string lastName, - string city) - { - Id = id; - FirstName = firstName; - LastName = lastName; - City = city; - } + public int Id { get; set; } = id; + public string FirstName { get; set; } = firstName; + public string LastName { get; set; } = lastName; + public string City { get; set; } = city; } } \ No newline at end of file diff --git a/CH03/EmojiChat/Controllers/StatsController.cs b/CH03/EmojiChat/Controllers/StatsController.cs index 8359a5e..0b994d3 100644 --- a/CH03/EmojiChat/Controllers/StatsController.cs +++ b/CH03/EmojiChat/Controllers/StatsController.cs @@ -1,6 +1,6 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; public class UserStats { @@ -9,20 +9,13 @@ public class UserStats } [Route("stats/{action}")] -public class StatsController : ControllerBase +public class StatsController(IConfiguration config) : ControllerBase { - private readonly IConfiguration config; - - public StatsController(IConfiguration config) - { - this.config = config; - } - [HttpGet] public UserStats Get(int userId) { var result = new UserStats(); - string connectionString = config.GetConnectionString("DB"); + string connectionString = config.GetConnectionString("DB")!; using (var conn = new SqlConnection(connectionString)) { conn.Open(); diff --git a/CH03/EmojiChat/Controllers/WeatherForecastController.cs b/CH03/EmojiChat/Controllers/WeatherForecastController.cs index 8c2a1ff..b73d2b6 100644 --- a/CH03/EmojiChat/Controllers/WeatherForecastController.cs +++ b/CH03/EmojiChat/Controllers/WeatherForecastController.cs @@ -8,29 +8,23 @@ namespace EmojiChat.Controllers; [ApiController] [Route("[controller]")] -public class WeatherForecastController : ControllerBase +public class WeatherForecastController(ILogger logger) : ControllerBase { - private static readonly string[] summaries = new[] { - "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" -}; - - private readonly ILogger logger; - - public WeatherForecastController(ILogger logger) - { - this.logger = logger; - } + private static readonly string[] summaries = [ + "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", + "Balmy", "Hot", "Sweltering", "Scorching" + ]; [HttpGet] public IEnumerable Get() { + logger.LogDebug("GET request received"); var rng = new Random(); - return Enumerable.Range(1, 5).Select(index => new WeatherForecast - { - Date = DateTime.Now.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = summaries[rng.Next(summaries.Length)] - }) - .ToArray(); + return Enumerable.Range(1, 5) + .Select(index => new WeatherForecast( + Date: DateTime.Now.AddDays(index), + TemperatureC: rng.Next(-20, 55), + Summary: summaries[rng.Next(summaries.Length)])) + .ToArray(); } } \ No newline at end of file diff --git a/CH03/EmojiChat/EmojiChat.csproj b/CH03/EmojiChat/EmojiChat.csproj index dc87473..7fd2a53 100644 --- a/CH03/EmojiChat/EmojiChat.csproj +++ b/CH03/EmojiChat/EmojiChat.csproj @@ -1,11 +1,7 @@  - - net6.0 - - - + diff --git a/CH03/EmojiChat/Startup.cs b/CH03/EmojiChat/Startup.cs index 16737a3..6b9e048 100644 --- a/CH03/EmojiChat/Startup.cs +++ b/CH03/EmojiChat/Startup.cs @@ -6,14 +6,9 @@ namespace EmojiChat; -public class Startup +public class Startup(IConfiguration configuration) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } = configuration; // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) diff --git a/CH03/EmojiChat/WeatherForecast.cs b/CH03/EmojiChat/WeatherForecast.cs index c96750a..0999053 100644 --- a/CH03/EmojiChat/WeatherForecast.cs +++ b/CH03/EmojiChat/WeatherForecast.cs @@ -2,13 +2,7 @@ namespace EmojiChat; -public class WeatherForecast +public record WeatherForecast(DateTime Date, int TemperatureC, string Summary) { - public DateTime Date { get; set; } - - public int TemperatureC { get; set; } - public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); - - public string Summary { get; set; } } \ No newline at end of file diff --git a/CH03/HttpHandler/Program.cs b/CH03/HttpHandler/Program.cs index e0dcab1..c78d6df 100644 --- a/CH03/HttpHandler/Program.cs +++ b/CH03/HttpHandler/Program.cs @@ -38,12 +38,13 @@ public static int Main(string[] args) var client = new RestClient(apiUrl); var request = new RestRequest(requestPath); var response = client.Get(request); - if (response.StatusCode == HttpStatusCode.OK) + if (response.StatusCode != HttpStatusCode.OK + || response.Content is null) { - dynamic obj = JObject.Parse(response.Content); - var period = obj.properties.periods[0]; - return (double)period.temperature; + return null; } - return null; + dynamic obj = JObject.Parse(response.Content); + var period = obj.properties.periods[0]; + return (double)period.temperature; } } \ No newline at end of file diff --git a/CH03/HttpHandler/TempReader.csproj b/CH03/HttpHandler/TempReader.csproj index 872f83e..e60ef3e 100644 --- a/CH03/HttpHandler/TempReader.csproj +++ b/CH03/HttpHandler/TempReader.csproj @@ -1,13 +1,12 @@  - - net6.0 - Exe - + + Exe + - - - - + + + + diff --git a/CH03/IfElse/IDatabase.cs b/CH03/IfElse/IDatabase.cs index 4a2b8c5..26cf54b 100644 --- a/CH03/IfElse/IDatabase.cs +++ b/CH03/IfElse/IDatabase.cs @@ -1,4 +1,4 @@ -internal interface IDatabase +public interface IDatabase { string GetCurrentCityByName(string normalizedFirstName, string normalizedLastName); diff --git a/CH03/IfElse/IfElse.csproj b/CH03/IfElse/IfElse.csproj index fff7812..c632161 100644 --- a/CH03/IfElse/IfElse.csproj +++ b/CH03/IfElse/IfElse.csproj @@ -1,7 +1,3 @@  - - net6.0 - - diff --git a/CH03/IfElse/Person.cs b/CH03/IfElse/Person.cs index 46dc9ca..b789a25 100644 --- a/CH03/IfElse/Person.cs +++ b/CH03/IfElse/Person.cs @@ -1,11 +1,11 @@ -public class Person +public class Person(int id, string firstName, string lastName, string city, IDatabase db) { - public int Id { get; set; } - public string FirstName { get; set; } - public string LastName { get; set; } - public string City { get; set; } + public int Id { get; set; } = id; + public string FirstName { get; set; } = firstName; + public string LastName { get; set; } = lastName; + public string City { get; set; } = city; - private readonly IDatabase db; + private readonly IDatabase db = db; public enum UpdateResult { diff --git a/CH03/OrderAPI/OrderAPI.csproj b/CH03/OrderAPI/OrderAPI.csproj index fff7812..c632161 100644 --- a/CH03/OrderAPI/OrderAPI.csproj +++ b/CH03/OrderAPI/OrderAPI.csproj @@ -1,7 +1,3 @@  - - net6.0 - - diff --git a/CH03/OrderAPI/PostalAddress.cs b/CH03/OrderAPI/PostalAddress.cs index e292791..86ea1a3 100644 --- a/CH03/OrderAPI/PostalAddress.cs +++ b/CH03/OrderAPI/PostalAddress.cs @@ -1,10 +1,10 @@ -public class PostalAddress +public class PostalAddress(string firstName, string lastName, string address1, string address2, string city, string zipCode, string notes) { - public string FirstName { get; set; } - public string LastName { get; set; } - public string Address1 { get; set; } - public string Address2 { get; set; } - public string City { get; set; } - public string ZipCode { get; set; } - public string Notes { get; set; } + public string FirstName { get; set; } = firstName; + public string LastName { get; set; } = lastName; + public string Address1 { get; set; } = address1; + public string Address2 { get; set; } = address2; + public string City { get; set; } = city; + public string ZipCode { get; set; } = zipCode; + public string Notes { get; set; } = notes; } \ No newline at end of file diff --git a/CH03/OrderAPI/Shipping.cs b/CH03/OrderAPI/Shipping.cs index 72b8b16..df342d3 100644 --- a/CH03/OrderAPI/Shipping.cs +++ b/CH03/OrderAPI/Shipping.cs @@ -1,23 +1,21 @@ using System; -public class Shipping +public class Shipping(IDatabase db) { - private readonly IDatabase db; - public void SetShippingAddress(Guid customerId, PostalAddress newAddress) { - normalizeFields(newAddress); + NormalizeFields(newAddress); db.UpdateShippingAddress(customerId, newAddress); } - private void normalizeFields(PostalAddress address) + protected static void NormalizeFields(PostalAddress address) { address.FirstName = TextHelper.Capitalize(address.FirstName); address.LastName = TextHelper.Capitalize(address.LastName); } - private void normalizeFields2(PostalAddress address) + protected static void NormalizeFields2(PostalAddress address) { address.FirstName = TextHelper.Capitalize(address.FirstName); address.LastName = TextHelper.Capitalize(address.LastName); @@ -25,7 +23,7 @@ private void normalizeFields2(PostalAddress address) } } -internal interface IDatabase +public interface IDatabase { void UpdateShippingAddress(Guid customerId, PostalAddress newAddress); } \ No newline at end of file diff --git a/CH03/OrderAPI/TextHelper.cs b/CH03/OrderAPI/TextHelper.cs index ca869a7..7eb1e29 100644 --- a/CH03/OrderAPI/TextHelper.cs +++ b/CH03/OrderAPI/TextHelper.cs @@ -8,7 +8,7 @@ public static string Capitalize(string text) { return text; } - return Char.ToUpper(text[0]) + text.Substring(1).ToLower(); + return Char.ToUpper(text[0]) + text[1..].ToLower(); } public static string Capitalize(string text, @@ -20,7 +20,7 @@ public static string Capitalize(string text, } if (!everyWord) { - return Char.ToUpper(text[0]) + text.Substring(1).ToLower(); + return char.ToUpper(text[0]) + text[1..].ToLower(); } string[] words = text.Split(' '); for (int i = 0; i < words.Length; i++) @@ -42,9 +42,9 @@ public static string Capitalize(string text, if (filename) { return Char.ToUpperInvariant(text[0]) - + text.Substring(1).ToLowerInvariant(); + + text[1..].ToLowerInvariant(); } - return Char.ToUpper(text[0]) + text.Substring(1).ToLower(); + return char.ToUpper(text[0]) + text[1..].ToLower(); } string[] words = text.Split(' '); for (int i = 0; i < words.Length; i++) @@ -65,7 +65,7 @@ public static string CapitalizeFirstLetter(string text) { return text.ToUpper(); } - return Char.ToUpper(text[0]) + text.Substring(1).ToLower(); + return Char.ToUpper(text[0]) + text[1..].ToLower(); } public static string CapitalizeEveryWord(string text) @@ -91,7 +91,7 @@ public static string FormatFilename(string filename) else { words[n] = Char.ToUpperInvariant(word[0]) + - word.Substring(1).ToLowerInvariant(); + word[1..].ToLowerInvariant(); } } return String.Join("_", words); diff --git a/CH03/Shoppidy/Controllers/HomeController.cs b/CH03/Shoppidy/Controllers/HomeController.cs index 3487d19..a2b4093 100644 --- a/CH03/Shoppidy/Controllers/HomeController.cs +++ b/CH03/Shoppidy/Controllers/HomeController.cs @@ -1,37 +1,28 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Threading.Tasks; +using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Shoppidy.Models; -namespace Shoppidy.Controllers +namespace Shoppidy.Controllers; + +public class HomeController(ILogger logger) : Controller { - public class HomeController : Controller + public IActionResult Index() { - private readonly ILogger logger; - - public HomeController(ILogger logger) - { - this.logger = logger; - } - - public IActionResult Index() - { - return View(); - } + logger.LogDebug("Index()"); + return View(); + } - public IActionResult Privacy() - { - return View(); - } + public IActionResult Privacy() + { + logger.LogDebug("Privacy()"); + return View(); + } - [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] - public IActionResult Error() - { - return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); - } + [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] + public IActionResult Error() + { + logger.LogDebug("Error()"); + return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } diff --git a/CH03/Shoppidy/Controllers/ShipmentFormController.cs b/CH03/Shoppidy/Controllers/ShipmentFormController.cs index 7789fbe..a6f3815 100644 --- a/CH03/Shoppidy/Controllers/ShipmentFormController.cs +++ b/CH03/Shoppidy/Controllers/ShipmentFormController.cs @@ -1,5 +1,4 @@ -using System.Runtime.InteropServices.ComTypes; -using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc; public enum ShippingFormValidationResult { @@ -10,10 +9,8 @@ public enum ShippingFormValidationResult ZipCodeDidntMatch, } -public class ShipmentFormController : Controller +public class ShipmentFormController(IShipmentService service) : Controller { - private IShipmentService service; - public IActionResult Index() { return View(); @@ -146,7 +143,7 @@ private bool validate(ShipmentAddress form) return validationResult == ShippingFormValidationResult.Valid; } - private IActionResult shippingFormError(ShipmentAddress form = null) + private RedirectToActionResult shippingFormError(ShipmentAddress? form = null) { Response.Cookies.Append("shipping_error", "1"); return RedirectToAction("Index", "ShippingForm", form); diff --git a/CH03/Shoppidy/Models/ErrorViewModel.cs b/CH03/Shoppidy/Models/ErrorViewModel.cs index dcfcc95..3163854 100644 --- a/CH03/Shoppidy/Models/ErrorViewModel.cs +++ b/CH03/Shoppidy/Models/ErrorViewModel.cs @@ -1,11 +1,8 @@ -using System; +namespace Shoppidy.Models; -namespace Shoppidy.Models +public class ErrorViewModel { - public class ErrorViewModel - { - public string RequestId { get; set; } + public string? RequestId { get; set; } - public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); - } + public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } diff --git a/CH03/Shoppidy/Models/IShipmentService.cs b/CH03/Shoppidy/Models/IShipmentService.cs index 5fab761..3e008ae 100644 --- a/CH03/Shoppidy/Models/IShipmentService.cs +++ b/CH03/Shoppidy/Models/IShipmentService.cs @@ -1,4 +1,4 @@ -internal interface IShipmentService +public interface IShipmentService { ShippingFormValidationResult ValidateShippingForm(ShipmentAddress form); bool SaveShippingInfo(ShipmentAddress form); diff --git a/CH03/Shoppidy/Models/ShipmentAddress.cs b/CH03/Shoppidy/Models/ShipmentAddress.cs index 29257db..a13c486 100644 --- a/CH03/Shoppidy/Models/ShipmentAddress.cs +++ b/CH03/Shoppidy/Models/ShipmentAddress.cs @@ -2,13 +2,13 @@ public class ShipmentAddress { - public string FirstName { get; set; } - public string LastName { get; set; } - public string Address1 { get; set; } - public string Address2 { get; set; } - public string City { get; set; } + public required string FirstName { get; set; } + public required string LastName { get; set; } + public required string Address1 { get; set; } + public required string Address2 { get; set; } + public required string City { get; set; } [RegularExpression(@"^\s*\d{5}(-\d{4})?\s*$")] - public string ZipCode { get; set; } + public required string ZipCode { get; set; } } diff --git a/CH03/Shoppidy/Program.cs b/CH03/Shoppidy/Program.cs index f3cffac..dc7c34b 100644 --- a/CH03/Shoppidy/Program.cs +++ b/CH03/Shoppidy/Program.cs @@ -1,26 +1,19 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -namespace Shoppidy +namespace Shoppidy; + +public class Program { - public class Program + public static void Main(string[] args) { - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); + CreateHostBuilder(args).Build().Run(); } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); } diff --git a/CH03/Shoppidy/Shoppidy.csproj b/CH03/Shoppidy/Shoppidy.csproj index 92605c5..375cccf 100644 --- a/CH03/Shoppidy/Shoppidy.csproj +++ b/CH03/Shoppidy/Shoppidy.csproj @@ -1,7 +1,3 @@ - - netcoreapp3.1 - - diff --git a/CH03/Shoppidy/Startup.cs b/CH03/Shoppidy/Startup.cs index 864096c..42be484 100644 --- a/CH03/Shoppidy/Startup.cs +++ b/CH03/Shoppidy/Startup.cs @@ -1,57 +1,46 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -namespace Shoppidy +namespace Shoppidy; + +public class Startup(IConfiguration configuration) { - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } + public IConfiguration Configuration { get; } = configuration; - public IConfiguration Configuration { get; } + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddControllersWithViews(); + } - // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + if (env.IsDevelopment()) { - services.AddControllersWithViews(); + app.UseDeveloperExceptionPage(); } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + else { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - else - { - app.UseExceptionHandler("/Home/Error"); - // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. - app.UseHsts(); - } - app.UseHttpsRedirection(); - app.UseStaticFiles(); + app.UseExceptionHandler("/Home/Error"); + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); + } + app.UseHttpsRedirection(); + app.UseStaticFiles(); - app.UseRouting(); + app.UseRouting(); - app.UseAuthorization(); + app.UseAuthorization(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllerRoute( - name: "default", - pattern: "{controller=Home}/{action=Index}/{id?}"); - }); - } + app.UseEndpoints(endpoints => + { + endpoints.MapControllerRoute( + name: "default", + pattern: "{controller=Home}/{action=Index}/{id?}"); + }); } } diff --git a/CH03/TechnicalDebt/TechnicalDebt.csproj b/CH03/TechnicalDebt/TechnicalDebt.csproj index fff7812..c632161 100644 --- a/CH03/TechnicalDebt/TechnicalDebt.csproj +++ b/CH03/TechnicalDebt/TechnicalDebt.csproj @@ -1,7 +1,3 @@  - - net6.0 - - diff --git a/CH03/Twistat/Pages/Callback.cshtml.cs b/CH03/Twistat/Pages/Callback.cshtml.cs index 684241e..2cda1aa 100644 --- a/CH03/Twistat/Pages/Callback.cshtml.cs +++ b/CH03/Twistat/Pages/Callback.cshtml.cs @@ -7,12 +7,12 @@ namespace Twistat.Pages; public class CallbackModel : PageModel { - public IEnumerable Nicks { get; set; } + public required IEnumerable Nicks { get; set; } public void OnGet() { // https://localhost:44304/Callback?oauth_token=XhaguQAAAAABFEzEAAABcqR3JuQ&oauth_verifier=focVY8eYIvceblH3rNtPRNrEOtOUP0Pv - var session = (OAuth.OAuthSession)TempData["session"]; + var session = TempData["session"] as OAuth.OAuthSession; session.GetTokens(Request.Query["oauth_verifier"].First()); var tokens = new Tokens() { diff --git a/CH03/Twistat/Pages/Error.cshtml.cs b/CH03/Twistat/Pages/Error.cshtml.cs index f5d6acd..da8822d 100644 --- a/CH03/Twistat/Pages/Error.cshtml.cs +++ b/CH03/Twistat/Pages/Error.cshtml.cs @@ -6,21 +6,15 @@ namespace Twistat.Pages; [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] -public class ErrorModel : PageModel +public class ErrorModel(ILogger logger) : PageModel { - public string RequestId { get; set; } + public string? RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); - private readonly ILogger logger; - - public ErrorModel(ILogger logger) - { - this.logger = logger; - } - public void OnGet() { + logger.LogDebug("GET request received"); RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier; } } \ No newline at end of file diff --git a/CH03/Twistat/Pages/Index.cshtml.cs b/CH03/Twistat/Pages/Index.cshtml.cs index a456b70..16c1ace 100644 --- a/CH03/Twistat/Pages/Index.cshtml.cs +++ b/CH03/Twistat/Pages/Index.cshtml.cs @@ -3,16 +3,10 @@ namespace Twistat.Pages; -public class IndexModel : PageModel +public class IndexModel(ILogger logger) : PageModel { - private readonly ILogger logger; - - public IndexModel(ILogger logger) - { - this.logger = logger; - } - public void OnGet() { + logger.LogDebug("GET request received"); } } \ No newline at end of file diff --git a/CH03/Twistat/Pages/Login.cshtml.cs b/CH03/Twistat/Pages/Login.cshtml.cs index 13fd065..819a4c8 100644 --- a/CH03/Twistat/Pages/Login.cshtml.cs +++ b/CH03/Twistat/Pages/Login.cshtml.cs @@ -5,19 +5,12 @@ namespace Twistat.Pages; -public class LoginModel : PageModel +public class LoginModel(IConfiguration configuration) : PageModel { - private readonly IConfiguration config; - - public LoginModel(IConfiguration configuration) - { - this.config = configuration; - } - public IActionResult OnGet() { - string consumerKey = config["Twitter:ConsumerKey"]; - string consumerSecret = config["Twitter:ConsumerSecret"]; + string consumerKey = configuration["Twitter:ConsumerKey"]!; + string consumerSecret = configuration["Twitter:ConsumerSecret"]!; var session = OAuth.Authorize(consumerKey, consumerSecret, oauthCallback: $"{Request.Scheme}://{Request.Host}/Callback"); TempData["session"] = session; diff --git a/CH03/Twistat/Pages/Privacy.cshtml.cs b/CH03/Twistat/Pages/Privacy.cshtml.cs index 8553210..fcc43b1 100644 --- a/CH03/Twistat/Pages/Privacy.cshtml.cs +++ b/CH03/Twistat/Pages/Privacy.cshtml.cs @@ -3,16 +3,10 @@ namespace Twistat.Pages; -public class PrivacyModel : PageModel +public class PrivacyModel(ILogger logger) : PageModel { - private readonly ILogger logger; - - public PrivacyModel(ILogger logger) - { - this.logger = logger; - } - public void OnGet() { + logger.LogDebug("GET request received"); } } \ No newline at end of file diff --git a/CH03/Twistat/Startup.cs b/CH03/Twistat/Startup.cs index ac0d1d2..28a5817 100644 --- a/CH03/Twistat/Startup.cs +++ b/CH03/Twistat/Startup.cs @@ -6,14 +6,9 @@ namespace Twistat; -public class Startup +public class Startup(IConfiguration configuration) { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } + public IConfiguration Configuration { get; } = configuration; // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) diff --git a/CH03/Twistat/Twistat.csproj b/CH03/Twistat/Twistat.csproj index 0f81324..e753578 100644 --- a/CH03/Twistat/Twistat.csproj +++ b/CH03/Twistat/Twistat.csproj @@ -1,13 +1,13 @@  - - net6.0 - Twistat - - - - - - - + + Twistat + + + + + + + + \ No newline at end of file diff --git a/CH03/Twistat/Twitter.cs b/CH03/Twistat/Twitter.cs index 3effbbb..18234c1 100644 --- a/CH03/Twistat/Twitter.cs +++ b/CH03/Twistat/Twitter.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -public class Twitter +public class Twitter(TwitterAccessToken accessToken) { public static Uri GetAuthorizationUrl(Uri callbackUrl) { @@ -17,15 +17,11 @@ public static TwitterAccessToken GetAccessToken( return new TwitterAccessToken(); } - public Twitter(TwitterAccessToken accessToken) - { - // we should store this somewhere - } - public IEnumerable GetListOfFollowers( TwitterUserId userId) { // no idea how this will work + _ = accessToken; // access the access token yield break; } } diff --git a/CH04/DateUtils/DateUtils.csproj b/CH04/DateUtils/DateUtils.csproj index fff7812..c632161 100644 --- a/CH04/DateUtils/DateUtils.csproj +++ b/CH04/DateUtils/DateUtils.csproj @@ -1,7 +1,3 @@  - - net6.0 - - diff --git a/CH04/DateUtilsTests/Tests.csproj b/CH04/DateUtilsTests/Tests.csproj index 0938593..8995a15 100644 --- a/CH04/DateUtilsTests/Tests.csproj +++ b/CH04/DateUtilsTests/Tests.csproj @@ -1,13 +1,10 @@  - - net6.0 - - - - - - + + + + + diff --git a/CH04/DateUtilsTests/UsernameTest.cs b/CH04/DateUtilsTests/UsernameTest.cs index 2ed5ee4..965932c 100644 --- a/CH04/DateUtilsTests/UsernameTest.cs +++ b/CH04/DateUtilsTests/UsernameTest.cs @@ -10,7 +10,7 @@ internal class UsernameTest public void ctor_nullUsername_ThrowsArgumentNullException() { Assert.Throws( - () => new Username(null)); + () => new Username(null!)); } [TestCase("")] diff --git a/CH04/Posts/PostService.cs b/CH04/Posts/PostService.cs index ab3154f..ba60fc6 100644 --- a/CH04/Posts/PostService.cs +++ b/CH04/Posts/PostService.cs @@ -7,56 +7,50 @@ namespace Posts; public class Tag { public Guid Id { get; set; } - public string Title { get; set; } + public required string Title { get; set; } } -public class PostService +public class PostService(IPostRepository db) { public const int MaxPageSize = 100; - private readonly IPostRepository db; - public PostService(IPostRepository db) + private List toListTrimmed(byte numberOfItems, + IQueryable query) { - this.db = db; + return [.. query.Take(numberOfItems)]; } - private IList toListTrimmed(byte numberOfItems, - IQueryable query) - { - return query.Take(numberOfItems).ToList(); - } - - public IList GetTrendingTags(byte numberOfItems) + public List GetTrendingTags(byte numberOfItems) { return toListTrimmed(numberOfItems, db.GetTrendingTagTable()); } - public IList GetTrendingTagsByTitle( - byte numberOfItems) + public List GetTrendingTagsByTitle( + byte numberOfItems) { return toListTrimmed(numberOfItems, db.GetTrendingTagTable() .OrderBy(p => p.Title)); } - public IList GetYesterdaysTrendingTags(byte numberOfItems) + public List GetYesterdaysTrendingTags(byte numberOfItems) { return toListTrimmed(numberOfItems, db.GetYesterdaysTrendingTagTable()); } - public IList GetTrendingTags(byte numberOfItems, - bool sortByTitle) + public List GetTrendingTags(byte numberOfItems, + bool sortByTitle) { var query = db.GetTrendingTagTable(); if (sortByTitle) { query = query.OrderBy(p => p.Title); } - return query.Take(numberOfItems).ToList(); + return [.. query.Take(numberOfItems)]; } - public IList GetTrendingTags(byte numberOfItems, - bool sortByTitle, bool yesterdaysTags) + public List GetTrendingTags(byte numberOfItems, + bool sortByTitle, bool yesterdaysTags) { var query = yesterdaysTags ? db.GetTrendingTagTable() @@ -65,15 +59,12 @@ public IList GetTrendingTags(byte numberOfItems, { query = query.OrderBy(p => p.Title); } - return query.Take(numberOfItems).ToList(); + return [.. query.Take(numberOfItems)]; } public Tag GetTagDetails(byte numberOfItems, int index) { - if (index >= numberOfItems) - { - throw new ArgumentOutOfRangeException(nameof(numberOfItems)); - } + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(index, numberOfItems); return GetTrendingTags(numberOfItems)[index]; } } \ No newline at end of file diff --git a/CH04/Posts/Posts.csproj b/CH04/Posts/Posts.csproj index fff7812..c632161 100644 --- a/CH04/Posts/Posts.csproj +++ b/CH04/Posts/Posts.csproj @@ -1,7 +1,3 @@  - - net6.0 - - diff --git a/CH04/Summer/Summer.csproj b/CH04/Summer/Summer.csproj index fff7812..c632161 100644 --- a/CH04/Summer/Summer.csproj +++ b/CH04/Summer/Summer.csproj @@ -1,7 +1,3 @@  - - net6.0 - - diff --git a/CH04/User/User.csproj b/CH04/User/User.csproj index fff7812..c632161 100644 --- a/CH04/User/User.csproj +++ b/CH04/User/User.csproj @@ -1,7 +1,3 @@  - - net6.0 - - diff --git a/CH04/User/Username.cs b/CH04/User/Username.cs index 609af8e..911e53d 100644 --- a/CH04/User/Username.cs +++ b/CH04/User/Username.cs @@ -10,23 +10,19 @@ public class Username public Username(string username) { - if (username is null) - { - throw new ArgumentNullException(nameof(username)); - } + ArgumentNullException.ThrowIfNull(username); if (!Regex.IsMatch(username, validUsernamePattern)) { - throw new ArgumentException(nameof(username), - "Invalid username"); + throw new ArgumentException("Invalid username", nameof(username)); } this.Value = username; } - public override string ToString() => base.ToString(); + public override string? ToString() => base.ToString(); public override int GetHashCode() => Value.GetHashCode(); - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is Username other && other.Value == Value; } diff --git a/CH05/Blabber.Models/Blabber.Models.csproj b/CH05/Blabber.Models/Blabber.Models.csproj index edb0b7b..d3d89b6 100644 --- a/CH05/Blabber.Models/Blabber.Models.csproj +++ b/CH05/Blabber.Models/Blabber.Models.csproj @@ -1,6 +1,14 @@  netstandard2.0 + 7.3 + disable + + + 1701;1702;IDE0130 + + + 1701;1702;IDE0130 diff --git a/CH05/Blabber/Blabber.csproj b/CH05/Blabber/Blabber.csproj index 0b9479e..1b2de24 100644 --- a/CH05/Blabber/Blabber.csproj +++ b/CH05/Blabber/Blabber.csproj @@ -1,6 +1,6 @@  - + Debug @@ -25,6 +25,8 @@ + 7.3 + disable true @@ -46,48 +48,49 @@ - ..\..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.dll + ..\..\packages\EntityFramework.6.5.1\lib\net45\EntityFramework.dll - ..\..\packages\EntityFramework.6.4.4\lib\net45\EntityFramework.SqlServer.dll + ..\..\packages\EntityFramework.6.5.1\lib\net45\EntityFramework.SqlServer.dll - - ..\..\packages\Microsoft.Bcl.AsyncInterfaces.7.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll + + ..\..\packages\Microsoft.Bcl.AsyncInterfaces.9.0.9\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll - - ..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.3.6.0\lib\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll + + ..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.4.1.0\lib\net472\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll - - ..\..\packages\Microsoft.Extensions.DependencyInjection.7.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.dll + + ..\..\packages\Microsoft.Extensions.DependencyInjection.9.0.9\lib\net462\Microsoft.Extensions.DependencyInjection.dll - - ..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.7.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.Abstractions.dll + + ..\..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.9.0.9\lib\net462\Microsoft.Extensions.DependencyInjection.Abstractions.dll ..\..\packages\Microsoft.Web.Infrastructure.2.0.0\lib\net40\Microsoft.Web.Infrastructure.dll - ..\..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll + ..\..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll - - ..\..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.116.0\lib\net46\System.Data.SQLite.dll + + ..\..\packages\System.Data.SQLite.2.0.2\lib\net471\System.Data.SQLite.dll - - ..\..\packages\System.Data.SQLite.EF6.1.0.116.0\lib\net46\System.Data.SQLite.EF6.dll + + ..\..\packages\System.Data.SQLite.EF6.2.0.2\lib\net471\System.Data.SQLite.EF6.dll - - ..\..\packages\System.Data.SQLite.Linq.1.0.116.0\lib\net46\System.Data.SQLite.Linq.dll + + ..\..\packages\System.Data.SQLite.Linq.1.0.119.0\lib\net46\System.Data.SQLite.Linq.dll - - ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.0.0\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + ..\..\packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll - - ..\..\packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + + ..\..\packages\System.Threading.Tasks.Extensions.4.6.3\lib\net462\System.Threading.Tasks.Extensions.dll + @@ -95,22 +98,22 @@ - ..\..\packages\Microsoft.AspNet.WebPages.3.2.9\lib\net45\System.Web.Helpers.dll + ..\..\packages\Microsoft.AspNet.WebPages.3.3.0\lib\net45\System.Web.Helpers.dll - - ..\..\packages\Microsoft.AspNet.Mvc.5.2.9\lib\net45\System.Web.Mvc.dll + + ..\..\packages\Microsoft.AspNet.Mvc.5.3.0\lib\net45\System.Web.Mvc.dll - ..\..\packages\Microsoft.AspNet.Razor.3.2.9\lib\net45\System.Web.Razor.dll + ..\..\packages\Microsoft.AspNet.Razor.3.3.0\lib\net45\System.Web.Razor.dll - ..\..\packages\Microsoft.AspNet.WebPages.3.2.9\lib\net45\System.Web.WebPages.dll + ..\..\packages\Microsoft.AspNet.WebPages.3.3.0\lib\net45\System.Web.WebPages.dll - ..\..\packages\Microsoft.AspNet.WebPages.3.2.9\lib\net45\System.Web.WebPages.Deployment.dll + ..\..\packages\Microsoft.AspNet.WebPages.3.3.0\lib\net45\System.Web.WebPages.Deployment.dll - ..\..\packages\Microsoft.AspNet.WebPages.3.2.9\lib\net45\System.Web.WebPages.Razor.dll + ..\..\packages\Microsoft.AspNet.WebPages.3.3.0\lib\net45\System.Web.WebPages.Razor.dll @@ -199,11 +202,11 @@ - - - - - + + + + + @@ -231,8 +234,8 @@ - - + + @@ -272,16 +275,16 @@ This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - + + + + - - - + + + 'click') event = event.replace(stripNameRegex, ''); return customEvents[event] || event; } - const EventHandler = { on(element, event, handler, delegationFunction) { addHandler(element, event, handler, delegationFunction, false); }, - one(element, event, handler, delegationFunction) { addHandler(element, event, handler, delegationFunction, true); }, - off(element, originalTypeEvent, handler, delegationFunction) { if (typeof originalTypeEvent !== 'string' || !element) { return; } - const [isDelegated, callable, typeEvent] = normalizeParameters(originalTypeEvent, handler, delegationFunction); const inNamespace = typeEvent !== originalTypeEvent; const events = getElementEvents(element); const storeElementEvent = events[typeEvent] || {}; const isNamespace = originalTypeEvent.startsWith('.'); - if (typeof callable !== 'undefined') { // Simplest case: handler is passed, remove that listener ONLY. if (!Object.keys(storeElementEvent).length) { return; } - removeHandler(element, events, typeEvent, callable, isDelegated ? handler : null); return; } - if (isNamespace) { for (const elementEvent of Object.keys(events)) { removeNamespacedHandlers(element, events, elementEvent, originalTypeEvent.slice(1)); } } - - for (const keyHandlers of Object.keys(storeElementEvent)) { + for (const [keyHandlers, event] of Object.entries(storeElementEvent)) { const handlerKey = keyHandlers.replace(stripUidRegex, ''); - if (!inNamespace || originalTypeEvent.includes(handlerKey)) { - const event = storeElementEvent[keyHandlers]; removeHandler(element, events, typeEvent, event.callable, event.delegationSelector); } } }, - trigger(element, event, args) { if (typeof event !== 'string' || !element) { return null; } - const $ = getjQuery(); const typeEvent = getTypeEvent(event); const inNamespace = event !== typeEvent; @@ -542,7 +486,6 @@ let bubbles = true; let nativeDispatch = true; let defaultPrevented = false; - if (inNamespace && $) { jQueryEvent = $.Event(event, args); $(element).trigger(jQueryEvent); @@ -550,177 +493,103 @@ nativeDispatch = !jQueryEvent.isImmediatePropagationStopped(); defaultPrevented = jQueryEvent.isDefaultPrevented(); } - - let evt = new Event(event, { + const evt = hydrateObj(new Event(event, { bubbles, cancelable: true - }); - evt = hydrateObj(evt, args); - + }), args); if (defaultPrevented) { evt.preventDefault(); } - if (nativeDispatch) { element.dispatchEvent(evt); } - if (evt.defaultPrevented && jQueryEvent) { jQueryEvent.preventDefault(); } - return evt; } - }; - - function hydrateObj(obj, meta) { - for (const [key, value] of Object.entries(meta || {})) { + function hydrateObj(obj, meta = {}) { + for (const [key, value] of Object.entries(meta)) { try { obj[key] = value; } catch (_unused) { Object.defineProperty(obj, key, { configurable: true, - get() { return value; } - }); } } - return obj; } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): dom/data.js + * Bootstrap dom/manipulator.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ - /** - * Constants - */ - const elementMap = new Map(); - const 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.2.2): dom/manipulator.js - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) - * -------------------------------------------------------------------------- - */ function normalizeData(value) { if (value === 'true') { return true; } - if (value === 'false') { return false; } - if (value === Number(value).toString()) { return Number(value); } - if (value === '' || value === 'null') { return null; } - if (typeof value !== 'string') { return value; } - try { return JSON.parse(decodeURIComponent(value)); } catch (_unused) { return value; } } - 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 = {}; const bsKeys = Object.keys(element.dataset).filter(key => key.startsWith('bs') && !key.startsWith('bsConfig')); - for (const key of bsKeys) { let pureKey = key.replace(/^bs/, ''); - pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1, pureKey.length); + pureKey = pureKey.charAt(0).toLowerCase() + pureKey.slice(1); attributes[pureKey] = normalizeData(element.dataset[key]); } - return attributes; }, - getDataAttribute(element, key) { return normalizeData(element.getAttribute(`data-bs-${normalizeDataKey(key)}`)); } - }; /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): util/config.js + * Bootstrap util/config.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Class definition */ @@ -730,63 +599,56 @@ static get Default() { return {}; } - static get DefaultType() { return {}; } - static get NAME() { throw new Error('You have to implement the static method "NAME", for each component!'); } - _getConfig(config) { config = this._mergeConfigObj(config); config = this._configAfterMerge(config); - this._typeCheckConfig(config); - return config; } - _configAfterMerge(config) { return config; } - _mergeConfigObj(config, element) { const jsonConfig = isElement$1(element) ? Manipulator.getDataAttribute(element, 'config') : {}; // try to parse - return { ...this.constructor.Default, + return { + ...this.constructor.Default, ...(typeof jsonConfig === 'object' ? jsonConfig : {}), ...(isElement$1(element) ? Manipulator.getDataAttributes(element) : {}), ...(typeof config === 'object' ? config : {}) }; } - _typeCheckConfig(config, configTypes = this.constructor.DefaultType) { - for (const property of Object.keys(configTypes)) { - const expectedTypes = configTypes[property]; + for (const [property, expectedTypes] of Object.entries(configTypes)) { const value = config[property]; const valueType = isElement$1(value) ? 'element' : toType(value); - if (!new RegExp(expectedTypes).test(valueType)) { throw new TypeError(`${this.constructor.NAME.toUpperCase()}: Option "${property}" provided type "${valueType}" but expected type "${expectedTypes}".`); } } } - } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): base-component.js + * Bootstrap base-component.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ - const VERSION = '5.2.2'; + const VERSION = '5.3.8'; + /** * Class definition */ @@ -795,69 +657,147 @@ constructor(element, config) { super(); element = getElement(element); - if (!element) { return; } - this._element = element; this._config = this._getConfig(config); Data.set(this._element, this.constructor.DATA_KEY, this); - } // Public - + } + // Public dispose() { Data.remove(this._element, this.constructor.DATA_KEY); EventHandler.off(this._element, this.constructor.EVENT_KEY); - for (const propertyName of Object.getOwnPropertyNames(this)) { this[propertyName] = null; } } + // Private _queueCallback(callback, element, isAnimated = true) { executeAfterTransition(callback, element, isAnimated); } - _getConfig(config) { config = this._mergeConfigObj(config, this._element); config = this._configAfterMerge(config); - this._typeCheckConfig(config); - return config; - } // Static - + } + // 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 DATA_KEY() { return `bs.${this.NAME}`; } - static get EVENT_KEY() { return `.${this.DATA_KEY}`; } - static eventName(name) { return `${name}${this.EVENT_KEY}`; } - } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): util/component-functions.js + * Bootstrap dom/selector-engine.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + + const getSelector = element => { + let selector = element.getAttribute('data-bs-target'); + if (!selector || selector === '#') { + let hrefAttribute = element.getAttribute('href'); + + // The only valid content that could double as a selector are IDs or classes, + // so everything starting with `#` or `.`. If a "real" URL is used as the selector, + // `document.querySelector` will rightfully complain it is invalid. + // See https://github.com/twbs/bootstrap/issues/32273 + if (!hrefAttribute || !hrefAttribute.includes('#') && !hrefAttribute.startsWith('.')) { + return null; + } + + // Just in case some CMS puts out a full URL with the anchor appended + if (hrefAttribute.includes('#') && !hrefAttribute.startsWith('#')) { + hrefAttribute = `#${hrefAttribute.split('#')[1]}`; + } + selector = hrefAttribute && hrefAttribute !== '#' ? hrefAttribute.trim() : null; + } + return selector ? selector.split(',').map(sel => parseSelector(sel)).join(',') : null; + }; + 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.closest(selector); + while (ancestor) { + parents.push(ancestor); + ancestor = ancestor.parentNode.closest(selector); + } + return parents; + }, + prev(element, selector) { + let previous = element.previousElementSibling; + while (previous) { + if (previous.matches(selector)) { + return [previous]; + } + previous = previous.previousElementSibling; + } + return []; + }, + // TODO: this is now unused; remove later along with prev() + 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)); + }, + getSelectorFromElement(element) { + const selector = getSelector(element); + if (selector) { + return SelectorEngine.findOne(selector) ? selector : null; + } + return null; + }, + getElementFromSelector(element) { + const selector = getSelector(element); + return selector ? SelectorEngine.findOne(selector) : null; + }, + getMultipleElementsFromSelector(element) { + const selector = getSelector(element); + return selector ? SelectorEngine.find(selector) : []; + } + }; + + /** + * -------------------------------------------------------------------------- + * Bootstrap util/component-functions.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ @@ -869,24 +809,25 @@ if (['A', 'AREA'].includes(this.tagName)) { event.preventDefault(); } - if (isDisabled(this)) { return; } + const target = SelectorEngine.getElementFromSelector(this) || this.closest(`.${name}`); + const instance = component.getOrCreateInstance(target); - 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 - + // Method argument is left, for Alert and only, as it doesn't implement the 'hide' method instance[method](); }); }; /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): alert.js + * Bootstrap alert.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ @@ -898,6 +839,7 @@ const EVENT_CLOSED = `closed${EVENT_KEY$b}`; const CLASS_NAME_FADE$5 = 'fade'; const CLASS_NAME_SHOW$8 = 'show'; + /** * Class definition */ @@ -906,55 +848,47 @@ // Getters static get NAME() { return NAME$f; - } // Public - + } + // 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 - + } + // Private _destroyElement() { this._element.remove(); - EventHandler.trigger(this._element, EVENT_CLOSED); this.dispose(); - } // Static - + } + // 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 */ @@ -963,10 +897,12 @@ /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): button.js + * Bootstrap button.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ @@ -978,6 +914,7 @@ const CLASS_NAME_ACTIVE$3 = 'active'; const SELECTOR_DATA_TOGGLE$5 = '[data-bs-toggle="button"]'; const EVENT_CLICK_DATA_API$6 = `click${EVENT_KEY$a}${DATA_API_KEY$6}`; + /** * Class definition */ @@ -986,37 +923,36 @@ // Getters static get NAME() { return NAME$e; - } // Public - + } + // 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 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 */ @@ -1025,81 +961,12 @@ /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): dom/selector-engine.js + * Bootstrap util/swipe.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ - /** - * Constants - */ - - 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.closest(selector); - - while (ancestor) { - parents.push(ancestor); - ancestor = ancestor.parentNode.closest(selector); - } - - return parents; - }, - - prev(element, selector) { - let previous = element.previousElementSibling; - - while (previous) { - if (previous.matches(selector)) { - return [previous]; - } - - previous = previous.previousElementSibling; - } - - return []; - }, - - // TODO: this is now unused; remove later along with prev() - 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.2.2): util/swipe.js - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) - * -------------------------------------------------------------------------- - */ /** * Constants */ @@ -1125,6 +992,7 @@ leftCallback: '(function|null)', rightCallback: '(function|null)' }; + /** * Class definition */ @@ -1133,84 +1001,67 @@ constructor(element, config) { super(); this._element = element; - if (!element || !Swipe.isSupported()) { return; } - this._config = this._getConfig(config); this._deltaX = 0; this._supportPointerEvents = Boolean(window.PointerEvent); - this._initEvents(); - } // Getters - + } + // Getters static get Default() { return Default$c; } - static get DefaultType() { return DefaultType$c; } - static get NAME() { return NAME$d; - } // Public - + } + // Public dispose() { EventHandler.off(this._element, EVENT_KEY$9); - } // Private - + } + // Private _start(event) { if (!this._supportPointerEvents) { this._deltaX = event.touches[0].clientX; return; } - if (this._eventIsPointerPenTouch(event)) { this._deltaX = event.clientX; } } - _end(event) { if (this._eventIsPointerPenTouch(event)) { this._deltaX = event.clientX - this._deltaX; } - this._handleSwipe(); - execute(this._config.endCallback); } - _move(event) { this._deltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this._deltaX; } - _handleSwipe() { const absDeltaX = Math.abs(this._deltaX); - if (absDeltaX <= SWIPE_THRESHOLD) { return; } - const direction = absDeltaX / this._deltaX; this._deltaX = 0; - if (!direction) { return; } - execute(direction > 0 ? this._config.rightCallback : this._config.leftCallback); } - _initEvents() { if (this._supportPointerEvents) { EventHandler.on(this._element, EVENT_POINTERDOWN, event => this._start(event)); EventHandler.on(this._element, EVENT_POINTERUP, event => this._end(event)); - this._element.classList.add(CLASS_NAME_POINTER_EVENT); } else { EventHandler.on(this._element, EVENT_TOUCHSTART, event => this._start(event)); @@ -1218,24 +1069,24 @@ EventHandler.on(this._element, EVENT_TOUCHEND, event => this._end(event)); } } - _eventIsPointerPenTouch(event) { return this._supportPointerEvents && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH); - } // Static - + } + // Static static isSupported() { return 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0; } - } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): carousel.js + * Bootstrap carousel.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ @@ -1295,6 +1146,7 @@ touch: 'boolean', wrap: 'boolean' }; + /** * Class definition */ @@ -1308,32 +1160,27 @@ this.touchTimeout = null; this._swipeHelper = null; this._indicatorsElement = SelectorEngine.findOne(SELECTOR_INDICATORS, this._element); - this._addEventListeners(); - if (this._config.ride === CLASS_NAME_CAROUSEL) { this.cycle(); } - } // Getters - + } + // Getters static get Default() { return Default$b; } - static get DefaultType() { return DefaultType$b; } - static get NAME() { return NAME$c; - } // Public - + } + // Public next() { this._slide(ORDER_NEXT); } - nextWhenVisible() { // FIXME TODO use `document.visibilityState` // Don't call next when the page isn't visible @@ -1342,101 +1189,80 @@ this.next(); } } - prev() { this._slide(ORDER_PREV); } - pause() { if (this._isSliding) { triggerTransitionEnd(this._element); } - this._clearInterval(); } - cycle() { this._clearInterval(); - this._updateInterval(); - this._interval = setInterval(() => this.nextWhenVisible(), this._config.interval); } - _maybeEnableCycle() { if (!this._config.ride) { return; } - if (this._isSliding) { EventHandler.one(this._element, EVENT_SLID, () => this.cycle()); return; } - this.cycle(); } - to(index) { const items = this._getItems(); - if (index > items.length - 1 || index < 0) { return; } - if (this._isSliding) { EventHandler.one(this._element, EVENT_SLID, () => this.to(index)); return; } - const activeIndex = this._getItemIndex(this._getActive()); - if (activeIndex === index) { return; } - const order = index > activeIndex ? ORDER_NEXT : ORDER_PREV; - this._slide(order, items[index]); } - dispose() { if (this._swipeHelper) { this._swipeHelper.dispose(); } - super.dispose(); - } // Private - + } + // Private _configAfterMerge(config) { config.defaultInterval = config.interval; return config; } - _addEventListeners() { if (this._config.keyboard) { EventHandler.on(this._element, EVENT_KEYDOWN$1, event => this._keydown(event)); } - if (this._config.pause === 'hover') { EventHandler.on(this._element, EVENT_MOUSEENTER$1, () => this.pause()); EventHandler.on(this._element, EVENT_MOUSELEAVE$1, () => this._maybeEnableCycle()); } - if (this._config.touch && Swipe.isSupported()) { this._addTouchEventListeners(); } } - _addTouchEventListeners() { for (const img of SelectorEngine.find(SELECTOR_ITEM_IMG, this._element)) { EventHandler.on(img, EVENT_DRAG_START, event => event.preventDefault()); } - const endCallBack = () => { if (this._config.pause !== 'hover') { return; - } // If it's a touch-enabled device, mouseenter/leave are fired as + } + + // 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 @@ -1444,16 +1270,12 @@ // 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(() => this._maybeEnableCycle(), TOUCHEVENT_COMPAT_WAIT + this._config.interval); }; - const swipeConfig = { leftCallback: () => this._slide(this._directionToOrder(DIRECTION_LEFT)), rightCallback: () => this._slide(this._directionToOrder(DIRECTION_RIGHT)), @@ -1461,68 +1283,51 @@ }; this._swipeHelper = new Swipe(this._element, swipeConfig); } - _keydown(event) { if (/input|textarea/i.test(event.target.tagName)) { return; } - const direction = KEY_TO_DIRECTION[event.key]; - if (direction) { event.preventDefault(); - this._slide(this._directionToOrder(direction)); } } - _getItemIndex(element) { return this._getItems().indexOf(element); } - _setActiveIndicatorElement(index) { if (!this._indicatorsElement) { return; } - const activeIndicator = SelectorEngine.findOne(SELECTOR_ACTIVE, this._indicatorsElement); activeIndicator.classList.remove(CLASS_NAME_ACTIVE$2); activeIndicator.removeAttribute('aria-current'); const newActiveIndicator = SelectorEngine.findOne(`[data-bs-slide-to="${index}"]`, this._indicatorsElement); - if (newActiveIndicator) { newActiveIndicator.classList.add(CLASS_NAME_ACTIVE$2); newActiveIndicator.setAttribute('aria-current', 'true'); } } - _updateInterval() { const element = this._activeElement || this._getActive(); - if (!element) { return; } - const elementInterval = Number.parseInt(element.getAttribute('data-bs-interval'), 10); this._config.interval = elementInterval || this._config.defaultInterval; } - _slide(order, element = null) { if (this._isSliding) { return; } - const activeElement = this._getActive(); - const isNext = order === ORDER_NEXT; const nextElement = element || getNextActiveElement(this._getItems(), activeElement, isNext, this._config.wrap); - if (nextElement === activeElement) { return; } - const nextElementIndex = this._getItemIndex(nextElement); - const triggerEvent = eventName => { return EventHandler.trigger(this._element, eventName, { relatedTarget: nextElement, @@ -1531,25 +1336,19 @@ to: nextElementIndex }); }; - const slideEvent = triggerEvent(EVENT_SLIDE); - if (slideEvent.defaultPrevented) { return; } - if (!activeElement || !nextElement) { // Some weirdness is happening, so we bail - // todo: change tests that use empty divs to avoid this check + // TODO: change tests that use empty divs to avoid this check return; } - const isCycling = Boolean(this._interval); this.pause(); this._isSliding = true; - this._setActiveIndicatorElement(nextElementIndex); - this._activeElement = nextElement; const directionalClassName = isNext ? CLASS_NAME_START : CLASS_NAME_END; const orderClassName = isNext ? CLASS_NAME_NEXT : CLASS_NAME_PREV; @@ -1557,7 +1356,6 @@ reflow(nextElement); activeElement.classList.add(directionalClassName); nextElement.classList.add(directionalClassName); - const completeCallBack = () => { nextElement.classList.remove(directionalClassName, orderClassName); nextElement.classList.add(CLASS_NAME_ACTIVE$2); @@ -1565,113 +1363,89 @@ this._isSliding = false; triggerEvent(EVENT_SLID); }; - this._queueCallback(completeCallBack, activeElement, this._isAnimated()); - if (isCycling) { this.cycle(); } } - _isAnimated() { return this._element.classList.contains(CLASS_NAME_SLIDE); } - _getActive() { return SelectorEngine.findOne(SELECTOR_ACTIVE_ITEM, this._element); } - _getItems() { return SelectorEngine.find(SELECTOR_ITEM, this._element); } - _clearInterval() { if (this._interval) { clearInterval(this._interval); this._interval = null; } } - _directionToOrder(direction) { if (isRTL()) { return direction === DIRECTION_LEFT ? ORDER_PREV : ORDER_NEXT; } - return direction === DIRECTION_LEFT ? ORDER_NEXT : ORDER_PREV; } - _orderToDirection(order) { if (isRTL()) { return order === ORDER_PREV ? DIRECTION_LEFT : DIRECTION_RIGHT; } - return order === ORDER_PREV ? DIRECTION_RIGHT : DIRECTION_LEFT; - } // Static - + } + // Static static jQueryInterface(config) { return this.each(function () { const data = Carousel.getOrCreateInstance(this, config); - if (typeof config === 'number') { data.to(config); return; } - if (typeof config === 'string') { if (data[config] === undefined || config.startsWith('_') || config === 'constructor') { throw new TypeError(`No method named "${config}"`); } - data[config](); } }); } - } + /** * Data API implementation */ - EventHandler.on(document, EVENT_CLICK_DATA_API$5, SELECTOR_DATA_SLIDE, function (event) { - const target = getElementFromSelector(this); - + const target = SelectorEngine.getElementFromSelector(this); if (!target || !target.classList.contains(CLASS_NAME_CAROUSEL)) { return; } - event.preventDefault(); const carousel = Carousel.getOrCreateInstance(target); const slideIndex = this.getAttribute('data-bs-slide-to'); - if (slideIndex) { carousel.to(slideIndex); - carousel._maybeEnableCycle(); - return; } - if (Manipulator.getDataAttribute(this, 'slide') === 'next') { carousel.next(); - carousel._maybeEnableCycle(); - return; } - carousel.prev(); - carousel._maybeEnableCycle(); }); EventHandler.on(window, EVENT_LOAD_DATA_API$3, () => { const carousels = SelectorEngine.find(SELECTOR_DATA_RIDE); - for (const carousel of carousels) { Carousel.getOrCreateInstance(carousel); } }); + /** * jQuery */ @@ -1680,10 +1454,12 @@ /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): collapse.js + * Bootstrap collapse.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ @@ -1715,6 +1491,7 @@ parent: '(null|element)', toggle: 'boolean' }; + /** * Class definition */ @@ -1725,41 +1502,34 @@ this._isTransitioning = false; this._triggerArray = []; const toggleList = SelectorEngine.find(SELECTOR_DATA_TOGGLE$4); - for (const elem of toggleList) { - const selector = getSelectorFromElement(elem); + const selector = SelectorEngine.getSelectorFromElement(elem); const filterElement = SelectorEngine.find(selector).filter(foundElement => foundElement === this._element); - if (selector !== null && filterElement.length) { this._triggerArray.push(elem); } } - this._initializeChildren(); - if (!this._config.parent) { this._addAriaAndCollapsedClass(this._triggerArray, this._isShown()); } - if (this._config.toggle) { this.toggle(); } - } // Getters - + } + // Getters static get Default() { return Default$a; } - static get DefaultType() { return DefaultType$a; } - static get NAME() { return NAME$b; - } // Public - + } + // Public toggle() { if (this._isShown()) { this.hide(); @@ -1767,201 +1537,149 @@ this.show(); } } - show() { if (this._isTransitioning || this._isShown()) { return; } + let activeChildren = []; - let activeChildren = []; // find active children - + // find active children if (this._config.parent) { activeChildren = this._getFirstLevelChildren(SELECTOR_ACTIVES).filter(element => element !== this._element).map(element => Collapse.getOrCreateInstance(element, { toggle: false })); } - if (activeChildren.length && activeChildren[0]._isTransitioning) { return; } - const startEvent = EventHandler.trigger(this._element, EVENT_SHOW$6); - if (startEvent.defaultPrevented) { return; } - for (const activeInstance of activeChildren) { activeInstance.hide(); } - const dimension = this._getDimension(); - this._element.classList.remove(CLASS_NAME_COLLAPSE); - this._element.classList.add(CLASS_NAME_COLLAPSING); - this._element.style[dimension] = 0; - this._addAriaAndCollapsedClass(this._triggerArray, true); - this._isTransitioning = true; - const complete = () => { this._isTransitioning = false; - this._element.classList.remove(CLASS_NAME_COLLAPSING); - this._element.classList.add(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7); - this._element.style[dimension] = ''; EventHandler.trigger(this._element, EVENT_SHOWN$6); }; - const capitalizedDimension = dimension[0].toUpperCase() + dimension.slice(1); const scrollSize = `scroll${capitalizedDimension}`; - this._queueCallback(complete, this._element, true); - this._element.style[dimension] = `${this._element[scrollSize]}px`; } - hide() { if (this._isTransitioning || !this._isShown()) { return; } - const startEvent = EventHandler.trigger(this._element, EVENT_HIDE$6); - if (startEvent.defaultPrevented) { return; } - const dimension = this._getDimension(); - this._element.style[dimension] = `${this._element.getBoundingClientRect()[dimension]}px`; reflow(this._element); - this._element.classList.add(CLASS_NAME_COLLAPSING); - this._element.classList.remove(CLASS_NAME_COLLAPSE, CLASS_NAME_SHOW$7); - for (const trigger of this._triggerArray) { - const element = getElementFromSelector(trigger); - + const element = SelectorEngine.getElementFromSelector(trigger); if (element && !this._isShown(element)) { this._addAriaAndCollapsedClass([trigger], false); } } - this._isTransitioning = true; - const complete = () => { this._isTransitioning = false; - this._element.classList.remove(CLASS_NAME_COLLAPSING); - this._element.classList.add(CLASS_NAME_COLLAPSE); - EventHandler.trigger(this._element, EVENT_HIDDEN$6); }; - this._element.style[dimension] = ''; - this._queueCallback(complete, this._element, true); } + // Private _isShown(element = this._element) { return element.classList.contains(CLASS_NAME_SHOW$7); - } // Private - - + } _configAfterMerge(config) { config.toggle = Boolean(config.toggle); // Coerce string values - config.parent = getElement(config.parent); return config; } - _getDimension() { return this._element.classList.contains(CLASS_NAME_HORIZONTAL) ? WIDTH : HEIGHT; } - _initializeChildren() { if (!this._config.parent) { return; } - const children = this._getFirstLevelChildren(SELECTOR_DATA_TOGGLE$4); - for (const element of children) { - const selected = getElementFromSelector(element); - + const selected = SelectorEngine.getElementFromSelector(element); if (selected) { this._addAriaAndCollapsedClass([element], this._isShown(selected)); } } } - _getFirstLevelChildren(selector) { - const children = SelectorEngine.find(CLASS_NAME_DEEPER_CHILDREN, this._config.parent); // remove children if greater depth - + const children = SelectorEngine.find(CLASS_NAME_DEEPER_CHILDREN, this._config.parent); + // remove children if greater depth return SelectorEngine.find(selector, this._config.parent).filter(element => !children.includes(element)); } - _addAriaAndCollapsedClass(triggerArray, isOpen) { if (!triggerArray.length) { return; } - for (const element of triggerArray) { element.classList.toggle(CLASS_NAME_COLLAPSED, !isOpen); element.setAttribute('aria-expanded', isOpen); } - } // Static - + } + // Static static jQueryInterface(config) { const _config = {}; - if (typeof config === 'string' && /show|hide/.test(config)) { _config.toggle = false; } - return this.each(function () { const data = Collapse.getOrCreateInstance(this, _config); - if (typeof config === 'string') { if (typeof data[config] === 'undefined') { throw new TypeError(`No method named "${config}"`); } - data[config](); } }); } - } + /** * Data API implementation */ - 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(); } - - const selector = getSelectorFromElement(this); - const selectorElements = SelectorEngine.find(selector); - - for (const element of selectorElements) { + for (const element of SelectorEngine.getMultipleElementsFromSelector(this)) { Collapse.getOrCreateInstance(element, { toggle: false }).toggle(); } }); + /** * jQuery */ @@ -2131,7 +1849,7 @@ function getUAString() { var uaData = navigator.userAgentData; - if (uaData != null && uaData.brands) { + if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) { return uaData.brands.map(function (item) { return item.brand + "/" + item.version; }).join(' '); @@ -2419,7 +2137,6 @@ } if (!contains(state.elements.popper, arrowElement)) { - return; } @@ -2450,10 +2167,9 @@ // 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) { + function roundOffsetsByDPR(_ref, win) { var x = _ref.x, y = _ref.y; - var win = window; var dpr = win.devicePixelRatio || 1; return { x: round(x * dpr) / dpr || 0, @@ -2536,7 +2252,7 @@ var _ref4 = roundOffsets === true ? roundOffsetsByDPR({ x: x, y: y - }) : { + }, getWindow(popper)) : { x: x, y: y }; @@ -2562,7 +2278,6 @@ 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), variation: getVariation(state.placement), @@ -2953,7 +2668,6 @@ var popperOffsets = computeOffsets({ reference: referenceClientRect, element: popperRect, - strategy: 'absolute', placement: placement }); var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets)); @@ -3281,7 +2995,6 @@ 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 @@ -3630,8 +3343,7 @@ state.orderedModifiers = orderedModifiers.filter(function (m) { return m.enabled; - }); // Validate the provided modifiers so that the consumer will get warned - + }); runModifierEffects(); return instance.update(); }, @@ -3651,7 +3363,6 @@ // anymore if (!areValidElements(reference, popper)) { - return; } // Store the reference and popper rects to be read by modifiers @@ -3676,7 +3387,6 @@ }); for (var index = 0; index < state.orderedModifiers.length; index++) { - if (state.reset === true) { state.reset = false; index = -1; @@ -3714,7 +3424,6 @@ }; if (!areValidElements(reference, popper)) { - return instance; } @@ -3729,11 +3438,11 @@ // 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; + state.orderedModifiers.forEach(function (_ref) { + var name = _ref.name, + _ref$options = _ref.options, + options = _ref$options === void 0 ? {} : _ref$options, + effect = _ref.effect; if (typeof effect === 'function') { var cleanupFn = effect({ @@ -3774,52 +3483,54 @@ const Popper = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({ __proto__: null, - popperGenerator, - detectOverflow, - createPopperBase: createPopper$2, - createPopper, - createPopperLite: createPopper$1, - top, - bottom, - right, - left, - auto, - basePlacements, - start, - end, - clippingParents, - viewport, - popper, - reference, - variationPlacements, - placements, - beforeRead, - read, - afterRead, - beforeMain, - main, afterMain, - beforeWrite, - write, + afterRead, afterWrite, - modifierPhases, applyStyles: applyStyles$1, arrow: arrow$1, + auto, + basePlacements, + beforeMain, + beforeRead, + beforeWrite, + bottom, + clippingParents, computeStyles: computeStyles$1, + createPopper, + createPopperBase: createPopper$2, + createPopperLite: createPopper$1, + detectOverflow, + end, eventListeners, flip: flip$1, hide: hide$1, + left, + main, + modifierPhases, offset: offset$1, + placements, + popper, + popperGenerator, popperOffsets: popperOffsets$1, - preventOverflow: preventOverflow$1 + preventOverflow: preventOverflow$1, + read, + reference, + right, + start, + top, + variationPlacements, + viewport, + write }, Symbol.toStringTag, { value: 'Module' })); /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): dropdown.js + * Bootstrap dropdown.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ @@ -3877,6 +3588,7 @@ popperConfig: '(null|object|function)', reference: '(string|element|object)' }; + /** * Class definition */ @@ -3886,143 +3598,112 @@ super(element, config); this._popper = null; this._parent = this._element.parentNode; // dropdown wrapper - // todo: v6 revert #37011 & change markup https://getbootstrap.com/docs/5.2/forms/input-group/ - + // TODO: v6 revert #37011 & change markup https://getbootstrap.com/docs/5.3/forms/input-group/ this._menu = SelectorEngine.next(this._element, SELECTOR_MENU)[0] || SelectorEngine.prev(this._element, SELECTOR_MENU)[0] || SelectorEngine.findOne(SELECTOR_MENU, this._parent); this._inNavbar = this._detectNavbar(); - } // Getters - + } + // Getters static get Default() { return Default$9; } - static get DefaultType() { return DefaultType$9; } - static get NAME() { return NAME$a; - } // Public - + } + // Public toggle() { return this._isShown() ? this.hide() : this.show(); } - show() { if (isDisabled(this._element) || this._isShown()) { return; } - const relatedTarget = { relatedTarget: this._element }; const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$5, relatedTarget); - if (showEvent.defaultPrevented) { return; } + this._createPopper(); - this._createPopper(); // If this is a touch-enabled device we add extra + // 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 ('ontouchstart' in document.documentElement && !this._parent.closest(SELECTOR_NAVBAR_NAV)) { for (const element of [].concat(...document.body.children)) { EventHandler.on(element, 'mouseover', noop); } } - this._element.focus(); - 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$5, relatedTarget); } - hide() { if (isDisabled(this._element) || !this._isShown()) { return; } - const relatedTarget = { relatedTarget: this._element }; - this._completeHide(relatedTarget); } - dispose() { if (this._popper) { this._popper.destroy(); } - super.dispose(); } - update() { this._inNavbar = this._detectNavbar(); - if (this._popper) { this._popper.update(); } - } // Private - + } + // Private _completeHide(relatedTarget) { const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$5, relatedTarget); - if (hideEvent.defaultPrevented) { return; - } // If this is a touch-enabled device we remove the extra - // empty mouseover listeners we added for iOS support - + } + // If this is a touch-enabled device we remove the extra + // empty mouseover listeners we added for iOS support if ('ontouchstart' in document.documentElement) { for (const element of [].concat(...document.body.children)) { EventHandler.off(element, 'mouseover', noop); } } - if (this._popper) { this._popper.destroy(); } - this._menu.classList.remove(CLASS_NAME_SHOW$6); - this._element.classList.remove(CLASS_NAME_SHOW$6); - this._element.setAttribute('aria-expanded', 'false'); - Manipulator.removeDataAttribute(this._menu, 'popper'); EventHandler.trigger(this._element, EVENT_HIDDEN$5, relatedTarget); } - _getConfig(config) { config = super._getConfig(config); - 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$a.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`); } - return config; } - _createPopper() { if (typeof Popper === 'undefined') { - throw new TypeError('Bootstrap\'s dropdowns require Popper (https://popper.js.org)'); + throw new TypeError('Bootstrap\'s dropdowns require Popper (https://popper.js.org/docs/v2/)'); } - let referenceElement = this._element; - if (this._config.reference === 'parent') { referenceElement = this._parent; } else if (isElement$1(this._config.reference)) { @@ -4030,65 +3711,49 @@ } else if (typeof this._config.reference === 'object') { referenceElement = this._config.reference; } - const popperConfig = this._getPopperConfig(); - this._popper = createPopper(referenceElement, this._menu, popperConfig); } - _isShown() { return this._menu.classList.contains(CLASS_NAME_SHOW$6); } - _getPlacement() { const parentDropdown = this._parent; - if (parentDropdown.classList.contains(CLASS_NAME_DROPEND)) { return PLACEMENT_RIGHT; } - if (parentDropdown.classList.contains(CLASS_NAME_DROPSTART)) { return PLACEMENT_LEFT; } - if (parentDropdown.classList.contains(CLASS_NAME_DROPUP_CENTER)) { return PLACEMENT_TOPCENTER; } - if (parentDropdown.classList.contains(CLASS_NAME_DROPDOWN_CENTER)) { return PLACEMENT_BOTTOMCENTER; - } // We need to trim the value because custom properties can also include spaces - + } + // We need to trim the value because custom properties can also include spaces const isEnd = getComputedStyle(this._menu).getPropertyValue('--bs-position').trim() === 'end'; - if (parentDropdown.classList.contains(CLASS_NAME_DROPUP)) { return isEnd ? PLACEMENT_TOPEND : PLACEMENT_TOP; } - return isEnd ? PLACEMENT_BOTTOMEND : PLACEMENT_BOTTOM; } - _detectNavbar() { return this._element.closest(SELECTOR_NAVBAR) !== null; } - _getOffset() { const { offset } = this._config; - if (typeof offset === 'string') { return offset.split(',').map(value => Number.parseInt(value, 10)); } - if (typeof offset === 'function') { return popperData => offset(popperData, this._element); } - return offset; } - _getPopperConfig() { const defaultBsPopperConfig = { placement: this._getPlacement(), @@ -4103,121 +3768,101 @@ offset: this._getOffset() } }] - }; // Disable Popper if we have a static display or Dropdown is in Navbar + }; + // Disable Popper if we have a static display or Dropdown is in Navbar if (this._inNavbar || this._config.display === 'static') { - Manipulator.setDataAttribute(this._menu, 'popper', 'static'); // todo:v6 remove - + Manipulator.setDataAttribute(this._menu, 'popper', 'static'); // TODO: v6 remove defaultBsPopperConfig.modifiers = [{ name: 'applyStyles', enabled: false }]; } - - return { ...defaultBsPopperConfig, - ...(typeof this._config.popperConfig === 'function' ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig) + return { + ...defaultBsPopperConfig, + ...execute(this._config.popperConfig, [undefined, defaultBsPopperConfig]) }; } - _selectMenuItem({ key, target }) { const items = SelectorEngine.find(SELECTOR_VISIBLE_ITEMS, this._menu).filter(element => isVisible(element)); - 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 - + } + // 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 getNextActiveElement(items, target, key === ARROW_DOWN_KEY$1, !items.includes(target)).focus(); - } // Static - + } + // Static static jQueryInterface(config) { return this.each(function () { const data = Dropdown.getOrCreateInstance(this, config); - if (typeof config !== 'string') { return; } - if (typeof data[config] === 'undefined') { throw new TypeError(`No method named "${config}"`); } - data[config](); }); } - static clearMenus(event) { if (event.button === RIGHT_MOUSE_BUTTON || event.type === 'keyup' && event.key !== TAB_KEY$1) { return; } - const openToggles = SelectorEngine.find(SELECTOR_DATA_TOGGLE_SHOWN); - for (const toggle of openToggles) { const context = Dropdown.getInstance(toggle); - if (!context || context._config.autoClose === false) { continue; } - const composedPath = event.composedPath(); const isMenuTarget = composedPath.includes(context._menu); - 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 - + } + // Tab navigation through the dropdown menu or events from contained inputs shouldn't close the menu 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; } - const relatedTarget = { relatedTarget: context._element }; - if (event.type === 'click') { relatedTarget.clickEvent = event; } - context._completeHide(relatedTarget); } } - static dataApiKeydownHandler(event) { // If not an UP | DOWN | ESCAPE key => not a dropdown command // If input/textarea && if key is other than ESCAPE => not a dropdown command + const isInput = /input|textarea/i.test(event.target.tagName); const isEscapeEvent = event.key === ESCAPE_KEY$2; const isUpOrDownEvent = [ARROW_UP_KEY$1, ARROW_DOWN_KEY$1].includes(event.key); - if (!isUpOrDownEvent && !isEscapeEvent) { return; } - if (isInput && !isEscapeEvent) { return; } + event.preventDefault(); - event.preventDefault(); // todo: v6 revert #37011 & change markup https://getbootstrap.com/docs/5.2/forms/input-group/ - + // TODO: v6 revert #37011 & change markup https://getbootstrap.com/docs/5.3/forms/input-group/ const getToggleButton = this.matches(SELECTOR_DATA_TOGGLE$3) ? this : SelectorEngine.prev(this, SELECTOR_DATA_TOGGLE$3)[0] || SelectorEngine.next(this, SELECTOR_DATA_TOGGLE$3)[0] || SelectorEngine.findOne(SELECTOR_DATA_TOGGLE$3, event.delegateTarget.parentNode); const instance = Dropdown.getOrCreateInstance(getToggleButton); - if (isUpOrDownEvent) { event.stopPropagation(); instance.show(); - instance._selectMenuItem(event); - return; } - if (instance._isShown()) { // else is escape and we check if it is shown event.stopPropagation(); @@ -4225,13 +3870,12 @@ getToggleButton.focus(); } } - } + /** * 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); @@ -4240,137 +3884,21 @@ event.preventDefault(); Dropdown.getOrCreateInstance(this).toggle(); }); - /** - * jQuery - */ - - defineJQueryPlugin(Dropdown); /** - * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): util/scrollBar.js - * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) - * -------------------------------------------------------------------------- - */ - /** - * Constants - */ - - const SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top'; - const SELECTOR_STICKY_CONTENT = '.sticky-top'; - const PROPERTY_PADDING = 'padding-right'; - const PROPERTY_MARGIN = 'margin-right'; - /** - * Class definition - */ - - class ScrollBarHelper { - constructor() { - this._element = document.body; - } // Public - - - 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); - } - - hide() { - const width = this.getWidth(); - - this._disableOverFlow(); // give padding to element to balance the hidden scrollbar width - - - this._setElementAttributes(this._element, PROPERTY_PADDING, calculatedValue => calculatedValue + width); // trick: We adjust positive paddingRight and negative marginRight to sticky-top elements to keep showing fullwidth - - - this._setElementAttributes(SELECTOR_FIXED_CONTENT, PROPERTY_PADDING, calculatedValue => calculatedValue + width); - - this._setElementAttributes(SELECTOR_STICKY_CONTENT, PROPERTY_MARGIN, calculatedValue => calculatedValue - width); - } - - reset() { - this._resetElementAttributes(this._element, 'overflow'); - - this._resetElementAttributes(this._element, PROPERTY_PADDING); - - this._resetElementAttributes(SELECTOR_FIXED_CONTENT, PROPERTY_PADDING); - - this._resetElementAttributes(SELECTOR_STICKY_CONTENT, PROPERTY_MARGIN); - } - - isOverflowing() { - return this.getWidth() > 0; - } // Private - - - _disableOverFlow() { - this._saveInitialAttribute(this._element, 'overflow'); - - this._element.style.overflow = 'hidden'; - } - - _setElementAttributes(selector, styleProperty, callback) { - const scrollbarWidth = this.getWidth(); - - const manipulationCallBack = element => { - if (element !== this._element && window.innerWidth > element.clientWidth + scrollbarWidth) { - return; - } - - this._saveInitialAttribute(element, styleProperty); - - const calculatedValue = window.getComputedStyle(element).getPropertyValue(styleProperty); - element.style.setProperty(styleProperty, `${callback(Number.parseFloat(calculatedValue))}px`); - }; - - this._applyManipulationCallback(selector, manipulationCallBack); - } - - _saveInitialAttribute(element, styleProperty) { - const actualValue = element.style.getPropertyValue(styleProperty); - - if (actualValue) { - Manipulator.setDataAttribute(element, styleProperty, actualValue); - } - } - - _resetElementAttributes(selector, styleProperty) { - const manipulationCallBack = element => { - const value = Manipulator.getDataAttribute(element, styleProperty); // We only want to remove the property if the value is `null`; the value can also be zero - - if (value === null) { - element.style.removeProperty(styleProperty); - return; - } - - Manipulator.removeDataAttribute(element, styleProperty); - element.style.setProperty(styleProperty, value); - }; - - this._applyManipulationCallback(selector, manipulationCallBack); - } - - _applyManipulationCallback(selector, callBack) { - if (isElement$1(selector)) { - callBack(selector); - return; - } - - for (const sel of SelectorEngine.find(selector, this._element)) { - callBack(sel); - } - } + * jQuery + */ - } + defineJQueryPlugin(Dropdown); /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): util/backdrop.js + * Bootstrap util/backdrop.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ @@ -4386,7 +3914,6 @@ isVisible: true, // if false, we use the backdrop helper without adding any element to the dom rootElement: 'body' // give the choice to place backdrop under different elements - }; const DefaultType$8 = { className: 'string', @@ -4395,6 +3922,7 @@ isVisible: 'boolean', rootElement: '(element|string)' }; + /** * Class definition */ @@ -4405,118 +3933,96 @@ this._config = this._getConfig(config); this._isAppended = false; this._element = null; - } // Getters - + } + // Getters static get Default() { return Default$8; } - static get DefaultType() { return DefaultType$8; } - static get NAME() { return NAME$9; - } // Public - + } + // Public show(callback) { if (!this._config.isVisible) { execute(callback); return; } - this._append(); - const element = this._getElement(); - if (this._config.isAnimated) { reflow(element); } - element.classList.add(CLASS_NAME_SHOW$5); - this._emulateAnimation(() => { execute(callback); }); } - hide(callback) { if (!this._config.isVisible) { execute(callback); return; } - this._getElement().classList.remove(CLASS_NAME_SHOW$5); - this._emulateAnimation(() => { this.dispose(); execute(callback); }); } - dispose() { if (!this._isAppended) { return; } - EventHandler.off(this._element, EVENT_MOUSEDOWN); - this._element.remove(); - this._isAppended = false; - } // Private - + } + // Private _getElement() { if (!this._element) { const backdrop = document.createElement('div'); backdrop.className = this._config.className; - if (this._config.isAnimated) { backdrop.classList.add(CLASS_NAME_FADE$4); } - this._element = backdrop; } - return this._element; } - _configAfterMerge(config) { // use getElement() with the default "body" to get a fresh Element on each instantiation config.rootElement = getElement(config.rootElement); return config; } - _append() { if (this._isAppended) { return; } - const element = this._getElement(); - this._config.rootElement.append(element); - EventHandler.on(element, EVENT_MOUSEDOWN, () => { execute(this._config.clickCallback); }); this._isAppended = true; } - _emulateAnimation(callback) { executeAfterTransition(callback, this._getElement(), this._config.isAnimated); } - } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): util/focustrap.js + * Bootstrap util/focustrap.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ @@ -4532,12 +4038,12 @@ const Default$7 = { autofocus: true, trapElement: null // The element to trap focus inside of - }; const DefaultType$7 = { autofocus: 'boolean', trapElement: 'element' }; + /** * Class definition */ @@ -4548,59 +4054,49 @@ this._config = this._getConfig(config); this._isActive = false; this._lastTabNavDirection = null; - } // Getters - + } + // Getters static get Default() { return Default$7; } - static get DefaultType() { return DefaultType$7; } - static get NAME() { return NAME$8; - } // Public - + } + // Public activate() { if (this._isActive) { return; } - if (this._config.autofocus) { this._config.trapElement.focus(); } - EventHandler.off(document, EVENT_KEY$5); // guard against infinite focus loop - EventHandler.on(document, EVENT_FOCUSIN$2, event => this._handleFocusin(event)); EventHandler.on(document, EVENT_KEYDOWN_TAB, event => this._handleKeydown(event)); this._isActive = true; } - deactivate() { if (!this._isActive) { return; } - this._isActive = false; EventHandler.off(document, EVENT_KEY$5); - } // Private - + } + // Private _handleFocusin(event) { const { trapElement } = this._config; - if (event.target === document || event.target === trapElement || trapElement.contains(event.target)) { return; } - const elements = SelectorEngine.focusableChildren(trapElement); - if (elements.length === 0) { trapElement.focus(); } else if (this._lastTabNavDirection === TAB_NAV_BACKWARD) { @@ -4609,23 +4105,120 @@ elements[0].focus(); } } - _handleKeydown(event) { if (event.key !== TAB_KEY) { return; } - this._lastTabNavDirection = event.shiftKey ? TAB_NAV_BACKWARD : TAB_NAV_FORWARD; } + } + + /** + * -------------------------------------------------------------------------- + * Bootstrap util/scrollBar.js + * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) + * -------------------------------------------------------------------------- + */ + + + /** + * Constants + */ + + const SELECTOR_FIXED_CONTENT = '.fixed-top, .fixed-bottom, .is-fixed, .sticky-top'; + const SELECTOR_STICKY_CONTENT = '.sticky-top'; + const PROPERTY_PADDING = 'padding-right'; + const PROPERTY_MARGIN = 'margin-right'; + + /** + * Class definition + */ + + class ScrollBarHelper { + constructor() { + this._element = document.body; + } + + // Public + 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); + } + hide() { + const width = this.getWidth(); + this._disableOverFlow(); + // give padding to element to balance the hidden scrollbar width + this._setElementAttributes(this._element, PROPERTY_PADDING, calculatedValue => calculatedValue + width); + // trick: We adjust positive paddingRight and negative marginRight to sticky-top elements to keep showing fullwidth + this._setElementAttributes(SELECTOR_FIXED_CONTENT, PROPERTY_PADDING, calculatedValue => calculatedValue + width); + this._setElementAttributes(SELECTOR_STICKY_CONTENT, PROPERTY_MARGIN, calculatedValue => calculatedValue - width); + } + reset() { + this._resetElementAttributes(this._element, 'overflow'); + this._resetElementAttributes(this._element, PROPERTY_PADDING); + this._resetElementAttributes(SELECTOR_FIXED_CONTENT, PROPERTY_PADDING); + this._resetElementAttributes(SELECTOR_STICKY_CONTENT, PROPERTY_MARGIN); + } + isOverflowing() { + return this.getWidth() > 0; + } + // Private + _disableOverFlow() { + this._saveInitialAttribute(this._element, 'overflow'); + this._element.style.overflow = 'hidden'; + } + _setElementAttributes(selector, styleProperty, callback) { + const scrollbarWidth = this.getWidth(); + const manipulationCallBack = element => { + if (element !== this._element && window.innerWidth > element.clientWidth + scrollbarWidth) { + return; + } + this._saveInitialAttribute(element, styleProperty); + const calculatedValue = window.getComputedStyle(element).getPropertyValue(styleProperty); + element.style.setProperty(styleProperty, `${callback(Number.parseFloat(calculatedValue))}px`); + }; + this._applyManipulationCallback(selector, manipulationCallBack); + } + _saveInitialAttribute(element, styleProperty) { + const actualValue = element.style.getPropertyValue(styleProperty); + if (actualValue) { + Manipulator.setDataAttribute(element, styleProperty, actualValue); + } + } + _resetElementAttributes(selector, styleProperty) { + const manipulationCallBack = element => { + const value = Manipulator.getDataAttribute(element, styleProperty); + // We only want to remove the property if the value is `null`; the value can also be zero + if (value === null) { + element.style.removeProperty(styleProperty); + return; + } + Manipulator.removeDataAttribute(element, styleProperty); + element.style.setProperty(styleProperty, value); + }; + this._applyManipulationCallback(selector, manipulationCallBack); + } + _applyManipulationCallback(selector, callBack) { + if (isElement$1(selector)) { + callBack(selector); + return; + } + for (const sel of SelectorEngine.find(selector, this._element)) { + callBack(sel); + } + } } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): modal.js + * Bootstrap modal.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ @@ -4663,6 +4256,7 @@ focus: 'boolean', keyboard: 'boolean' }; + /** * Class definition */ @@ -4676,91 +4270,67 @@ this._isShown = false; this._isTransitioning = false; this._scrollBar = new ScrollBarHelper(); - this._addEventListeners(); - } // Getters - + } + // Getters static get Default() { return Default$6; } - static get DefaultType() { return DefaultType$6; } - static get NAME() { return NAME$7; - } // Public - + } + // Public toggle(relatedTarget) { return this._isShown ? this.hide() : this.show(relatedTarget); } - show(relatedTarget) { if (this._isShown || this._isTransitioning) { return; } - const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$4, { relatedTarget }); - if (showEvent.defaultPrevented) { return; } - this._isShown = true; this._isTransitioning = true; - this._scrollBar.hide(); - document.body.classList.add(CLASS_NAME_OPEN); - this._adjustDialog(); - this._backdrop.show(() => this._showElement(relatedTarget)); } - hide() { if (!this._isShown || this._isTransitioning) { return; } - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$4); - if (hideEvent.defaultPrevented) { return; } - this._isShown = false; this._isTransitioning = true; - this._focustrap.deactivate(); - this._element.classList.remove(CLASS_NAME_SHOW$4); - this._queueCallback(() => this._hideModal(), this._element, this._isAnimated()); } - dispose() { - for (const htmlElement of [window, this._dialog]) { - EventHandler.off(htmlElement, EVENT_KEY$4); - } - + EventHandler.off(window, EVENT_KEY$4); + EventHandler.off(this._dialog, EVENT_KEY$4); this._backdrop.dispose(); - this._focustrap.deactivate(); - super.dispose(); } - handleUpdate() { this._adjustDialog(); - } // Private - + } + // Private _initializeBackDrop() { return new Backdrop({ isVisible: Boolean(this._config.backdrop), @@ -4768,64 +4338,47 @@ isAnimated: this._isAnimated() }); } - _initializeFocusTrap() { return new FocusTrap({ trapElement: this._element }); } - _showElement(relatedTarget) { // try to append dynamic modal if (!document.body.contains(this._element)) { document.body.append(this._element); } - this._element.style.display = 'block'; - this._element.removeAttribute('aria-hidden'); - this._element.setAttribute('aria-modal', true); - this._element.setAttribute('role', 'dialog'); - this._element.scrollTop = 0; const modalBody = SelectorEngine.findOne(SELECTOR_MODAL_BODY, this._dialog); - if (modalBody) { modalBody.scrollTop = 0; } - reflow(this._element); - this._element.classList.add(CLASS_NAME_SHOW$4); - const transitionComplete = () => { if (this._config.focus) { this._focustrap.activate(); } - this._isTransitioning = false; EventHandler.trigger(this._element, EVENT_SHOWN$4, { relatedTarget }); }; - this._queueCallback(transitionComplete, this._dialog, this._isAnimated()); } - _addEventListeners() { EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS$1, event => { if (event.key !== ESCAPE_KEY$1) { return; } - if (this._config.keyboard) { - event.preventDefault(); this.hide(); return; } - this._triggerBackdropTransition(); }); EventHandler.on(window, EVENT_RESIZE$1, () => { @@ -4839,157 +4392,124 @@ if (this._element !== event.target || this._element !== event2.target) { return; } - if (this._config.backdrop === 'static') { this._triggerBackdropTransition(); - return; } - if (this._config.backdrop) { this.hide(); } }); }); } - _hideModal() { this._element.style.display = 'none'; - this._element.setAttribute('aria-hidden', true); - this._element.removeAttribute('aria-modal'); - this._element.removeAttribute('role'); - this._isTransitioning = false; - this._backdrop.hide(() => { document.body.classList.remove(CLASS_NAME_OPEN); - this._resetAdjustments(); - this._scrollBar.reset(); - EventHandler.trigger(this._element, EVENT_HIDDEN$4); }); } - _isAnimated() { return this._element.classList.contains(CLASS_NAME_FADE$3); } - _triggerBackdropTransition() { const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED$1); - if (hideEvent.defaultPrevented) { return; } - const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight; - const initialOverflowY = this._element.style.overflowY; // return if the following background transition hasn't yet completed - + const initialOverflowY = this._element.style.overflowY; + // return if the following background transition hasn't yet completed if (initialOverflowY === 'hidden' || this._element.classList.contains(CLASS_NAME_STATIC)) { return; } - if (!isModalOverflowing) { this._element.style.overflowY = 'hidden'; } - this._element.classList.add(CLASS_NAME_STATIC); - this._queueCallback(() => { this._element.classList.remove(CLASS_NAME_STATIC); - this._queueCallback(() => { this._element.style.overflowY = initialOverflowY; }, this._dialog); }, this._dialog); - this._element.focus(); } + /** * The following methods are used to handle overflowing modals */ - _adjustDialog() { const isModalOverflowing = this._element.scrollHeight > document.documentElement.clientHeight; - const scrollbarWidth = this._scrollBar.getWidth(); - const isBodyOverflowing = scrollbarWidth > 0; - if (isBodyOverflowing && !isModalOverflowing) { const property = isRTL() ? 'paddingLeft' : 'paddingRight'; this._element.style[property] = `${scrollbarWidth}px`; } - if (!isBodyOverflowing && isModalOverflowing) { const property = isRTL() ? 'paddingRight' : 'paddingLeft'; this._element.style[property] = `${scrollbarWidth}px`; } } - _resetAdjustments() { this._element.style.paddingLeft = ''; this._element.style.paddingRight = ''; - } // Static - + } + // Static 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); }); } - } + /** * Data API implementation */ - EventHandler.on(document, EVENT_CLICK_DATA_API$2, SELECTOR_DATA_TOGGLE$2, function (event) { - const target = getElementFromSelector(this); - + const target = SelectorEngine.getElementFromSelector(this); if (['A', 'AREA'].includes(this.tagName)) { event.preventDefault(); } - EventHandler.one(target, EVENT_SHOW$4, showEvent => { if (showEvent.defaultPrevented) { // only register focus restorer if modal will actually get shown return; } - EventHandler.one(target, EVENT_HIDDEN$4, () => { if (isVisible(this)) { this.focus(); } }); - }); // avoid conflict when clicking modal toggler while another one is open + }); + // avoid conflict when clicking modal toggler while another one is open const alreadyOpen = SelectorEngine.findOne(OPEN_SELECTOR$1); - if (alreadyOpen) { Modal.getInstance(alreadyOpen).hide(); } - const data = Modal.getOrCreateInstance(target); data.toggle(this); }); enableDismissTrigger(Modal); + /** * jQuery */ @@ -4998,10 +4518,12 @@ /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): offcanvas.js + * Bootstrap offcanvas.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ @@ -5036,6 +4558,7 @@ keyboard: 'boolean', scroll: 'boolean' }; + /** * Class definition */ @@ -5046,130 +4569,95 @@ this._isShown = false; this._backdrop = this._initializeBackDrop(); this._focustrap = this._initializeFocusTrap(); - this._addEventListeners(); - } // Getters - + } + // Getters static get Default() { return Default$5; } - static get DefaultType() { return DefaultType$5; } - static get NAME() { return NAME$6; - } // Public - + } + // Public toggle(relatedTarget) { return this._isShown ? this.hide() : this.show(relatedTarget); } - show(relatedTarget) { if (this._isShown) { return; } - const showEvent = EventHandler.trigger(this._element, EVENT_SHOW$3, { relatedTarget }); - if (showEvent.defaultPrevented) { return; } - this._isShown = true; - this._backdrop.show(); - if (!this._config.scroll) { new ScrollBarHelper().hide(); } - this._element.setAttribute('aria-modal', true); - this._element.setAttribute('role', 'dialog'); - this._element.classList.add(CLASS_NAME_SHOWING$1); - const completeCallBack = () => { if (!this._config.scroll || this._config.backdrop) { this._focustrap.activate(); } - this._element.classList.add(CLASS_NAME_SHOW$3); - this._element.classList.remove(CLASS_NAME_SHOWING$1); - EventHandler.trigger(this._element, EVENT_SHOWN$3, { relatedTarget }); }; - this._queueCallback(completeCallBack, this._element, true); } - hide() { if (!this._isShown) { return; } - const hideEvent = EventHandler.trigger(this._element, EVENT_HIDE$3); - if (hideEvent.defaultPrevented) { return; } - this._focustrap.deactivate(); - this._element.blur(); - this._isShown = false; - this._element.classList.add(CLASS_NAME_HIDING); - this._backdrop.hide(); - const completeCallback = () => { this._element.classList.remove(CLASS_NAME_SHOW$3, CLASS_NAME_HIDING); - this._element.removeAttribute('aria-modal'); - this._element.removeAttribute('role'); - if (!this._config.scroll) { new ScrollBarHelper().reset(); } - EventHandler.trigger(this._element, EVENT_HIDDEN$3); }; - this._queueCallback(completeCallback, this._element, true); } - dispose() { this._backdrop.dispose(); - this._focustrap.deactivate(); - super.dispose(); - } // Private - + } + // Private _initializeBackDrop() { const clickCallback = () => { if (this._config.backdrop === 'static') { EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED); return; } - this.hide(); - }; // 'static' option will be translated to true, and booleans will keep their value - + }; + // 'static' option will be translated to true, and booleans will keep their value const isVisible = Boolean(this._config.backdrop); return new Backdrop({ className: CLASS_NAME_BACKDROP, @@ -5179,75 +4667,63 @@ clickCallback: isVisible ? clickCallback : null }); } - _initializeFocusTrap() { return new FocusTrap({ trapElement: this._element }); } - _addEventListeners() { EventHandler.on(this._element, EVENT_KEYDOWN_DISMISS, event => { if (event.key !== ESCAPE_KEY) { return; } - - if (!this._config.keyboard) { - EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED); + if (this._config.keyboard) { + this.hide(); return; } - - this.hide(); + EventHandler.trigger(this._element, EVENT_HIDE_PREVENTED); }); - } // Static - + } + // Static static jQueryInterface(config) { return this.each(function () { const data = Offcanvas.getOrCreateInstance(this, config); - 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 */ - EventHandler.on(document, EVENT_CLICK_DATA_API$1, SELECTOR_DATA_TOGGLE$1, function (event) { - const target = getElementFromSelector(this); - + const target = SelectorEngine.getElementFromSelector(this); if (['A', 'AREA'].includes(this.tagName)) { event.preventDefault(); } - if (isDisabled(this)) { return; } - EventHandler.one(target, EVENT_HIDDEN$3, () => { // 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 + }); + // avoid conflict when clicking a toggler of an offcanvas, while another is open const alreadyOpen = SelectorEngine.findOne(OPEN_SELECTOR); - if (alreadyOpen && alreadyOpen !== target) { Offcanvas.getInstance(alreadyOpen).hide(); } - const data = Offcanvas.getOrCreateInstance(target); data.toggle(this); }); @@ -5264,6 +4740,7 @@ } }); enableDismissTrigger(Offcanvas); + /** * jQuery */ @@ -5272,42 +4749,13 @@ /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): util/sanitizer.js + * Bootstrap util/sanitizer.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ - const uriAttributes = 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. - * - * Shout-out to Angular https://github.com/angular/angular/blob/12.2.x/packages/core/src/sanitization/url_sanitizer.ts - */ - - const SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file|sms):|[^#&/:?]*(?:[#/?]|$))/i; - /** - * A pattern that matches safe data URLs. Only matches image, video and audio types. - * - * Shout-out to Angular https://github.com/angular/angular/blob/12.2.x/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; - - const allowedAttribute = (attribute, allowedAttributeList) => { - const attributeName = attribute.nodeName.toLowerCase(); - - if (allowedAttributeList.includes(attributeName)) { - if (uriAttributes.has(attributeName)) { - return Boolean(SAFE_URL_PATTERN.test(attribute.nodeValue) || DATA_URL_PATTERN.test(attribute.nodeValue)); - } - - return true; - } // Check if a regular expression validates the attribute. - - - return allowedAttributeList.filter(attributeRegex => attributeRegex instanceof RegExp).some(regex => regex.test(attributeName)); - }; + // js-docs-start allow-list + const ARIA_ATTRIBUTE_PATTERN = /^aria-[\w-]*$/i; const DefaultAllowlist = { // Global attributes allowed on any supplied element below. '*': ['class', 'dir', 'id', 'lang', 'role', ARIA_ATTRIBUTE_PATTERN], @@ -5317,7 +4765,10 @@ br: [], col: [], code: [], + dd: [], div: [], + dl: [], + dt: [], em: [], hr: [], h1: [], @@ -5341,46 +4792,64 @@ u: [], ul: [] }; + // js-docs-end allow-list + + const uriAttributes = new Set(['background', 'cite', 'href', 'itemtype', 'longdesc', 'poster', 'src', 'xlink:href']); + + /** + * A pattern that recognizes URLs that are safe wrt. XSS in URL navigation + * contexts. + * + * Shout-out to Angular https://github.com/angular/angular/blob/15.2.8/packages/core/src/sanitization/url_sanitizer.ts#L38 + */ + const SAFE_URL_PATTERN = /^(?!javascript:)(?:[a-z0-9+.-]+:|[^&:/?#]*(?:[/?#]|$))/i; + const allowedAttribute = (attribute, allowedAttributeList) => { + const attributeName = attribute.nodeName.toLowerCase(); + if (allowedAttributeList.includes(attributeName)) { + if (uriAttributes.has(attributeName)) { + return Boolean(SAFE_URL_PATTERN.test(attribute.nodeValue)); + } + return true; + } + + // Check if a regular expression validates the attribute. + return allowedAttributeList.filter(attributeRegex => attributeRegex instanceof RegExp).some(regex => regex.test(attributeName)); + }; function sanitizeHtml(unsafeHtml, allowList, sanitizeFunction) { if (!unsafeHtml.length) { return unsafeHtml; } - if (sanitizeFunction && typeof sanitizeFunction === 'function') { return sanitizeFunction(unsafeHtml); } - const domParser = new window.DOMParser(); const createdDocument = domParser.parseFromString(unsafeHtml, 'text/html'); const elements = [].concat(...createdDocument.body.querySelectorAll('*')); - for (const element of elements) { const elementName = element.nodeName.toLowerCase(); - if (!Object.keys(allowList).includes(elementName)) { element.remove(); continue; } - const attributeList = [].concat(...element.attributes); const allowedAttributes = [].concat(allowList['*'] || [], allowList[elementName] || []); - for (const attribute of attributeList) { if (!allowedAttribute(attribute, allowedAttributes)) { element.removeAttribute(attribute.nodeName); } } } - return createdDocument.body.innerHTML; } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): util/template-factory.js + * Bootstrap util/template-factory.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ @@ -5409,6 +4878,7 @@ entry: '(string|element|function|null)', selector: '(string|element)' }; + /** * Class definition */ @@ -5417,65 +4887,53 @@ constructor(config) { super(); this._config = this._getConfig(config); - } // Getters - + } + // Getters static get Default() { return Default$4; } - static get DefaultType() { return DefaultType$4; } - static get NAME() { return NAME$5; - } // Public - + } + // Public getContent() { return Object.values(this._config.content).map(config => this._resolvePossibleFunction(config)).filter(Boolean); } - hasContent() { return this.getContent().length > 0; } - changeContent(content) { this._checkContent(content); - - this._config.content = { ...this._config.content, + this._config.content = { + ...this._config.content, ...content }; return this; } - toHtml() { const templateWrapper = document.createElement('div'); templateWrapper.innerHTML = this._maybeSanitize(this._config.template); - for (const [selector, text] of Object.entries(this._config.content)) { this._setContent(templateWrapper, text, selector); } - const template = templateWrapper.children[0]; - const extraClass = this._resolvePossibleFunction(this._config.extraClass); - if (extraClass) { template.classList.add(...extraClass.split(' ')); } - return template; - } // Private - + } + // Private _typeCheckConfig(config) { super._typeCheckConfig(config); - this._checkContent(config.content); } - _checkContent(arg) { for (const [selector, content] of Object.entries(arg)) { super._typeCheckConfig({ @@ -5484,61 +4942,50 @@ }, DefaultContentType); } } - _setContent(template, content, selector) { const templateElement = SelectorEngine.findOne(selector, template); - if (!templateElement) { return; } - content = this._resolvePossibleFunction(content); - if (!content) { templateElement.remove(); return; } - if (isElement$1(content)) { this._putElementInTemplate(getElement(content), templateElement); - return; } - if (this._config.html) { templateElement.innerHTML = this._maybeSanitize(content); return; } - templateElement.textContent = content; } - _maybeSanitize(arg) { return this._config.sanitize ? sanitizeHtml(arg, this._config.allowList, this._config.sanitizeFn) : arg; } - _resolvePossibleFunction(arg) { - return typeof arg === 'function' ? arg(this) : arg; + return execute(arg, [undefined, this]); } - _putElementInTemplate(element, templateElement) { if (this._config.html) { templateElement.innerHTML = ''; templateElement.append(element); return; } - templateElement.textContent = element.textContent; } - } /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): tooltip.js + * Bootstrap tooltip.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ @@ -5581,7 +5028,7 @@ delay: 0, fallbackPlacements: ['top', 'right', 'bottom', 'left'], html: false, - offset: [0, 0], + offset: [0, 6], placement: 'top', popperConfig: null, sanitize: true, @@ -5610,6 +5057,7 @@ title: '(string|element|function)', trigger: 'string' }; + /** * Class definition */ @@ -5617,176 +5065,131 @@ class Tooltip extends BaseComponent { constructor(element, config) { if (typeof Popper === 'undefined') { - throw new TypeError('Bootstrap\'s tooltips require Popper (https://popper.js.org)'); + throw new TypeError('Bootstrap\'s tooltips require Popper (https://popper.js.org/docs/v2/)'); } + super(element, config); - super(element, config); // Private - + // Private this._isEnabled = true; this._timeout = 0; this._isHovered = null; this._activeTrigger = {}; this._popper = null; this._templateFactory = null; - this._newContent = null; // Protected + this._newContent = null; + // Protected this.tip = null; - this._setListeners(); - if (!this._config.selector) { this._fixTitle(); } - } // Getters - + } + // Getters static get Default() { return Default$3; } - static get DefaultType() { return DefaultType$3; } - static get NAME() { return NAME$4; - } // Public - + } + // Public enable() { this._isEnabled = true; } - disable() { this._isEnabled = false; } - toggleEnabled() { this._isEnabled = !this._isEnabled; } - toggle() { if (!this._isEnabled) { return; } - - this._activeTrigger.click = !this._activeTrigger.click; - if (this._isShown()) { this._leave(); - return; } - this._enter(); } - dispose() { clearTimeout(this._timeout); EventHandler.off(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler); - - if (this.tip) { - this.tip.remove(); - } - if (this._element.getAttribute('data-bs-original-title')) { this._element.setAttribute('title', this._element.getAttribute('data-bs-original-title')); } - this._disposePopper(); - super.dispose(); } - show() { if (this._element.style.display === 'none') { throw new Error('Please use show on visible elements'); } - if (!(this._isWithContent() && this._isEnabled)) { return; } - const showEvent = EventHandler.trigger(this._element, this.constructor.eventName(EVENT_SHOW$2)); const shadowRoot = findShadowRoot(this._element); - const isInTheDom = (shadowRoot || this._element.ownerDocument.documentElement).contains(this._element); - if (showEvent.defaultPrevented || !isInTheDom) { return; - } // todo v6 remove this OR make it optional - - - if (this.tip) { - this.tip.remove(); - this.tip = null; } + // TODO: v6 remove this or make it optional + this._disposePopper(); const tip = this._getTipElement(); - this._element.setAttribute('aria-describedby', tip.getAttribute('id')); - const { container } = this._config; - if (!this._element.ownerDocument.documentElement.contains(this.tip)) { container.append(tip); EventHandler.trigger(this._element, this.constructor.eventName(EVENT_INSERTED)); } + this._popper = this._createPopper(tip); + tip.classList.add(CLASS_NAME_SHOW$2); - if (this._popper) { - this._popper.update(); - } else { - this._popper = this._createPopper(tip); - } - - tip.classList.add(CLASS_NAME_SHOW$2); // If this is a touch-enabled device we add extra + // 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 ('ontouchstart' in document.documentElement) { for (const element of [].concat(...document.body.children)) { EventHandler.on(element, 'mouseover', noop); } } - const complete = () => { EventHandler.trigger(this._element, this.constructor.eventName(EVENT_SHOWN$2)); - if (this._isHovered === false) { this._leave(); } - this._isHovered = false; }; - this._queueCallback(complete, this.tip, this._isAnimated()); } - hide() { if (!this._isShown()) { return; } - const hideEvent = EventHandler.trigger(this._element, this.constructor.eventName(EVENT_HIDE$2)); - if (hideEvent.defaultPrevented) { return; } - const tip = this._getTipElement(); + tip.classList.remove(CLASS_NAME_SHOW$2); - tip.classList.remove(CLASS_NAME_SHOW$2); // If this is a touch-enabled device we remove the extra + // If this is a touch-enabled device we remove the extra // empty mouseover listeners we added for iOS support - if ('ontouchstart' in document.documentElement) { for (const element of [].concat(...document.body.children)) { EventHandler.off(element, 'mouseover', noop); } } - this._activeTrigger[TRIGGER_CLICK] = false; this._activeTrigger[TRIGGER_FOCUS] = false; this._activeTrigger[TRIGGER_HOVER] = false; @@ -5796,135 +5199,107 @@ if (this._isWithActiveTrigger()) { return; } - if (!this._isHovered) { - tip.remove(); + this._disposePopper(); } - this._element.removeAttribute('aria-describedby'); - EventHandler.trigger(this._element, this.constructor.eventName(EVENT_HIDDEN$2)); - - this._disposePopper(); }; - this._queueCallback(complete, this.tip, this._isAnimated()); } - update() { if (this._popper) { this._popper.update(); } - } // Protected - + } + // Protected _isWithContent() { return Boolean(this._getTitle()); } - _getTipElement() { if (!this.tip) { this.tip = this._createTipElement(this._newContent || this._getContentForTemplate()); } - return this.tip; } - _createTipElement(content) { - const tip = this._getTemplateFactory(content).toHtml(); // todo: remove this check on v6 - + const tip = this._getTemplateFactory(content).toHtml(); + // TODO: remove this check in v6 if (!tip) { return null; } - - tip.classList.remove(CLASS_NAME_FADE$2, CLASS_NAME_SHOW$2); // todo: on v6 the following can be achieved with CSS only - + tip.classList.remove(CLASS_NAME_FADE$2, CLASS_NAME_SHOW$2); + // TODO: v6 the following can be achieved with CSS only tip.classList.add(`bs-${this.constructor.NAME}-auto`); const tipId = getUID(this.constructor.NAME).toString(); tip.setAttribute('id', tipId); - if (this._isAnimated()) { tip.classList.add(CLASS_NAME_FADE$2); } - return tip; } - setContent(content) { this._newContent = content; - if (this._isShown()) { this._disposePopper(); - this.show(); } } - _getTemplateFactory(content) { if (this._templateFactory) { this._templateFactory.changeContent(content); } else { - this._templateFactory = new TemplateFactory({ ...this._config, + this._templateFactory = new TemplateFactory({ + ...this._config, // the `content` var has to be after `this._config` // to override config.content in case of popover content, extraClass: this._resolvePossibleFunction(this._config.customClass) }); } - return this._templateFactory; } - _getContentForTemplate() { return { [SELECTOR_TOOLTIP_INNER]: this._getTitle() }; } - _getTitle() { return this._resolvePossibleFunction(this._config.title) || this._element.getAttribute('data-bs-original-title'); - } // Private - + } + // Private _initializeOnDelegatedTarget(event) { return this.constructor.getOrCreateInstance(event.delegateTarget, this._getDelegateConfig()); } - _isAnimated() { return this._config.animation || this.tip && this.tip.classList.contains(CLASS_NAME_FADE$2); } - _isShown() { return this.tip && this.tip.classList.contains(CLASS_NAME_SHOW$2); } - _createPopper(tip) { - const placement = typeof this._config.placement === 'function' ? this._config.placement.call(this, tip, this._element) : this._config.placement; + const placement = execute(this._config.placement, [this, tip, this._element]); const attachment = AttachmentMap[placement.toUpperCase()]; return createPopper(this._element, tip, this._getPopperConfig(attachment)); } - _getOffset() { const { offset } = this._config; - if (typeof offset === 'string') { return offset.split(',').map(value => Number.parseInt(value, 10)); } - if (typeof offset === 'function') { return popperData => offset(popperData, this._element); } - return offset; } - _resolvePossibleFunction(arg) { - return typeof arg === 'function' ? arg.call(this._element) : arg; + return execute(arg, [this._element, this._element]); } - _getPopperConfig(attachment) { const defaultBsPopperConfig = { placement: attachment, @@ -5959,19 +5334,18 @@ } }] }; - return { ...defaultBsPopperConfig, - ...(typeof this._config.popperConfig === 'function' ? this._config.popperConfig(defaultBsPopperConfig) : this._config.popperConfig) + return { + ...defaultBsPopperConfig, + ...execute(this._config.popperConfig, [undefined, defaultBsPopperConfig]) }; } - _setListeners() { const triggers = this._config.trigger.split(' '); - for (const trigger of triggers) { if (trigger === 'click') { EventHandler.on(this._element, this.constructor.eventName(EVENT_CLICK$1), this._config.selector, event => { const context = this._initializeOnDelegatedTarget(event); - + context._activeTrigger[TRIGGER_CLICK] = !(context._isShown() && context._activeTrigger[TRIGGER_CLICK]); context.toggle(); }); } else if (trigger !== TRIGGER_MANUAL) { @@ -5979,182 +5353,151 @@ const eventOut = trigger === TRIGGER_HOVER ? this.constructor.eventName(EVENT_MOUSELEAVE) : this.constructor.eventName(EVENT_FOCUSOUT$1); EventHandler.on(this._element, eventIn, this._config.selector, event => { const context = this._initializeOnDelegatedTarget(event); - context._activeTrigger[event.type === 'focusin' ? TRIGGER_FOCUS : TRIGGER_HOVER] = true; - context._enter(); }); EventHandler.on(this._element, eventOut, this._config.selector, event => { const context = this._initializeOnDelegatedTarget(event); - context._activeTrigger[event.type === 'focusout' ? TRIGGER_FOCUS : TRIGGER_HOVER] = context._element.contains(event.relatedTarget); - context._leave(); }); } } - this._hideModalHandler = () => { if (this._element) { this.hide(); } }; - EventHandler.on(this._element.closest(SELECTOR_MODAL), EVENT_MODAL_HIDE, this._hideModalHandler); } - _fixTitle() { const title = this._element.getAttribute('title'); - if (!title) { return; } - if (!this._element.getAttribute('aria-label') && !this._element.textContent.trim()) { this._element.setAttribute('aria-label', title); } - this._element.setAttribute('data-bs-original-title', title); // DO NOT USE IT. Is only for backwards compatibility - - this._element.removeAttribute('title'); } - _enter() { if (this._isShown() || this._isHovered) { this._isHovered = true; return; } - this._isHovered = true; - this._setTimeout(() => { if (this._isHovered) { this.show(); } }, this._config.delay.show); } - _leave() { if (this._isWithActiveTrigger()) { return; } - this._isHovered = false; - this._setTimeout(() => { if (!this._isHovered) { this.hide(); } }, this._config.delay.hide); } - _setTimeout(handler, timeout) { clearTimeout(this._timeout); this._timeout = setTimeout(handler, timeout); } - _isWithActiveTrigger() { return Object.values(this._activeTrigger).includes(true); } - _getConfig(config) { const dataAttributes = Manipulator.getDataAttributes(this._element); - for (const dataAttribute of Object.keys(dataAttributes)) { if (DISALLOWED_ATTRIBUTES.has(dataAttribute)) { delete dataAttributes[dataAttribute]; } } - - config = { ...dataAttributes, + config = { + ...dataAttributes, ...(typeof config === 'object' && config ? config : {}) }; config = this._mergeConfigObj(config); config = this._configAfterMerge(config); - this._typeCheckConfig(config); - return config; } - _configAfterMerge(config) { config.container = config.container === false ? document.body : getElement(config.container); - if (typeof config.delay === 'number') { config.delay = { show: config.delay, hide: config.delay }; } - if (typeof config.title === 'number') { config.title = config.title.toString(); } - if (typeof config.content === 'number') { config.content = config.content.toString(); } - return config; } - _getDelegateConfig() { const config = {}; - - for (const key in this._config) { - if (this.constructor.Default[key] !== this._config[key]) { - config[key] = this._config[key]; + for (const [key, value] of Object.entries(this._config)) { + if (this.constructor.Default[key] !== value) { + config[key] = value; } } - config.selector = false; - config.trigger = 'manual'; // In the future can be replaced with: + config.trigger = 'manual'; + + // 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; } - _disposePopper() { if (this._popper) { this._popper.destroy(); - this._popper = null; } - } // Static - + if (this.tip) { + this.tip.remove(); + this.tip = null; + } + } + // Static static jQueryInterface(config) { return this.each(function () { const data = Tooltip.getOrCreateInstance(this, config); - if (typeof config !== 'string') { return; } - if (typeof data[config] === 'undefined') { throw new TypeError(`No method named "${config}"`); } - data[config](); }); } - } + /** * jQuery */ - defineJQueryPlugin(Tooltip); /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): popover.js + * Bootstrap popover.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ @@ -6162,16 +5505,19 @@ const NAME$3 = 'popover'; const SELECTOR_TITLE = '.popover-header'; const SELECTOR_CONTENT = '.popover-body'; - const Default$2 = { ...Tooltip.Default, + const Default$2 = { + ...Tooltip.Default, content: '', offset: [0, 8], placement: 'right', template: '', trigger: 'click' }; - const DefaultType$2 = { ...Tooltip.DefaultType, + const DefaultType$2 = { + ...Tooltip.DefaultType, content: '(null|string|element|function)' }; + /** * Class definition */ @@ -6181,63 +5527,58 @@ static get Default() { return Default$2; } - static get DefaultType() { return DefaultType$2; } - static get NAME() { return NAME$3; - } // Overrides - + } + // Overrides _isWithContent() { return this._getTitle() || this._getContent(); - } // Private - + } + // Private _getContentForTemplate() { return { [SELECTOR_TITLE]: this._getTitle(), [SELECTOR_CONTENT]: this._getContent() }; } - _getContent() { return this._resolvePossibleFunction(this._config.content); - } // Static - + } + // Static static jQueryInterface(config) { return this.each(function () { const data = Popover.getOrCreateInstance(this, config); - if (typeof config !== 'string') { return; } - if (typeof data[config] === 'undefined') { throw new TypeError(`No method named "${config}"`); } - data[config](); }); } - } + /** * jQuery */ - defineJQueryPlugin(Popover); /** * -------------------------------------------------------------------------- - * Bootstrap (v5.2.2): scrollspy.js + * Bootstrap scrollspy.js * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE) * -------------------------------------------------------------------------- */ + + /** * Constants */ @@ -6276,14 +5617,16 @@ target: 'element', threshold: 'array' }; + /** * Class definition */ class ScrollSpy extends BaseComponent { constructor(element, config) { - super(element, config); // this._element is the observablesContainer and config.target the menu links wrapper + super(element, config); + // this._element is the observablesContainer and config.target the menu links wrapper this._targetLinks = new Map(); this._observableSections = new Map(); this._rootElement = getComputedStyle(this._element).overflowY === 'visible' ? null : this._element; @@ -6294,87 +5637,75 @@ parentScrollTop: 0 }; this.refresh(); // initialize - } // Getters - + } + // Getters static get Default() { return Default$1; } - static get DefaultType() { return DefaultType$1; } - static get NAME() { return NAME$2; - } // Public - + } + // Public refresh() { this._initializeTargetsAndObservables(); - this._maybeEnableSmoothScroll(); - if (this._observer) { this._observer.disconnect(); } else { this._observer = this._getNewObserver(); } - for (const section of this._observableSections.values()) { this._observer.observe(section); } } - dispose() { this._observer.disconnect(); - super.dispose(); - } // Private - + } + // Private _configAfterMerge(config) { // TODO: on v6 target should be given explicitly & remove the {target: 'ss-target'} case - config.target = getElement(config.target) || document.body; // TODO: v6 Only for backwards compatibility reasons. Use rootMargin only + config.target = getElement(config.target) || document.body; + // TODO: v6 Only for backwards compatibility reasons. Use rootMargin only config.rootMargin = config.offset ? `${config.offset}px 0px -30%` : config.rootMargin; - if (typeof config.threshold === 'string') { config.threshold = config.threshold.split(',').map(value => Number.parseFloat(value)); } - return config; } - _maybeEnableSmoothScroll() { if (!this._config.smoothScroll) { return; - } // unregister any previous listeners - + } + // unregister any previous listeners EventHandler.off(this._config.target, EVENT_CLICK); EventHandler.on(this._config.target, EVENT_CLICK, SELECTOR_TARGET_LINKS, event => { const observableSection = this._observableSections.get(event.target.hash); - if (observableSection) { event.preventDefault(); const root = this._rootElement || window; const height = observableSection.offsetTop - this._element.offsetTop; - if (root.scrollTo) { root.scrollTo({ top: height, behavior: 'smooth' }); return; - } // Chrome 60 doesn't support `scrollTo` - + } + // Chrome 60 doesn't support `scrollTo` root.scrollTop = height; } }); } - _getNewObserver() { const options = { root: this._rootElement, @@ -6382,95 +5713,77 @@ rootMargin: this._config.rootMargin }; return new IntersectionObserver(entries => this._observerCallback(entries), options); - } // The logic of selection - + } + // The logic of selection _observerCallback(entries) { const targetElement = entry => this._targetLinks.get(`#${entry.target.id}`); - const activate = entry => { this._previousScrollData.visibleEntryTop = entry.target.offsetTop; - this._process(targetElement(entry)); }; - const parentScrollTop = (this._rootElement || document.documentElement).scrollTop; const userScrollsDown = parentScrollTop >= this._previousScrollData.parentScrollTop; this._previousScrollData.parentScrollTop = parentScrollTop; - for (const entry of entries) { if (!entry.isIntersecting) { this._activeTarget = null; - this._clearActiveClass(targetElement(entry)); - continue; } - - const entryIsLowerThanPrevious = entry.target.offsetTop >= this._previousScrollData.visibleEntryTop; // if we are scrolling down, pick the bigger offsetTop - + const entryIsLowerThanPrevious = entry.target.offsetTop >= this._previousScrollData.visibleEntryTop; + // if we are scrolling down, pick the bigger offsetTop if (userScrollsDown && entryIsLowerThanPrevious) { - activate(entry); // if parent isn't scrolled, let's keep the first visible item, breaking the iteration - + activate(entry); + // if parent isn't scrolled, let's keep the first visible item, breaking the iteration if (!parentScrollTop) { return; } - continue; - } // if we are scrolling up, pick the smallest offsetTop - + } + // if we are scrolling up, pick the smallest offsetTop if (!userScrollsDown && !entryIsLowerThanPrevious) { activate(entry); } } } - _initializeTargetsAndObservables() { this._targetLinks = new Map(); this._observableSections = new Map(); const targetLinks = SelectorEngine.find(SELECTOR_TARGET_LINKS, this._config.target); - for (const anchor of targetLinks) { // ensure that the anchor has an id and is not disabled if (!anchor.hash || isDisabled(anchor)) { continue; } + const observableSection = SelectorEngine.findOne(decodeURI(anchor.hash), this._element); - const observableSection = SelectorEngine.findOne(anchor.hash, this._element); // ensure that the observableSection exists & is visible - + // ensure that the observableSection exists & is visible if (isVisible(observableSection)) { - this._targetLinks.set(anchor.hash, anchor); - + this._targetLinks.set(decodeURI(anchor.hash), anchor); this._observableSections.set(anchor.hash, observableSection); } } } - _process(target) { if (this._activeTarget === target) { return; } - this._clearActiveClass(this._config.target); - this._activeTarget = target; target.classList.add(CLASS_NAME_ACTIVE$1); - this._activateParents(target); - EventHandler.trigger(this._element, EVENT_ACTIVATE, { relatedTarget: target }); } - _activateParents(target) { // Activate dropdown parents if (target.classList.contains(CLASS_NAME_DROPDOWN_ITEM)) { SelectorEngine.findOne(SELECTOR_DROPDOWN_TOGGLE$1, target.closest(SELECTOR_DROPDOWN)).classList.add(CLASS_NAME_ACTIVE$1); return; } - for (const listGroup of SelectorEngine.parents(target, SELECTOR_NAV_LIST_GROUP)) { // Set triggered links parents as active // With both