Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 65 additions & 1 deletion src/Elastic.Documentation.Site/Htmx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,74 @@
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using System.Reflection;
using System.Text;
using System.Text.Encodings.Web;
using Elastic.Documentation.Extensions;

namespace Elastic.Documentation.Site;

public static class UrlHelper
{
private static readonly KeyValuePair<string, string?>[] VersionParameters = [new("v", Htmx.VersionHash)];

public static string AddVersionParameters(string uri) => AddQueryString(uri, VersionParameters);

/// <summary>
/// Append the given query keys and values to the URI.
/// </summary>
/// <param name="uri">The base URI.</param>
/// <param name="queryString">A collection of name value query pairs to append.</param>
/// <returns>The combined result.</returns>
/// <exception cref="ArgumentNullException"><paramref name="uri"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="queryString"/> is <c>null</c>.</exception>
public static string AddQueryString(
string uri,
IEnumerable<KeyValuePair<string, string?>> queryString)
{
ArgumentNullException.ThrowIfNull(uri);
ArgumentNullException.ThrowIfNull(queryString);

var anchorIndex = uri.IndexOf('#');
var uriToBeAppended = uri.AsSpan();
var anchorText = ReadOnlySpan<char>.Empty;
// If there is an anchor, then the query string must be inserted before its first occurrence.
if (anchorIndex != -1)
{
anchorText = uriToBeAppended.Slice(anchorIndex);
uriToBeAppended = uriToBeAppended.Slice(0, anchorIndex);
}

var queryIndex = uriToBeAppended.IndexOf('?');
var hasQuery = queryIndex != -1;

var sb = new StringBuilder();
_ = sb.Append(uriToBeAppended);
foreach (var parameter in queryString)
{
if (parameter.Value == null)
continue;

_ = sb.Append(hasQuery ? '&' : '?')
.Append(UrlEncoder.Default.Encode(parameter.Key))
.Append('=')
.Append(UrlEncoder.Default.Encode(parameter.Value));
hasQuery = true;
}

_ = sb.Append(anchorText);
return sb.ToString();
}
}

