From 4369c905cddc104eb37ea8d57eac823d1e584075 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Mon, 16 Nov 2026 15:58:02 +0100 Subject: [PATCH] H4: hero in de eerste HTML (regio, preload), gedeeld datablok met contributors (Offerings byte-identiek), ASF golden files, volledige pijplijntest Co-Authored-By: Claude Sonnet 5.5 --- .../features/hero-module/aidlc-state.md | 2 +- .../construction/h4-injection/code/summary.md | 22 ++ .../HeroInjectionPipelineTests.cs | 202 ++++++++++++ .../HeroOnTheMasterHostTests.cs | 10 + .../Website/CmsDataBlockTransformTests.cs | 97 ++++++ .../Hosting/Website/CmsDataBlock.cs | 68 +++++ .../Website/PrerenderedSiteExtensions.cs | 4 + .../Hosting/Website/SpaSeoExtensions.cs | 4 + .../Golden/SOURCE.md | 8 + .../Golden/host-injection/hero/README.md | 33 ++ .../hero/hero-hostile.expected-preload.html | 1 + .../hero/hero-hostile.expected.html | 1 + .../hero/hero-hostile.input.json | 58 ++++ .../hero/hero-minimal.expected-preload.html | 1 + .../hero/hero-minimal.expected.html | 1 + .../hero/hero-minimal.input.json | 17 ++ .../hero/hero-no-alt.expected-preload.html | 1 + .../hero/hero-no-alt.expected.html | 1 + .../hero/hero-no-alt.input.json | 13 + .../hero/hero-none.expected-preload.html | 1 + .../hero/hero-none.expected.html | 1 + .../host-injection/hero/hero-none.input.json | 1 + .../hero/hero-standard.expected-preload.html | 1 + .../hero/hero-standard.expected.html | 1 + .../hero/hero-standard.input.json | 76 +++++ .../hero/hero-two-lines.expected-preload.html | 1 + .../hero/hero-two-lines.expected.html | 1 + .../hero/hero-two-lines.input.json | 23 ++ .../Golden/host-injection/hero/seed.json | 73 +++++ .../HeroInjectionTests.cs | 287 ++++++++++++++++++ .../HeroServiceTests.cs | 18 ++ .../SlpModularCms.Modules.Hero.Tests.csproj | 4 + src/SlpModularCms.Modules.Hero/HeroModule.cs | 4 + .../Repositories/HeroRepository.cs | 7 +- .../Services/HeroImageService.cs | 32 +- .../Services/HeroInjection.cs | 80 +++++ .../Services/HeroPictureRenderer.cs | 213 +++++++++++++ .../Services/OfferingsHtmlTransformTests.cs | 7 +- .../OfferingsModule.cs | 2 + .../Services/OfferingsDataContributors.cs | 30 ++ .../Services/OfferingsHtmlTransform.cs | 26 +- 41 files changed, 1402 insertions(+), 31 deletions(-) create mode 100644 aidlc-docs/features/hero-module/construction/h4-injection/code/summary.md create mode 100644 src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs create mode 100644 src/SlpModularCms.Core.Tests/Hosting/Website/CmsDataBlockTransformTests.cs create mode 100644 src/SlpModularCms.Core/Hosting/Website/CmsDataBlock.cs create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/SOURCE.md create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/README.md create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected-preload.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.input.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-minimal.expected-preload.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-minimal.expected.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-minimal.input.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-no-alt.expected-preload.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-no-alt.expected.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-no-alt.input.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-none.expected-preload.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-none.expected.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-none.input.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-standard.expected-preload.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-standard.expected.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-standard.input.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-two-lines.expected-preload.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-two-lines.expected.html create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-two-lines.input.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/seed.json create mode 100644 src/SlpModularCms.Modules.Hero.Tests/HeroInjectionTests.cs create mode 100644 src/SlpModularCms.Modules.Hero/Services/HeroInjection.cs create mode 100644 src/SlpModularCms.Modules.Hero/Services/HeroPictureRenderer.cs create mode 100644 src/SlpModularCms.Modules.Offerings/Services/OfferingsDataContributors.cs diff --git a/aidlc-docs/features/hero-module/aidlc-state.md b/aidlc-docs/features/hero-module/aidlc-state.md index 6155f8b..998ffcd 100644 --- a/aidlc-docs/features/hero-module/aidlc-state.md +++ b/aidlc-docs/features/hero-module/aidlc-state.md @@ -53,7 +53,7 @@ - [x] NFR Requirements (construction/nfr-requirements/) - [x] NFR Design (construction/nfr-design/) - [x] Infrastructure Design (media directory; construction/infrastructure-design/) -- [ ] Code Generation - per unit: H0 done, H1 done (image pipeline), H2 to H6 open +- [ ] Code Generation - per unit: H0, H1, H2, H3, H4 done; H5 (admin) and H6 (seed, docs, smoke) open - [ ] Build and Test - EXECUTE ### 🟡 OPERATIONS PHASE - [ ] SKIP (Q19 = B; points go into the joint production checklist) diff --git a/aidlc-docs/features/hero-module/construction/h4-injection/code/summary.md b/aidlc-docs/features/hero-module/construction/h4-injection/code/summary.md new file mode 100644 index 0000000..56aa2b0 --- /dev/null +++ b/aidlc-docs/features/hero-module/construction/h4-injection/code/summary.md @@ -0,0 +1,22 @@ +# H4 Host injection: code summary + +Built 2026-11-16 on `feature/hero-module`. The CI solution filter is green (Core 921, Hero 141, Offerings 212, Availability 171, Identity 145, Api 47, Contact 349, Master 61). The Api tests run the whole chain on the master host with a real MariaDB. + +| Area | What | +|---|---| +| Shared data block | `ICmsDataBlockContributor` and `CmsDataBlockTransform` in Core (`Hosting/Website/CmsDataBlock.cs`), registered next to the injector in both website modes. Keys follow the contributors order (100 offerings, 110 banners, 200 hero); a failing contributor fails the whole block, so the page keeps its baked block | +| Offerings | `OfferingsHtmlTransform` no longer writes the block; `OfferingsDataContributor` and `BannersDataContributor` supply `offerings` and `banners`. The block is byte-for-byte what it was (the existing assertions on shape, escaping and the ASF pipeline test pass unchanged apart from calling the new transform) | +| Hero regions | `HeroPictureRenderer` (pure) writes the `` region and the preload links exactly as the ASF golden files; `HeroHtmlTransform` fills `` and `` and leaves the page alone when the hero is unusable | +| Hero data | `HeroDataContributor` adds `hero` (the full public hero with all slides, or null) | +| Missing files | `HeroPageModel` checks that the files of the first slide exist in the media store; when they do not, region, preload and data are left baked (no broken first image) | +| Golden files | ASF commit 13f78c4 copied to `Hero.Tests/Golden/host-injection/hero` (6 cases, region and preload byte-exact) | +| Tests | golden files, renderer details (focus, no tall, no AVIF, first usable slide, encoding, property test that nothing breaks out of the HTML), transform behaviour, page model (files present or missing), data block order and escaping (Core), and a full pipeline test on the master host: no hero leaves the baked page and `hero: null`; a hero made through the services shows in the first HTML with the preload and the data block (same JSON as `GET /api/v1/hero`), every variant address is served immutable, 304 works, switching the hero off and losing the media directory both restore the baked page | + +## Found and fixed while building + +- The EF MySQL provider cannot translate `IN` on a Guid list parameter (found only by the real-database test; the in-memory tests hid it): the images of a save are now read and filtered in memory (a few dozen rows). +- Re-uploading a photo whose row exists but whose files were lost (a restored database without the media directory) now repairs the files instead of returning the broken image. + +## Not yet + +The admin screens (H5), the seed script, the smoke test and the docs (H6), the LCP measurement on the test hosts (needs the sites with the markers). diff --git a/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs b/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs new file mode 100644 index 0000000..d0a30df --- /dev/null +++ b/src/SlpModularCms.Api.Tests/HeroInjectionPipelineTests.cs @@ -0,0 +1,202 @@ +using System.Net; +using System.Text.Json; +using FluentAssertions; +using ImageMagick; +using Microsoft.AspNetCore.Hosting; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using SlpModularCms.Modules.Hero.Data; +using SlpModularCms.Modules.Hero.Models; +using SlpModularCms.Modules.Hero.Services; + +namespace SlpModularCms.Api.Tests; + +/// The hero on the master host with Andrea Slop Fotografie's settings: a prerendered page with the hero markers, a media directory and a real database. +public sealed class HeroInjectionFactory : AsfVariantFactory, IDisposable +{ + public string WebRoot { get; } = Path.Combine(Path.GetTempPath(), "slp-hero-web-" + Guid.NewGuid().ToString("N")); + public string MediaDirectory { get; } = Path.Combine(Path.GetTempPath(), "slp-hero-media-" + Guid.NewGuid().ToString("N")); + + public HeroInjectionFactory() => Directory.CreateDirectory(Path.Combine(WebRoot, "web")); + + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + base.ConfigureWebHost(builder); + builder.UseWebRoot(WebRoot); + builder.ConfigureAppConfiguration((_, config) => + config.AddInMemoryCollection(new Dictionary { ["Media:Directory"] = MediaDirectory, ["Website:PublicBaseUrl"] = "https://test.andreaslop.nl" })); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + if (disposing) + { + foreach (var directory in new[] { WebRoot, MediaDirectory }) + { + if (Directory.Exists(directory)) Directory.Delete(directory, recursive: true); + } + } + } +} + +[Collection("HeroDatabase")] +public class HeroInjectionPipelineTests : IClassFixture +{ + private const string Page = + "baked preload" + + "" + + "baked hero"; + + private readonly HeroInjectionFactory _factory; + + public HeroInjectionPipelineTests(HeroInjectionFactory factory) + { + _factory = factory; + File.WriteAllText(Path.Combine(factory.WebRoot, "web", "hero.html"), Page); + } + + private async Task InScope(Func> action) + { + _ = _factory.CreateClient(); // starts the host, migrates and runs the start-up checks + await using var scope = _factory.Services.CreateAsyncScope(); + return await action(scope.ServiceProvider); + } + + private static byte[] Photo() + { + using var image = new MagickImage(MagickColors.Red, 1600, 1067); + using var blue = new MagickImage(MagickColors.Blue, 800, 1067); + image.Composite(blue, 800, 0, CompositeOperator.Over); + using var stream = new MemoryStream(); + image.Write(stream, MagickFormat.Jpeg); + return stream.ToArray(); + } + + private static string DataBlock(string body) + { + const string open = "", start, StringComparison.Ordinal)]; + } + + [Fact] + public async Task AHeroMadeThroughTheModule_ShowsInTheFirstHtml_AndItsImagesAreServed() + { + try + { + await RunAsync(); + } + finally + { + await ClearHeroes(); + } + } + + private async Task ClearHeroes() + => await InScope(async sp => + { + var db = sp.GetRequiredService(); + db.Heroes.RemoveRange(await db.Heroes.ToListAsync()); + await db.SaveChangesAsync(); + return 0; + }); + + private async Task RunAsync() + { + var client = _factory.CreateClient(); + var caller = Guid.NewGuid(); + + // Clean slate: the database is shared with other tests. + await InScope(async sp => + { + var db = sp.GetRequiredService(); + db.Heroes.RemoveRange(await db.Heroes.ToListAsync()); + await db.SaveChangesAsync(); + return 0; + }); + + // Without a hero the page stays as it was built, and the data block says so. + var before = await client.GetAsync("/hero"); + before.StatusCode.Should().Be(HttpStatusCode.OK); + var beforeBody = await before.Content.ReadAsStringAsync(); + beforeBody.Should().Contain("baked hero").And.Contain("baked preload"); + JsonDocument.Parse(DataBlock(beforeBody)).RootElement.GetProperty("hero").ValueKind.Should().Be(JsonValueKind.Null); + var etagBefore = before.Headers.ETag!.Tag; + + // Upload a photo and publish a hero through the module's services. + var image = await InScope(sp => sp.GetRequiredService().UploadAsync(new MemoryStream(Photo()), Photo().Length, caller, default)); + await InScope(async sp => await sp.GetRequiredService().SaveAsync( + new HeroSaveRequest("Andrea Slop", "Lifestyle fotograaf · Huizen", null, "slideshow", [new HeroButtonRequest("Lees meer", "/over-mij")], true, null, null, + [new HeroSlideRequest(null, Guid.Parse(image.Id), "Zwangerschapsfoto in de duinen")]), caller, default)); + + var live = await client.GetAsync("/hero"); + var body = await live.Content.ReadAsStringAsync(); + live.Headers.ETag!.Tag.Should().NotBe(etagBefore); + body.Should().NotContain("baked hero").And.NotContain("baked preload"); + body.Should().Contain("Andrea Slop"); + body.Should().Contain("Lees meer"); + body.Should().Contain(" p.Name).Should().Equal("siteUrl", "offerings", "banners", "hero"); + var api = JsonDocument.Parse(await client.GetStringAsync("/api/v1/hero")).RootElement; + System.Text.Json.Nodes.JsonNode.DeepEquals(System.Text.Json.Nodes.JsonNode.Parse(data.GetProperty("hero").GetRawText()), System.Text.Json.Nodes.JsonNode.Parse(api.GetRawText())) + .Should().BeTrue("the data block carries the same JSON as GET /api/v1/hero"); + + // Every address in the page is served by the host: immutable, same origin. + var src = api.GetProperty("slides")[0].GetProperty("image").GetProperty("src").GetString()!; + body.Should().Contain($"src=\"{src}\""); + foreach (var url in api.GetProperty("slides")[0].GetProperty("image").GetProperty("variants").EnumerateArray().Select(v => v.GetProperty("url").GetString()!)) + { + var media = await client.GetAsync(url); + media.StatusCode.Should().Be(HttpStatusCode.OK, url); + media.Headers.CacheControl!.ToString().Should().Be("public, max-age=31536000, immutable"); + (await media.Content.ReadAsByteArrayAsync()).Length.Should().BeGreaterThan(100); + } + + // A matching ETag is a 304. + var conditional = new HttpRequestMessage(HttpMethod.Get, "/hero"); + conditional.Headers.IfNoneMatch.Add(live.Headers.ETag); + (await client.SendAsync(conditional)).StatusCode.Should().Be(HttpStatusCode.NotModified); + + // Switching the hero off puts the baked page back at once. + await InScope(async sp => + { + var service = sp.GetRequiredService(); + var current = await service.GetAsync(default); + await service.SaveAsync(new HeroSaveRequest(current.Title, current.Tagline, current.Lead, current.Display, [], IsActive: false, null, null, + current.Slides.Select(s => new HeroSlideRequest(Guid.Parse(s.Id), Guid.Parse(s.ImageId), s.Alt)).ToList()), caller, default); + return 0; + }); + var off = await client.GetStringAsync("/hero"); + off.Should().Contain("baked hero").And.Contain("baked preload").And.NotContain("cms-hero-picture"); + + // And a media directory that lost its files leaves the baked hero too (no broken first image). + await InScope(async sp => + { + var service = sp.GetRequiredService(); + var current = await service.GetAsync(default); + await service.SaveAsync(new HeroSaveRequest(current.Title, current.Tagline, current.Lead, current.Display, [], IsActive: true, null, null, + current.Slides.Select(s => new HeroSlideRequest(Guid.Parse(s.Id), Guid.Parse(s.ImageId), s.Alt)).ToList()), caller, default); + return 0; + }); + (await client.GetStringAsync("/hero")).Should().Contain("cms-hero-picture"); + Directory.Delete(Path.Combine(_factory.MediaDirectory, "hero"), recursive: true); + await InScope(sp => { sp.GetRequiredService().Invalidate(); return Task.FromResult(0); }); + var missing = await client.GetStringAsync("/hero"); + missing.Should().Contain("baked hero").And.NotContain("cms-hero-picture"); + + // Clean up for the other tests. + await InScope(async sp => + { + var db = sp.GetRequiredService(); + db.Heroes.RemoveRange(await db.Heroes.ToListAsync()); + await db.SaveChangesAsync(); + return 0; + }); + } +} diff --git a/src/SlpModularCms.Api.Tests/HeroOnTheMasterHostTests.cs b/src/SlpModularCms.Api.Tests/HeroOnTheMasterHostTests.cs index 654e8a1..ba67b68 100644 --- a/src/SlpModularCms.Api.Tests/HeroOnTheMasterHostTests.cs +++ b/src/SlpModularCms.Api.Tests/HeroOnTheMasterHostTests.cs @@ -7,6 +7,7 @@ using SlpModularCms.Modules.Hero.Data; namespace SlpModularCms.Api.Tests; /// The Hero module on the real master host and the real, migrated database. +[Collection("HeroDatabase")] public class HeroOnTheMasterHostTests : IClassFixture { private readonly ApiWebApplicationFactory _factory; @@ -25,6 +26,15 @@ public class HeroOnTheMasterHostTests : IClassFixture [Fact] public async Task WithoutAHero_ThePublicEndpointAnswers204_WithTheShortCache() { + // The database is shared with other tests (and earlier runs): start without a hero. + _ = _factory.CreateClient(); + using (var scope = _factory.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.Heroes.RemoveRange(await db.Heroes.ToListAsync()); + await db.SaveChangesAsync(); + } + var response = await _factory.CreateClient().GetAsync("/api/v1/hero"); response.StatusCode.Should().Be(HttpStatusCode.NoContent); diff --git a/src/SlpModularCms.Core.Tests/Hosting/Website/CmsDataBlockTransformTests.cs b/src/SlpModularCms.Core.Tests/Hosting/Website/CmsDataBlockTransformTests.cs new file mode 100644 index 0000000..989be86 --- /dev/null +++ b/src/SlpModularCms.Core.Tests/Hosting/Website/CmsDataBlockTransformTests.cs @@ -0,0 +1,97 @@ +using System.Text.Json; +using FluentAssertions; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using SlpModularCms.Core.Hosting.Website; + +namespace SlpModularCms.Core.Tests.Hosting.Website; + +public class CmsDataBlockTransformTests +{ + private static readonly HtmlTransformContext Context = new("https://test.example.nl"); + private const string Open = "", start, StringComparison.Ordinal)]).RootElement; + } + + [Theory] + [InlineData("", true)] + [InlineData("

nothing

", false)] + [InlineData("", false)] + public void Wants_OnlyPagesWithTheDataMarker(string html, bool expected) + => new CmsDataBlockTransform([]).Wants(html).Should().Be(expected); + + [Fact] + public async Task TheKeys_FollowTheOrderOfTheContributors_AfterTheSiteUrl() + { + var transform = new CmsDataBlockTransform([Contributor("hero", 200, new { a = 1 }), Contributor("offerings", 100, new[] { 1, 2 }), Contributor("banners", 110, new { top = (string?)null })]); + + var html = await transform.ApplyAsync("", Context, default); + + html.Should().StartWith("" + Open).And.EndWith("").And.NotContain("baked"); + var data = Data(html); + data.EnumerateObject().Select(p => p.Name).Should().Equal("siteUrl", "offerings", "banners", "hero"); + data.GetProperty("siteUrl").GetString().Should().Be("https://test.example.nl"); + data.GetProperty("offerings").GetRawText().Should().Be("[1,2]"); + data.GetProperty("banners").GetProperty("top").ValueKind.Should().Be(JsonValueKind.Null); + } + + [Fact] + public async Task ANullValue_IsWrittenAsNull_SoTheWebsiteKeepsItsBakedVersion() + { + var html = await new CmsDataBlockTransform([Contributor("hero", 200, null)]).ApplyAsync("", Context, default); + + Data(html).GetProperty("hero").ValueKind.Should().Be(JsonValueKind.Null); + } + + [Fact] + public async Task TheValues_UseTheCamelCaseShapeOfThePublicApi() + { + var html = await new CmsDataBlockTransform([Contributor("x", 1, new { SomeName = "a", Nested = new { InnerValue = (int?)null } })]).ApplyAsync("", Context, default); + + html.Should().Contain("\"someName\":\"a\"").And.Contain("\"innerValue\":null"); + } + + [Fact] + public async Task TheBlock_CannotCloseTheScriptElement() + { + var html = await new CmsDataBlockTransform([Contributor("x", 1, new { text = " & \u2028" })]).ApplyAsync("", Context, default); + + var inner = html[Open.Length..^"".Length]; + inner.Should().NotContain("<").And.NotContain(">").And.NotContain("&").And.NotContain("\u2028"); + JsonDocument.Parse(inner).RootElement.GetProperty("x").GetProperty("text").GetString().Should().Be(" & \u2028"); + } + + [Fact] + public async Task AFailingContributor_FailsTheWholeBlock_SoThePageKeepsItsBakedBlock() + { + var failing = Substitute.For(); + failing.Key.Returns("hero"); + failing.Order.Returns(200); + failing.GetAsync(default!, default).ThrowsAsyncForAnyArgs(new InvalidOperationException("boom")); + + var act = async () => await new CmsDataBlockTransform([Contributor("offerings", 100, new[] { 1 }), failing]).ApplyAsync("", Context, default); + + await act.Should().ThrowAsync(); + } + + [Fact] + public async Task WithoutContributors_TheBlockHoldsTheSiteUrlOnly() + { + var html = await new CmsDataBlockTransform([]).ApplyAsync("", Context, default); + + Data(html).EnumerateObject().Select(p => p.Name).Should().Equal("siteUrl"); + } +} diff --git a/src/SlpModularCms.Core/Hosting/Website/CmsDataBlock.cs b/src/SlpModularCms.Core/Hosting/Website/CmsDataBlock.cs new file mode 100644 index 0000000..3eb7e82 --- /dev/null +++ b/src/SlpModularCms.Core/Hosting/Website/CmsDataBlock.cs @@ -0,0 +1,68 @@ +using System.Buffers; +using System.Text; +using System.Text.Json; +using Microsoft.Extensions.Logging; + +namespace SlpModularCms.Core.Hosting.Website; + +/// +/// A module's key in the data block that the host writes into a website page (<script type="application/json" +/// id="cms-data"> after the <!--CMS:DATA--> marker). The website reads this block instead of +/// fetching, so the same data that the public API answers is in the first HTML. Contributors are scoped. +/// +public interface ICmsDataBlockContributor +{ + /// The property name in the block (offerings, banners, hero). + string Key { get; } + + /// Fixes the order of the keys in the block: lower first (100 offerings, 110 banners, 200 hero). + int Order { get; } + + /// The value to write for ; null is written as JSON null (the website then keeps what it was built with). + Task GetAsync(HtmlTransformContext context, CancellationToken cancellationToken); +} + +/// +/// Owns the <!--CMS:DATA--> marker: composes one block from siteUrl and every registered +/// , so modules never edit each other's output. If one contributor fails the whole +/// block stays as it was built: a half-filled block would mislead the website (fail-open for the block as a whole). +/// +public sealed class CmsDataBlockTransform(IEnumerable contributors) : IHtmlPageTransform +{ + public const string Marker = "CMS:DATA"; + public const string BlockId = "cms-data"; + + // The shape of the public API answers: camelCase, nulls written. + private static readonly JsonSerializerOptions ApiJson = new(JsonSerializerDefaults.Web); + + public bool Wants(string html) => html.Contains("", StringComparison.Ordinal); + + public async Task ApplyAsync(string html, HtmlTransformContext context, CancellationToken cancellationToken) + { + var buffer = new ArrayBufferWriter(); + await using (var writer = new Utf8JsonWriter(buffer)) + { + writer.WriteStartObject(); + writer.WriteString("siteUrl", context.SiteUrl); + foreach (var contributor in contributors.OrderBy(c => c.Order).ThenBy(c => c.Key, StringComparer.Ordinal)) + { + var value = await contributor.GetAsync(context, cancellationToken); + writer.WritePropertyName(contributor.Key); + if (value is null) + { + writer.WriteNullValue(); + } + else + { + JsonSerializer.Serialize(writer, value, value.GetType(), ApiJson); + } + } + + writer.WriteEndObject(); + } + + var json = Encoding.UTF8.GetString(buffer.WrittenSpan); + var block = ""; + return HtmlMarkerEditor.ReplaceDataBlock(html, Marker, BlockId, block); + } +} diff --git a/src/SlpModularCms.Core/Hosting/Website/PrerenderedSiteExtensions.cs b/src/SlpModularCms.Core/Hosting/Website/PrerenderedSiteExtensions.cs index 94a6fbc..1ae1df3 100644 --- a/src/SlpModularCms.Core/Hosting/Website/PrerenderedSiteExtensions.cs +++ b/src/SlpModularCms.Core/Hosting/Website/PrerenderedSiteExtensions.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.ResponseCompression; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; namespace SlpModularCms.Core.Hosting.Website; @@ -40,6 +41,9 @@ public static class PrerenderedSiteExtensions services.AddSingleton(); services.AddSingleton(provider => provider.GetRequiredService()); + // The shared CMS data block of the pages (siteUrl plus what each module contributes). + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + // Presence of the marker switches on the full security-header set for website responses. services.AddSingleton(); diff --git a/src/SlpModularCms.Core/Hosting/Website/SpaSeoExtensions.cs b/src/SlpModularCms.Core/Hosting/Website/SpaSeoExtensions.cs index 8c8948f..20c6844 100644 --- a/src/SlpModularCms.Core/Hosting/Website/SpaSeoExtensions.cs +++ b/src/SlpModularCms.Core/Hosting/Website/SpaSeoExtensions.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using Microsoft.Net.Http.Headers; @@ -24,6 +25,9 @@ public static class SpaSeoExtensions services.AddOptions().Bind(configuration.GetSection(WebsiteOptions.SectionName)); services.AddSingleton(); services.AddSingleton(provider => provider.GetRequiredService()); + + // The shared CMS data block of the pages (siteUrl plus what each module contributes). + services.TryAddEnumerable(ServiceDescriptor.Scoped()); return services; } diff --git a/src/SlpModularCms.Modules.Hero.Tests/Golden/SOURCE.md b/src/SlpModularCms.Modules.Hero.Tests/Golden/SOURCE.md new file mode 100644 index 0000000..f7b15be --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/Golden/SOURCE.md @@ -0,0 +1,8 @@ +# Golden files of the website build (ASF): hero + +`host-injection/hero/` is a copy of `web/contract/host-injection/hero` of the Andrea Slop Fotografie website repository, +ASF commit `13f78c4` (branch `feature/hero-module`). It is the contract for the plain HTML the CMS host writes between the +CMS markers `CMS:HERO-HTML` (the hero) and `CMS:HERO-PRELOAD` (the preload links in the head); see +`host-injection/hero/README.md` for the rules. `HeroGoldenTests` runs `HeroPictureRenderer` against every input/expected +pair. When the website changes the contract it sends new files and the commit; replace the folder and note the new commit +here. `seed.json` is the seed data of the ASF test CMS (used by `scripts/Seed-Hero.ps1`). diff --git a/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/README.md b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/README.md new file mode 100644 index 0000000..43a989e --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/README.md @@ -0,0 +1,33 @@ +# Hero contract (ASF site and CMS host) + +Golden files for the hero regions that the CMS host fills, model B (decided 2026-11-16): the host cuts a `wide` (3:2) and a `tall` (4:5) variant per photo around the focus point, and the site uses ``. Same idea as the packages (`../README.md`): for every `NAME.input.json` the host's template must give exactly `NAME.expected.html` (between `` and ``) and `NAME.expected-preload.html` (between `` and `` in the head). The file ends with one newline that is not part of the HTML. The ASF repo tests its own implementation (`src/lib/hero.ts`, `src/lib/heroHtml.ts`) against the same files; to change the contract, change the code and run `UPDATE_GOLDEN=1 pnpm test src/lib/heroHtml.test.ts`, then send the new files to the CMS session. The ASF commit is in `git log -1 -- web/contract/host-injection/hero`. + +## Input + +The answer of `GET /api/v1/hero` (an object). A 204 (no hero) is `null`: the output is empty and the baked hero stays. + +## Rules + +1. Usable hero: an object with a non-empty `title` (trimmed) and at least one usable slide; otherwise both outputs are empty strings (fail open: the baked page stays). +2. A slide is kept when: `id` is non-empty; `image.src` is a path of our host (starts with one `/`, not `//`, no backslash); `image.width` and `image.height` are whole numbers above 0; and it has an `alt` (non-empty after trimming) or `decorative` is `true`. Other slides are skipped. Order is the given order. Only the FIRST kept slide is written; the client takes the rest from the data block. +3. A decorative slide writes `alt=""`. +4. Variants: kept when `ratio`, `type` and `url` are non-empty, `width` is a whole number above 0 and `url` is a path of our host. Only `image/webp` variants are used here (a preload cannot say "AVIF if supported", so a second format would be fetched twice). `wide` variants make the `img` `srcset`, `tall` variants the `source` `srcset`; sorted by width ascending, written `URL WIDTHw`, joined by `, `. +5. `focus` (`x` and `y` both between 0 and 1) is written as `style="object-position:X% Y%"` on the `img` (percentages without trailing zeros, at most two decimals); without a valid focus there is no `style`. +6. Buttons: at most 2 (the first two valid ones). A button is valid with a non-empty `label` and a `target` that is an anchor (`#name`), a path (one leading `/`, not `//`, no backslash) or an `https://` address that parses. `lead` and `display` are not written in the HTML. +7. Escape every text and attribute (`&` `&`, `<` `<`, `>` `>`, `"` `"`, `'` `'`). A new line in the title becomes `
` (after escaping). + +## Output, HERO-HTML + +`` + (when a `tall` webp variant exists: ``) + `ALT` + `` + `