public static class Htmx
{
private static readonly string Version =
Assembly.GetExecutingAssembly().GetCustomAttributes<AssemblyInformationalVersionAttribute>()
.FirstOrDefault()?.InformationalVersion ?? "0.0.0";

public static readonly string VersionHash = ShortId.Create(Version);

public static string GetHxSelectOob(bool hasSameTopLevelGroup) => hasSameTopLevelGroup ? "#content-container,#toc-nav" : "#main-container";
public const string Preload = "mousedown";
public const string HxSwap = "none";
Expand All @@ -24,8 +86,10 @@ public static string GetHxAttributes(
string? hxIndicator = HxIndicator
)
{
var hxGetUrl = UrlHelper.AddVersionParameters(targetUrl);

var attributes = new StringBuilder();
_ = attributes.Append($" hx-get={targetUrl}");
_ = attributes.Append($" hx-get={hxGetUrl}");
_ = attributes.Append($" hx-select-oob={hxSwapOob ?? GetHxSelectOob(hasSameTopLevelGroup)}");
_ = attributes.Append($" hx-swap={hxSwap}");
_ = attributes.Append($" hx-push-url={hxPushUrl}");
Expand Down
2 changes: 1 addition & 1 deletion src/Elastic.Markdown/IO/Navigation/DocumentationGroup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public bool TryGetTableOfContentsTree(Uri source, [NotNullWhen(true)] out TableO
}


[DebuggerDisplay("Toc >{Depth} {FolderName} ({NavigationItems.Count} items)")]
[DebuggerDisplay("Toc >{Depth} {FolderName} {Source} ({NavigationItems.Count} items)")]
public class TableOfContentsTree : DocumentationGroup, IRootNavigationItem<MarkdownFile, INavigationItem>
{
public Uri Source { get; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information

using System.Reflection;
using Elastic.Documentation.Extensions;
using Elastic.Documentation.Site;
using Elastic.Documentation.Site.Navigation;
using Elastic.Markdown.IO;
Expand All @@ -25,7 +27,10 @@ protected override void Write(HtmlRenderer renderer, LinkInline link)
return;
}

var url = link.GetDynamicUrl != null ? link.GetDynamicUrl() : link.Url;
var url = link.GetDynamicUrl?.Invoke() ?? link.Url;
var hxGetUrl = url;
if (hxGetUrl is not null)
hxGetUrl = UrlHelper.AddVersionParameters(hxGetUrl);

var isCrossLink = (link.GetData("isCrossLink") as bool?) == true;
var isHttpLink = url?.StartsWith("http") ?? false;
Expand All @@ -41,7 +46,7 @@ protected override void Write(HtmlRenderer renderer, LinkInline link)
var targetRootNavigation = link.GetData($"Target{nameof(MarkdownFile.NavigationRoot)}") as INodeNavigationItem<INavigationModel, INavigationItem>;
var hasSameTopLevelGroup = !isCrossLink && (currentRootNavigation?.Id == targetRootNavigation?.Id);
_ = renderer.Write(" hx-get=\"");
_ = renderer.WriteEscapeUrl(url);
_ = renderer.WriteEscapeUrl(hxGetUrl);
_ = renderer.Write('"');
_ = renderer.Write($" hx-select-oob=\"{Htmx.GetHxSelectOob(hasSameTopLevelGroup)}\"");
_ = renderer.Write($" hx-swap=\"{Htmx.HxSwap}\"");
Expand Down
2 changes: 2 additions & 0 deletions tests/Elastic.Markdown.Tests/Elastic.Markdown.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="DiffPlex" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
<PackageReference Include="xunit.runner.visualstudio" />
<PackageReference Include="GitHubActionsTestLogger" />
<PackageReference Include="AngleSharp.Diffing" />

<PackageReference Include="FluentAssertions" />
<PackageReference Include="JetBrains.Annotations" />
Expand Down
21 changes: 11 additions & 10 deletions tests/Elastic.Markdown.Tests/Inline/AnchorLinkTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,15 @@ [Sub Requirements](testing/req.md#sub-requirements)
[Fact]
public void GeneratesHtml() =>
// language=html
Html.Should().Contain(
Html.ShouldContainHtml(
"""<p><a href="/docs/testing/req#sub-requirements" hx-get="/docs/testing/req#sub-requirements" hx-select-oob="#content-container,#toc-nav" hx-swap="none" hx-push-url="true" hx-indicator="#htmx-indicator" preload="mousedown">Sub Requirements</a></p>"""
);

[Fact]
public void HxGetContainsVersionAnchor() =>
// language=html
Html.Should().MatchRegex("""hx-get="/docs/testing/req\?v=(.+?)#sub-requirements""");

[Fact]
public void HasNoErrors() => Collector.Diagnostics.Should().HaveCount(0);
}
Expand All @@ -92,7 +97,7 @@ [Sub Requirements](testing/req.md#new-reqs)
[Fact]
public void GeneratesHtml() =>
// language=html
Html.Should().Contain(
Html.ShouldContainHtml(
"""<p><a href="/docs/testing/req#new-reqs" hx-get="/docs/testing/req#new-reqs" hx-select-oob="#content-container,#toc-nav" hx-swap="none" hx-push-url="true" hx-indicator="#htmx-indicator" preload="mousedown">Sub Requirements</a></p>"""
);

Expand All @@ -108,8 +113,7 @@ public class ExternalPageAnchorAutoTitleTests(ITestOutputHelper output) : Anchor
{
[Fact]
public void GeneratesHtml() =>
// language=html
Html.Should().Contain(
Html.ShouldContainHtml(
"""<p><a href="/docs/testing/req#sub-requirements" hx-get="/docs/testing/req#sub-requirements" hx-select-oob="#content-container,#toc-nav" hx-swap="none" hx-push-url="true" hx-indicator="#htmx-indicator" preload="mousedown">Special Requirements &gt; Sub Requirements</a></p>"""
);

Expand All @@ -126,8 +130,7 @@ public class InPageBadAnchorTests(ITestOutputHelper output) : AnchorLinkTestBase
{
[Fact]
public void GeneratesHtml() =>
// language=html
Html.Should().Contain(
Html.ShouldContainHtml(
"""<p><a href="#hello-world2">Hello</a></p>"""
);

Expand All @@ -144,8 +147,7 @@ [Sub Requirements](testing/req.md#sub-requirements2)
{
[Fact]
public void GeneratesHtml() =>
// language=html
Html.Should().Contain(
Html.ShouldContainHtml(
"""<p><a href="/docs/testing/req#sub-requirements2" hx-get="/docs/testing/req#sub-requirements2" hx-select-oob="#content-container,#toc-nav" hx-swap="none" hx-push-url="true" hx-indicator="#htmx-indicator" preload="mousedown">Sub Requirements</a></p>"""
);

Expand All @@ -163,8 +165,7 @@ [Heading inside dropdown](testing/req.md#heading-inside-dropdown)
{
[Fact]
public void GeneratesHtml() =>
// language=html
Html.Should().Contain(
Html.ShouldContainHtml(
"""<a href="/docs/testing/req#heading-inside-dropdown" hx-get="/docs/testing/req#heading-inside-dropdown" hx-select-oob="#content-container,#toc-nav" hx-swap="none" hx-push-url="true" hx-indicator="#htmx-indicator" preload="mousedown">Heading inside dropdown</a>"""
);
[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,8 @@ [Sub Requirements](testing/req.md#hint_ref)
{
[Fact]
public void GeneratesHtml() =>
// language=html
Html.Should().Contain(
"""<p><a href="/docs/testing/req#hint_ref" hx-get="/docs/testing/req#hint_ref" hx-select-oob="#content-container,#toc-nav" hx-swap="none" hx-push-url="true" hx-indicator="#htmx-indicator" preload="mousedown">Sub Requirements</a></p>"""
Html.ShouldContainHtml(
"""<p><a href="/docs/testing/req#hint_ref">Sub Requirements</a></p>"""
);

[Fact]
Expand Down
3 changes: 1 addition & 2 deletions tests/Elastic.Markdown.Tests/Inline/InlineAnchorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,7 @@ [Sub Requirements](testing/req.md#custom-anchor)
{
[Fact]
public void GeneratesHtml() =>
// language=html
Html.Should().Contain(
Html.ShouldContainHtml(
"""<p><a href="/docs/testing/req#custom-anchor" hx-get="/docs/testing/req#custom-anchor" hx-select-oob="#content-container,#toc-nav" hx-swap="none" hx-push-url="true" hx-indicator="#htmx-indicator" preload="mousedown">Sub Requirements</a></p>"""
);

Expand Down
32 changes: 14 additions & 18 deletions tests/Elastic.Markdown.Tests/Inline/InlineLinkTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ public class InlineLinkTests(ITestOutputHelper output) : LinkTestBase(output,
{
[Fact]
public void GeneratesHtml() =>
// language=html
Html.Should().Be(
Html.ShouldContainHtml(
"""<p><a href="/docs/_static/img/observability.png" hx-get="/docs/_static/img/observability.png" hx-select-oob="#main-container" hx-swap="none" hx-push-url="true" hx-indicator="#htmx-indicator" preload="mousedown">Elasticsearch</a></p>"""
);

Expand All @@ -64,8 +63,7 @@ public class LinkToPageTests(ITestOutputHelper output) : LinkTestBase(output,
{
[Fact]
public void GeneratesHtml() =>
// language=html
Html.Should().Contain(
Html.ShouldContainHtml(
"""<p><a href="/docs/testing/req" hx-get="/docs/testing/req" hx-select-oob="#content-container,#toc-nav" hx-swap="none" hx-push-url="true" hx-indicator="#htmx-indicator" preload="mousedown">Requirements</a></p>"""
);

Expand All @@ -84,8 +82,7 @@ public class InsertPageTitleTests(ITestOutputHelper output) : LinkTestBase(outpu
{
[Fact]
public void GeneratesHtml() =>
// language=html
Html.Should().Contain(
Html.ShouldContainHtml(
"""<p><a href="/docs/testing/req" hx-get="/docs/testing/req" hx-select-oob="#content-container,#toc-nav" hx-swap="none" hx-push-url="true" hx-indicator="#htmx-indicator" preload="mousedown">Special Requirements</a></p>"""
);

Expand All @@ -106,8 +103,7 @@ public class RepositoryLinksTest(ITestOutputHelper output) : LinkTestBase(output
{
[Fact]
public void GeneratesHtml() =>
// language=html
Html.Should().Contain(
Html.ShouldContainHtml(
"""<p><a href="/docs/testing/req" hx-get="/docs/testing/req" hx-select-oob="#content-container,#toc-nav" hx-swap="none" hx-push-url="true" hx-indicator="#htmx-indicator" preload="mousedown">test</a></p>"""
);

Expand Down Expand Up @@ -266,16 +262,16 @@ public class CommentedNonExistingLinks2(ITestOutputHelper output) : LinkTestBase
{
[Fact]
public void GeneratesHtml() =>
// language=html
Html.ReplaceLineEndings().TrimEnd().Should().Be("""
<p>Links:</p>
<ul>
<li><a href="/docs/testing/req" hx-get="/docs/testing/req" hx-select-oob="#content-container,#toc-nav" hx-swap="none" hx-push-url="true" hx-indicator="#htmx-indicator" preload="mousedown">Special Requirements</a></li>
</ul>
<ul>
<li><a href="/docs/testing/req" hx-get="/docs/testing/req" hx-select-oob="#content-container,#toc-nav" hx-swap="none" hx-push-url="true" hx-indicator="#htmx-indicator" preload="mousedown">Special Requirements</a></li>
</ul>
""".ReplaceLineEndings());
Html.ShouldMatchHtml(
"""
<p>Links:</p>
<ul>
<li><a href="/docs/testing/req">Special Requirements</a></li>
</ul>
<ul>
<li><a href="/docs/testing/req">Special Requirements</a></li>
</ul>
""");

[Fact]
public void HasErrors() => Collector.Diagnostics.Should().HaveCount(0);
Expand Down
Loading
Loading