` + (tagline: `TAGLINE `) + `TITLE

` + (when there are buttons: `

` + `LABEL`... + `

`). + +`src` is `image.src`; `W` and `H` are `image.width` and `image.height`. Selection is by orientation, not width, because the hero is as high as the screen. + +## Output, HERO-PRELOAD + +With a `tall` variant: `` followed by the landscape link with `media="(orientation: landscape)"`. The landscape link has `imagesrcset="WIDE" imagesizes="100vw"`, or `href="SRC"` when there is no wide set. Without a tall variant there is one link without `media`. The `srcset`, `sizes` and `media` values are byte for byte the same as in the picture; the golden files check this. + +## Files + +`hero-standard` (two slides, wide and tall, AVIF ignored), `hero-minimal` (no variants, no tagline, no button), `hero-two-lines` (line break, anchor, https and a third button that is cut, decorative slide), `hero-hostile` (escaping, unsafe buttons, unusable slides skipped), `hero-no-alt` and `hero-none` (empty). `seed.json` holds the seed for the ASF test CMS with a first focus estimate per photo. + +URL scheme suggestion for the variants (the CMS decides): `/media/hero//wide-1600.webp`, `/media/hero//tall-960.avif`. diff --git a/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected-preload.html b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected-preload.html new file mode 100644 index 0000000..885e97e --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected-preload.html @@ -0,0 +1 @@ + diff --git a/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected.html b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected.html new file mode 100644 index 0000000..73166d9 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.expected.html @@ -0,0 +1 @@ +Een "foto" <script>

<i>x</i> <b>"Andrea" & 'Slop'</b>

<Goed>

diff --git a/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.input.json b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.input.json new file mode 100644 index 0000000..497bbbf --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/Golden/host-injection/hero/hero-hostile.input.json @@ -0,0 +1,58 @@ +{ + "display": "slideshow", + "title": "\"Andrea\" & 'Slop'", + "tagline": "x", + "buttons": [ + { "label": "javascript", "target": "javascript:alert(1)" }, + { "label": "Protocolvrij", "target": "//evil.example/x" }, + { "label": "", "target": "/a?b=1&c=\"2\"" } + ], + "slides": [ + { + "id": "skip1", + "alt": "", + "decorative": false, + "image": { "width": 10, "height": 10, "src": "/media/x.webp" } + }, + { + "id": "skip2", + "alt": "extern", + "decorative": false, + "image": { + "width": 10, + "height": 10, + "src": "https://evil.example/x.webp" + } + }, + { + "id": "skip3", + "alt": "geen afmeting", + "decorative": false, + "image": { "width": 0, "height": 10, "src": "/media/x.webp" } + }, + { + "id": "a1", + "alt": "Een \"foto\" \n\"x\" & 'y'", "", new HeroButtonDto("", "/ok?a=1&b=\"2\"")); + + var html = HeroPictureRenderer.Render(hero).Region; + + html.Should().NotContain(""); + html.Should().Contain("<script>alert(1)</script>
"x" & 'y'"); + } + + [Fact] + public void ARendererNeverThrows_OnArbitraryText() + => Prop.ForAll( + Gen.Elements("a", "<", ">", "&", "\"", "'", "\n", " ", "é", "\\", "/", "#").ArrayOf().Select(p => string.Concat(p)).ToArbitrary(), + text => + { + var hero = new PublicHeroDto("single", "T" + text, text, text, [new HeroButtonDto(text, "/" + text)], + [new PublicSlideDto("id", "a" + text, false, new PublicImageDto(10, 10, new FocusDto(0.5, 0.5, 1), "/media/x/" + text.Replace("\\", string.Empty), []))]); + var html = HeroPictureRenderer.Render(hero).Region; + html.Should().NotContain("baked preload" + + "baked hero

rest

"; + + private static PublicHeroDto Hero() => new("single", "Andrea Slop", null, null, [], + [new PublicSlideDto("s1", "Een foto", false, new PublicImageDto(1600, 1067, new FocusDto(0.5, 0.5, 1), "/media/hero/0123456789abcdef/wide-1600.webp", + [new HeroVariantDto("wide", 1600, 1067, "image/webp", "/media/hero/0123456789abcdef/wide-1600.webp")]))]); + + private static HeroHtmlTransform Sut(PublicHeroDto? hero) + { + var model = Substitute.For(); + model.GetAsync(default).ReturnsForAnyArgs(hero); + return new HeroHtmlTransform(model); + } + + [Theory] + [InlineData("

nothing

", false)] + [InlineData("", true)] + [InlineData("", true)] + [InlineData("", false)] + public void Wants_OnlyPagesWithHeroMarkers(string html, bool expected) => Sut(null).Wants(html).Should().Be(expected); + + [Fact] + public async Task TheRegions_AreFilled_AndTheMarkersStay() + { + var html = await Sut(Hero()).ApplyAsync(Page, Context, default); + + html.Should().Contain("").And.Contain(""); + html.Should().Contain(""); + html.Should().NotContain("baked").And.Contain("

rest

"); + } + + [Fact] + public async Task WithoutAHero_ThePageStaysAsItWasBuilt() + { + (await Sut(null).ApplyAsync(Page, Context, default)).Should().Be(Page); + } + + [Fact] + public async Task AHeroWithoutAUsableSlide_LeavesTheBakedHero() + { + var textOnly = new PublicHeroDto("single", "Titel", null, null, [], []); + + (await Sut(textOnly).ApplyAsync(Page, Context, default)).Should().Be(Page); + } + + [Fact] + public async Task APageWithOnlyOneMarker_OnlyGetsThatPart() + { + var html = await Sut(Hero()).ApplyAsync("x", Context, default); + + html.Should().Contain("cms-hero-picture").And.NotContain("preload"); + } +} + +public class HeroPageModelTests +{ + private static PublicHeroDto Hero(string src = "/media/hero/0123456789abcdef/wide-1600.webp") => new("single", "Titel", null, null, [], + [new PublicSlideDto("s1", "Foto", false, new PublicImageDto(1600, 1067, new FocusDto(0.5, 0.5, 1), src, + [new HeroVariantDto("wide", 1600, 1067, "image/webp", src), new HeroVariantDto("tall", 640, 800, "image/webp", "/media/hero/0123456789abcdef/tall-640.webp")]))]); + + private static (HeroPageModel Model, IMediaStore Store) Make(PublicHeroDto? hero) + { + var publicHero = Substitute.For(); + publicHero.GetActiveAsync(default).ReturnsForAnyArgs(hero); + var store = Substitute.For(); + store.ExistsAsync(default!, default).ReturnsForAnyArgs(true); + return (new HeroPageModel(publicHero, store, NullLogger.Instance), store); + } + + [Fact] + public async Task WhenTheFilesOfTheFirstSlideExist_TheHeroIsReturned() + { + var (model, _) = Make(Hero()); + + (await model.GetAsync(default)).Should().NotBeNull(); + } + + [Fact] + public async Task WhenAFileOfTheFirstSlideIsMissing_NothingIsReturned() + { + var (model, store) = Make(Hero()); + store.ExistsAsync("hero/0123456789abcdef/tall-640.webp", default).Returns(false); + + (await model.GetAsync(default)).Should().BeNull(); + } + + [Fact] + public async Task WithoutAHero_OrWithoutSlides_ThereIsNothingToCheck() + { + (await Make(null).Model.GetAsync(default)).Should().BeNull(); + var textOnly = new PublicHeroDto("single", "Titel", null, null, [], []); + var (model, store) = Make(textOnly); + + (await model.GetAsync(default)).Should().Be(textOnly); + await store.DidNotReceiveWithAnyArgs().ExistsAsync(default!, default); + } + + [Fact] + public async Task TheDataContributor_WritesTheHero_OrNull() + { + var withHero = Make(Hero()).Model; + var without = Make(null).Model; + + (await new HeroDataContributor(withHero).GetAsync(new HtmlTransformContext("https://x"), default)).Should().BeOfType(); + (await new HeroDataContributor(without).GetAsync(new HtmlTransformContext("https://x"), default)).Should().BeNull(); + new HeroDataContributor(withHero).Key.Should().Be("hero"); + } + + [Fact] + public async Task TheDataBlock_CarriesTheOfferingsFirst_ThenTheHero() + { + var offerings = Substitute.For(); + offerings.Key.Returns("offerings"); + offerings.Order.Returns(100); + offerings.GetAsync(default!, default).ReturnsForAnyArgs(new[] { 1 }); + var block = new CmsDataBlockTransform([new HeroDataContributor(Make(Hero()).Model), offerings]); + + var html = await block.ApplyAsync("", new HtmlTransformContext("https://x"), default); + + var json = html["".Length]; + using var doc = JsonDocument.Parse(json); + doc.RootElement.EnumerateObject().Select(p => p.Name).Should().Equal("siteUrl", "offerings", "hero"); + doc.RootElement.GetProperty("hero").GetProperty("slides")[0].GetProperty("image").GetProperty("variants").GetArrayLength().Should().Be(2); + } +} diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroServiceTests.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroServiceTests.cs index e50d165..ea3e5f0 100644 --- a/src/SlpModularCms.Modules.Hero.Tests/HeroServiceTests.cs +++ b/src/SlpModularCms.Modules.Hero.Tests/HeroServiceTests.cs @@ -60,6 +60,24 @@ public class HeroImageServiceTests rig.Db.HeroImages.Count().Should().Be(1); } + [Fact] + public async Task TheSamePhotoAgain_RepairsLostFiles() + { + using var rig = new HeroTestRig(); + var photo = HeroTestRig.Photo(); + var first = await rig.Upload(photo); + System.IO.Directory.Delete(rig.Directory, recursive: true); + + var again = await rig.Upload(photo); + + again.Id.Should().Be(first.Id); + rig.Db.HeroImages.Count().Should().Be(1); + foreach (var variant in again.Variants) + { + (await rig.Store.ExistsAsync(variant.Url["/media/".Length..], CancellationToken.None)).Should().BeTrue(variant.Url); + } + } + [Fact] public async Task ADefaultFocus_IsTheCentre_ForEveryRatio() { diff --git a/src/SlpModularCms.Modules.Hero.Tests/SlpModularCms.Modules.Hero.Tests.csproj b/src/SlpModularCms.Modules.Hero.Tests/SlpModularCms.Modules.Hero.Tests.csproj index ce0a9f7..3d3e2ea 100644 --- a/src/SlpModularCms.Modules.Hero.Tests/SlpModularCms.Modules.Hero.Tests.csproj +++ b/src/SlpModularCms.Modules.Hero.Tests/SlpModularCms.Modules.Hero.Tests.csproj @@ -27,6 +27,10 @@ + + + + diff --git a/src/SlpModularCms.Modules.Hero/HeroModule.cs b/src/SlpModularCms.Modules.Hero/HeroModule.cs index 2a82eb6..e58411f 100644 --- a/src/SlpModularCms.Modules.Hero/HeroModule.cs +++ b/src/SlpModularCms.Modules.Hero/HeroModule.cs @@ -5,6 +5,7 @@ using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using SlpModularCms.Core.Hosting; +using SlpModularCms.Core.Hosting.Website; using SlpModularCms.Core.Media; using SlpModularCms.Core.Media.Magick; using SlpModularCms.Core.Modules; @@ -43,6 +44,9 @@ public class HeroModule : IModule services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddHostedService(); } diff --git a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs index cb52681..68b26eb 100644 --- a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs +++ b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs @@ -55,7 +55,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository => context.HeroImages.FirstOrDefaultAsync(i => i.Id == id, cancellationToken); public async Task> GetImagesAsync(IReadOnlyCollection ids, CancellationToken cancellationToken) - => await context.HeroImages.Where(i => ids.Contains(i.Id)).ToListAsync(cancellationToken); + { + // The MySQL provider cannot map a Guid list parameter in an IN clause; there are only a few dozen images, so they + // are read and filtered here. + var wanted = ids.ToHashSet(); + return (await context.HeroImages.ToListAsync(cancellationToken)).Where(i => wanted.Contains(i.Id)).ToList(); + } public Task GetImageBySha256Async(string sha256, CancellationToken cancellationToken) => context.HeroImages.FirstOrDefaultAsync(i => i.OriginalSha256 == sha256, cancellationToken); diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs index 29c2265..71ba1dc 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs @@ -48,8 +48,10 @@ public class HeroImageService( using var admitted = await guard.AdmitAsync(upload, declaredLength, cancellationToken); var sha = Convert.ToHexStringLower(SHA256.HashData(admitted.Bytes)); + // The same photo again is the same image. When its files are gone (a lost or restored media directory) the upload + // repairs them from the file that was just sent. var existing = await repository.GetImageBySha256Async(sha, cancellationToken); - if (existing is not null) + if (existing is not null && await FilesExistAsync(existing, cancellationToken)) { return HeroMapping.ToImageDto(existing); } @@ -62,7 +64,7 @@ public class HeroImageService( var original = stripped ?? admitted.Bytes; var storedFormat = stripped is not null && format == ImageFormat.Heic ? ImageFormat.Jpeg : format; - var image = new HeroImage + var image = existing ?? new HeroImage { Id = Guid.NewGuid(), OriginalSha256 = sha, @@ -79,13 +81,35 @@ public class HeroImageService( await store.PutAsync(image.OriginalKey, original, cancellationToken); await store.PutSetAsync(HeroMapping.Area, image.SetHash, files, cancellationToken); - repository.AddImage(image); + if (existing is null) + { + repository.AddImage(image); + } + await repository.SaveChangesAsync(cancellationToken); - logger.LogInformation("Hero image {ImageId} uploaded by user {UserId} ({Width}x{Height}, {Variants} variants)", image.Id, callerId, image.Width, image.Height, image.Variants.Count); + logger.LogInformation("Hero image {ImageId} {Action} by user {UserId} ({Width}x{Height}, {Variants} variants)", image.Id, existing is null ? "uploaded" : "repaired", callerId, image.Width, image.Height, image.Variants.Count); return HeroMapping.ToImageDto(image); } + private async Task FilesExistAsync(HeroImage image, CancellationToken cancellationToken) + { + if (!await store.ExistsAsync(image.OriginalKey, cancellationToken)) + { + return false; + } + + foreach (var variant in image.Variants) + { + if (!await store.ExistsAsync($"{HeroMapping.Area}/{image.SetHash}/{variant.FileName}", cancellationToken)) + { + return false; + } + } + + return true; + } + public async Task SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken) { var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException(); diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroInjection.cs b/src/SlpModularCms.Modules.Hero/Services/HeroInjection.cs new file mode 100644 index 0000000..c3fa1c1 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Services/HeroInjection.cs @@ -0,0 +1,80 @@ +using Microsoft.Extensions.Logging; +using SlpModularCms.Core.Hosting.Website; +using SlpModularCms.Core.Media; +using SlpModularCms.Modules.Hero.Models; + +namespace SlpModularCms.Modules.Hero.Services; + +/// +/// The hero as a page may show it: the public hero, but only when the files of its first slide are really in the media +/// store. When they are not (a missing or restored directory) nothing of the hero is written, so a page never gets a broken +/// first image and the baked hero stays. One answer for the region, the preload and the data block. +/// +public interface IHeroPageModel +{ + Task GetAsync(CancellationToken cancellationToken); +} + +public sealed class HeroPageModel(IPublicHeroService publicHero, IMediaStore store, ILogger logger) : IHeroPageModel +{ + public async Task GetAsync(CancellationToken cancellationToken) + { + var hero = await publicHero.GetActiveAsync(cancellationToken); + if (hero is null) + { + return null; + } + + var first = hero.Slides.FirstOrDefault(); + if (first is null) + { + return hero; + } + + foreach (var url in new[] { first.Image.Src }.Concat(first.Image.Variants.Select(v => v.Url)).Distinct()) + { + if (url.StartsWith(MediaPaths.UrlPrefix, StringComparison.Ordinal) + && !await store.ExistsAsync(url[MediaPaths.UrlPrefix.Length..], cancellationToken)) + { + logger.LogWarning("The first hero slide has a file missing in the media store ({Address}); the hero is left out of the page.", url); + return null; + } + } + + return hero; + } +} + +/// Fills the hero regions of a page: <!--CMS:HERO-HTML--> in the body and <!--CMS:HERO-PRELOAD--> in the head. Fail-open: no hero means the baked page stays. +public sealed class HeroHtmlTransform(IHeroPageModel model) : IHtmlPageTransform +{ + public const string HtmlRegion = "CMS:HERO-HTML"; + public const string PreloadRegion = "CMS:HERO-PRELOAD"; + + public bool Wants(string html) + => html.Contains("", StringComparison.Ordinal) + || html.Contains("", StringComparison.Ordinal); + + public async Task ApplyAsync(string html, HtmlTransformContext context, CancellationToken cancellationToken) + { + var rendered = HeroPictureRenderer.Render(await model.GetAsync(cancellationToken)); + if (rendered.IsEmpty) + { + return html; + } + + html = HtmlMarkerEditor.ReplaceRegion(html, HtmlRegion, rendered.Region); + return HtmlMarkerEditor.ReplaceRegion(html, PreloadRegion, rendered.Preload); + } +} + +/// The hero key of the page data block: the complete public hero (all slides), or null. +public sealed class HeroDataContributor(IHeroPageModel model) : ICmsDataBlockContributor +{ + public string Key => "hero"; + + public int Order => 200; + + public async Task GetAsync(HtmlTransformContext context, CancellationToken cancellationToken) + => await model.GetAsync(cancellationToken); +} diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroPictureRenderer.cs b/src/SlpModularCms.Modules.Hero/Services/HeroPictureRenderer.cs new file mode 100644 index 0000000..62cc056 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Services/HeroPictureRenderer.cs @@ -0,0 +1,213 @@ +using System.Globalization; +using System.Text; +using SlpModularCms.Modules.Hero.Models; + +namespace SlpModularCms.Modules.Hero.Services; + +/// The two pieces written into a page: the hero itself and the preload links for the head. Both empty = leave the baked page. +public sealed record HeroInjection(string Region, string Preload) +{ + public static readonly HeroInjection None = new(string.Empty, string.Empty); + + public bool IsEmpty => Region.Length == 0; +} + +/// +/// The plain HTML of the hero for the first response, written exactly as the website's golden files expect +/// (aidlc-docs/features/hero-module, site contract; ASF commit 13f78c4). One place produces the picture and the preload, +/// so the srcset, sizes and media values are the same text in both. Pure; everything is HTML-encoded. +/// +/// +/// The rules are those of the website: a hero needs a title and a usable first slide (an id, an own-host path, a size, and +/// an alt text or the decorative flag), only WebP is used for the first image (a preload cannot say "AVIF if supported"), +/// at most two buttons, and unusable parts are skipped, never repaired. They are deliberately a little wider than what the +/// CMS accepts when saving, because the renderer must also cope with data it did not validate itself. +/// +public static class HeroPictureRenderer +{ + private const string Webp = "image/webp"; + private const string Portrait = "(orientation: portrait)"; + private const string Landscape = "(orientation: landscape)"; + + public static HeroInjection Render(PublicHeroDto? hero) + { + if (hero is null || string.IsNullOrWhiteSpace(hero.Title)) + { + return HeroInjection.None; + } + + var slide = (hero.Slides ?? []).FirstOrDefault(IsUsable); + if (slide is null) + { + return HeroInjection.None; + } + + var image = slide.Image; + var variants = (image.Variants ?? []).Where(v => IsUsable(v) && v.Type == Webp).ToList(); + var wide = SrcSet(variants, "wide"); + var tall = SrcSet(variants, "tall"); + + return new HeroInjection(Region(hero, slide, wide, tall), Preload(image.Src, wide, tall)); + } + + private static string Region(PublicHeroDto hero, PublicSlideDto slide, string wide, string tall) + { + var image = slide.Image; + var html = new StringBuilder(); + html.Append(""); + if (tall.Length > 0) + { + html.Append(""); + } + + html.Append(" 0) + { + html.Append(" srcset=\"").Append(Encode(wide)).Append("\" sizes=\"100vw\""); + } + + html.Append(" width=\"").Append(image.Width.ToString(CultureInfo.InvariantCulture)).Append("\" height=\"").Append(image.Height.ToString(CultureInfo.InvariantCulture)).Append('"'); + html.Append(" alt=\"").Append(slide.Decorative ? string.Empty : Encode(slide.Alt)).Append('"'); + if (Position(image) is { } position) + { + html.Append(" style=\"object-position:").Append(position).Append('"'); + } + + html.Append(" fetchpriority=\"high\">"); + + html.Append("

"); + if (!string.IsNullOrWhiteSpace(hero.Tagline)) + { + html.Append("").Append(Encode(hero.Tagline)).Append(" "); + } + + html.Append("").Append(string.Join("
", hero.Title.Replace("\r\n", "\n").Split('\n').Select(Encode))).Append("

"); + + var buttons = (hero.Buttons ?? []).Where(IsUsable).Take(2).ToList(); + if (buttons.Count > 0) + { + html.Append("

"); + foreach (var button in buttons) + { + html.Append("").Append(Encode(button.Label)).Append(""); + } + + html.Append("

"); + } + + return html.ToString(); + } + + private static string Preload(string src, string wide, string tall) + { + const string head = ""; + + string Link(string set, string? media) + { + var link = new StringBuilder(head); + if (set.Length > 0) + { + link.Append(" imagesrcset=\"").Append(Encode(set)).Append("\" imagesizes=\"100vw\""); + } + else + { + link.Append(" href=\"").Append(Encode(src)).Append('"'); + } + + if (media is not null) + { + link.Append(" media=\"").Append(media).Append('"'); + } + + return link.Append(tail).ToString(); + } + + return tall.Length > 0 ? Link(tall, Portrait) + Link(wide, Landscape) : Link(wide, null); + } + + // ----- what counts as usable (the rules of the website) ------------------------------------------------------- + + private static bool IsUsable(PublicSlideDto? slide) + => slide is { Image: not null } + && !string.IsNullOrEmpty(slide.Id) + && IsHostPath(slide.Image.Src) + && slide.Image.Width > 0 + && slide.Image.Height > 0 + && (slide.Decorative || !string.IsNullOrWhiteSpace(slide.Alt)); + + private static bool IsUsable(HeroVariantDto variant) + => !string.IsNullOrEmpty(variant.Ratio) && !string.IsNullOrEmpty(variant.Type) && variant.Width > 0 && IsHostPath(variant.Url); + + private static bool IsUsable(HeroButtonDto button) + => !string.IsNullOrWhiteSpace(button.Label) && IsButtonTarget(button.Target); + + /// A path of this host: one leading slash, not a protocol-relative address, no backslash. + private static bool IsHostPath(string? value) + => !string.IsNullOrEmpty(value) && value[0] == '/' && !value.StartsWith("//", StringComparison.Ordinal) && !value.Contains('\\'); + + private static bool IsButtonTarget(string? target) + { + if (string.IsNullOrEmpty(target)) + { + return false; + } + + if (target[0] == '#') + { + return target.Length > 1 && !target.Any(char.IsWhiteSpace); + } + + if (target[0] == '/') + { + return IsHostPath(target); + } + + return target.StartsWith("https://", StringComparison.Ordinal) + && Uri.TryCreate(target, UriKind.Absolute, out var uri) + && uri.Scheme == Uri.UriSchemeHttps + && !string.IsNullOrEmpty(uri.Host); + } + + private static string SrcSet(IEnumerable variants, string ratio) + => string.Join(", ", variants.Where(v => v.Ratio == ratio).OrderBy(v => v.Width).Select(v => v.Url + " " + v.Width.ToString(CultureInfo.InvariantCulture) + "w")); + + /// X% Y% from a focus point inside the image (at most two decimals, no trailing zeros), or null without a valid one. + private static string? Position(PublicImageDto image) + { + var focus = image.Focus; + if (focus is null || focus.X is < 0 or > 1 || focus.Y is < 0 or > 1 || double.IsNaN(focus.X) || double.IsNaN(focus.Y)) + { + return null; + } + + return Percent(focus.X) + "% " + Percent(focus.Y) + "%"; + } + + private static string Percent(double fraction) + => Math.Round(fraction * 100, 2, MidpointRounding.AwayFromZero).ToString("0.##", CultureInfo.InvariantCulture); + + private static string Encode(string? value) + { + if (string.IsNullOrEmpty(value)) + { + return string.Empty; + } + + var builder = new StringBuilder(value.Length + 8); + foreach (var c in value) + { + switch (c) + { + case '&': builder.Append("&"); break; + case '<': builder.Append("<"); break; + case '>': builder.Append(">"); break; + case '"': builder.Append("""); break; + case '\'': builder.Append("'"); break; + default: builder.Append(c); break; + } + } + + return builder.ToString(); + } +} diff --git a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsHtmlTransformTests.cs b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsHtmlTransformTests.cs index 5c2ca35..d1f1b24 100644 --- a/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsHtmlTransformTests.cs +++ b/src/SlpModularCms.Modules.Offerings.Tests/Services/OfferingsHtmlTransformTests.cs @@ -16,6 +16,9 @@ public class OfferingsHtmlTransformTests private OfferingsHtmlTransform Sut() => new(_offerings, _banners); + // The data block is composed by the Core transform from the contributors of the Offerings module (same output as before). + private CmsDataBlockTransform DataBlock() => new([new OfferingsDataContributor(_offerings), new BannersDataContributor(_banners)]); + private static OfferingDto Offering(string slug, string title, string price, int order = 0, bool featured = false) => new( Guid.NewGuid().ToString(), slug, title, "Beschrijving", price, "eenmalig", ["1 uur fotografie", "Online galerij"], "Boek", featured, order); @@ -92,7 +95,7 @@ public class OfferingsHtmlTransformTests Banner("top", top); Banner("bottom", null); - var html = await Sut().ApplyAsync("", Context, default); + var html = await DataBlock().ApplyAsync("", Context, default); html.Should().StartWith(""); var json = html["".Length]; @@ -114,7 +117,7 @@ public class OfferingsHtmlTransformTests Banner("top", null); Banner("bottom", null); - var html = await Sut().ApplyAsync("", Context, default); + var html = await DataBlock().ApplyAsync("", Context, default); var inner = html["".Length]; inner.Should().NotContain("<").And.NotContain(">").And.NotContain("&").And.NotContain("\u2028"); diff --git a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs index f665dd3..5d57abe 100644 --- a/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs +++ b/src/SlpModularCms.Modules.Offerings/OfferingsModule.cs @@ -34,6 +34,8 @@ public class OfferingsModule : IModule services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingsDataContributors.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingsDataContributors.cs new file mode 100644 index 0000000..79b3462 --- /dev/null +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingsDataContributors.cs @@ -0,0 +1,30 @@ +using SlpModularCms.Core.Hosting.Website; +using SlpModularCms.Modules.Offerings.Data.Entities; + +namespace SlpModularCms.Modules.Offerings.Services; + +/// The offerings key of the page data block: the same list the public endpoint answers. +public sealed class OfferingsDataContributor(IOfferingsService offerings) : ICmsDataBlockContributor +{ + public string Key => "offerings"; + + public int Order => 100; + + public async Task GetAsync(HtmlTransformContext context, CancellationToken cancellationToken) + => await offerings.GetOfferingsAsync(); +} + +/// The banners key of the page data block: the active top and bottom banner (null when there is none). +public sealed class BannersDataContributor(IOfferingBannersService banners) : ICmsDataBlockContributor +{ + public string Key => "banners"; + + public int Order => 110; + + public async Task GetAsync(HtmlTransformContext context, CancellationToken cancellationToken) + { + var top = await banners.GetActiveAsync(OfferingBannerPositions.Top); + var bottom = await banners.GetActiveAsync(OfferingBannerPositions.Bottom); + return new { top, bottom }; + } +} diff --git a/src/SlpModularCms.Modules.Offerings/Services/OfferingsHtmlTransform.cs b/src/SlpModularCms.Modules.Offerings/Services/OfferingsHtmlTransform.cs index f1aa52a..f4a1c2f 100644 --- a/src/SlpModularCms.Modules.Offerings/Services/OfferingsHtmlTransform.cs +++ b/src/SlpModularCms.Modules.Offerings/Services/OfferingsHtmlTransform.cs @@ -18,14 +18,9 @@ public sealed class OfferingsHtmlTransform(IOfferingsService offerings, IOfferin public const string OfferingsRegion = "CMS:OFFERINGS-HTML"; public const string BannerTopRegion = "CMS:BANNER-TOP-HTML"; public const string BannerBottomRegion = "CMS:BANNER-BOTTOM-HTML"; - public const string DataMarker = "CMS:DATA"; - public const string DataBlockId = "cms-data"; public const string JsonLdMarker = "CMS:OFFER-JSON-LD"; public const string PriceAttribute = "data-cms-price"; - // The shape of GET /api/v1/offerings and /offerings/banner: camelCase, nulls written. - private static readonly JsonSerializerOptions ApiJson = new(JsonSerializerDefaults.Web); - private static readonly JsonSerializerOptions LdJson = new() { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, @@ -35,13 +30,11 @@ public sealed class OfferingsHtmlTransform(IOfferingsService offerings, IOfferin public async Task ApplyAsync(string html, HtmlTransformContext context, CancellationToken cancellationToken) { - var wantsData = html.Contains("", StringComparison.Ordinal); - var wantsOfferings = wantsData - || html.Contains("", StringComparison.Ordinal) + var wantsOfferings = html.Contains("", StringComparison.Ordinal) || html.Contains("", StringComparison.Ordinal); - var wantsBottom = wantsData || html.Contains("", StringComparison.Ordinal); + var wantsTop = html.Contains("", StringComparison.Ordinal); + var wantsBottom = html.Contains("", StringComparison.Ordinal); var live = wantsOfferings ? await offerings.GetOfferingsAsync() : []; var top = wantsTop ? await banners.GetActiveAsync(OfferingBannerPositions.Top) : null; @@ -65,22 +58,9 @@ public sealed class OfferingsHtmlTransform(IOfferingsService offerings, IOfferin html = HtmlMarkerEditor.ReplaceRegion(html, BannerBottomRegion, CmsPageHtml.Banner(bottom, OfferingBannerPositions.Bottom)); } - if (wantsData) - { - html = HtmlMarkerEditor.ReplaceDataBlock(html, DataMarker, DataBlockId, DataBlock(context.SiteUrl, live, top, bottom)); - } - return html; } - /// The data block: the answers of the public API plus the address of the site, safe inside a script element. - public static string DataBlock(string siteUrl, IReadOnlyList live, PublicOfferingBannerDto? top, PublicOfferingBannerDto? bottom) - { - var json = JsonSerializer.Serialize( - new { siteUrl, offerings = live, banners = new { top, bottom } }, ApiJson); - return ""; - } - private static int? FindPrice(IReadOnlyList live, string slug) => live.FirstOrDefault(o => string.Equals(o.Slug, slug, StringComparison.Ordinal)) is { } offering ? CmsPageHtml.WholeEuros(offering.Price)