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 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 15:58:02 +01:00
co-authored by Claude Sonnet 5.5
parent ae04120d8c
commit 4369c905cd
41 changed files with 1402 additions and 31 deletions
@@ -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;
/// <summary>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.</summary>
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<string, string?> { ["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<HeroInjectionFactory>
{
private const string Page =
"<!doctype html><html><head><!--CMS:HERO-PRELOAD-->baked preload<!--/CMS:HERO-PRELOAD-->" +
"<!--CMS:DATA--><script type=\"application/json\" id=\"cms-data\">{\"baked\":true}</script></head>" +
"<body><!--CMS:HERO-HTML-->baked hero<!--/CMS:HERO-HTML--></body></html>";
private readonly HeroInjectionFactory _factory;
public HeroInjectionPipelineTests(HeroInjectionFactory factory)
{
_factory = factory;
File.WriteAllText(Path.Combine(factory.WebRoot, "web", "hero.html"), Page);
}
private async Task<T> InScope<T>(Func<IServiceProvider, Task<T>> 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 = "<script type=\"application/json\" id=\"cms-data\">";
var start = body.IndexOf(open, StringComparison.Ordinal) + open.Length;
return body[start..body.IndexOf("</script>", 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<HeroDbContext>();
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<HeroDbContext>();
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<IHeroImageService>().UploadAsync(new MemoryStream(Photo()), Photo().Length, caller, default));
await InScope(async sp => await sp.GetRequiredService<IHeroService>().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("<picture class=\"cms-hero-picture\"><source media=\"(orientation: portrait)\"");
body.Should().Contain("alt=\"Zwangerschapsfoto in de duinen\"").And.Contain("<span class=\"cms-hero-name\">Andrea Slop</span>");
body.Should().Contain("<a class=\"cms-hero-button\" href=\"/over-mij\">Lees meer</a>");
body.Should().Contain("<link rel=\"preload\" as=\"image\"").And.Contain("media=\"(orientation: landscape)\"");
// The data block carries the same hero as the public endpoint, after the site address.
var data = JsonDocument.Parse(DataBlock(body)).RootElement;
data.EnumerateObject().Select(p => 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<IHeroService>();
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<IHeroService>();
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<SlpModularCms.Core.Hosting.Website.IIndexHtmlCache>().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<HeroDbContext>();
db.Heroes.RemoveRange(await db.Heroes.ToListAsync());
await db.SaveChangesAsync();
return 0;
});
}
}
@@ -7,6 +7,7 @@ using SlpModularCms.Modules.Hero.Data;
namespace SlpModularCms.Api.Tests;
/// <summary>The Hero module on the real master host and the real, migrated database.</summary>
[Collection("HeroDatabase")]
public class HeroOnTheMasterHostTests : IClassFixture<ApiWebApplicationFactory>
{
private readonly ApiWebApplicationFactory _factory;
@@ -25,6 +26,15 @@ public class HeroOnTheMasterHostTests : IClassFixture<ApiWebApplicationFactory>
[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<HeroDbContext>();
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);
@@ -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 = "<script type=\"application/json\" id=\"cms-data\">";
private static ICmsDataBlockContributor Contributor(string key, int order, object? value)
{
var c = Substitute.For<ICmsDataBlockContributor>();
c.Key.Returns(key);
c.Order.Returns(order);
c.GetAsync(default!, default).ReturnsForAnyArgs(value);
return c;
}
private static JsonElement Data(string html)
{
var start = html.IndexOf(Open, StringComparison.Ordinal) + Open.Length;
return JsonDocument.Parse(html[start..html.IndexOf("</script>", start, StringComparison.Ordinal)]).RootElement;
}
[Theory]
[InlineData("<!--CMS:DATA-->", true)]
[InlineData("<p>nothing</p>", false)]
[InlineData("<!--CMS:OFFERINGS-HTML--><!--/CMS:OFFERINGS-HTML-->", 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("<head><!--CMS:DATA--><script type=\"application/json\" id=\"cms-data\">{\"baked\":true}</script></head>", Context, default);
html.Should().StartWith("<head>" + Open).And.EndWith("</script></head>").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("<!--CMS:DATA-->", 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("<!--CMS:DATA-->", 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 = "</script><img src=x onerror=alert(1)> & \u2028" })]).ApplyAsync("<!--CMS:DATA-->", Context, default);
var inner = html[Open.Length..^"</script>".Length];
inner.Should().NotContain("<").And.NotContain(">").And.NotContain("&").And.NotContain("\u2028");
JsonDocument.Parse(inner).RootElement.GetProperty("x").GetProperty("text").GetString().Should().Be("</script><img src=x onerror=alert(1)> & \u2028");
}
[Fact]
public async Task AFailingContributor_FailsTheWholeBlock_SoThePageKeepsItsBakedBlock()
{
var failing = Substitute.For<ICmsDataBlockContributor>();
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("<!--CMS:DATA-->", Context, default);
await act.Should().ThrowAsync<InvalidOperationException>();
}
[Fact]
public async Task WithoutContributors_TheBlockHoldsTheSiteUrlOnly()
{
var html = await new CmsDataBlockTransform([]).ApplyAsync("<!--CMS:DATA-->", Context, default);
Data(html).EnumerateObject().Select(p => p.Name).Should().Equal("siteUrl");
}
}
@@ -0,0 +1,68 @@
using System.Buffers;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Logging;
namespace SlpModularCms.Core.Hosting.Website;
/// <summary>
/// A module's key in the data block that the host writes into a website page (<c>&lt;script type="application/json"
/// id="cms-data"&gt;</c> after the <c>&lt;!--CMS:DATA--&gt;</c> 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.
/// </summary>
public interface ICmsDataBlockContributor
{
/// <summary>The property name in the block (<c>offerings</c>, <c>banners</c>, <c>hero</c>).</summary>
string Key { get; }
/// <summary>Fixes the order of the keys in the block: lower first (100 offerings, 110 banners, 200 hero).</summary>
int Order { get; }
/// <summary>The value to write for <see cref="Key"/>; null is written as JSON null (the website then keeps what it was built with).</summary>
Task<object?> GetAsync(HtmlTransformContext context, CancellationToken cancellationToken);
}
/// <summary>
/// Owns the <c>&lt;!--CMS:DATA--&gt;</c> marker: composes one block from <c>siteUrl</c> and every registered
/// <see cref="ICmsDataBlockContributor"/>, 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).
/// </summary>
public sealed class CmsDataBlockTransform(IEnumerable<ICmsDataBlockContributor> 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("<!--" + Marker + "-->", StringComparison.Ordinal);
public async Task<string> ApplyAsync(string html, HtmlTransformContext context, CancellationToken cancellationToken)
{
var buffer = new ArrayBufferWriter<byte>();
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 = "<script type=\"application/json\" id=\"" + BlockId + "\">" + HtmlMarkerEditor.EscapeForScript(json) + "</script>";
return HtmlMarkerEditor.ReplaceDataBlock(html, Marker, BlockId, block);
}
}
@@ -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<HtmlMarkerInjector>();
services.AddSingleton<IIndexHtmlCache>(provider => provider.GetRequiredService<HtmlMarkerInjector>());
// The shared CMS data block of the pages (siteUrl plus what each module contributes).
services.TryAddEnumerable(ServiceDescriptor.Scoped<IHtmlPageTransform, CmsDataBlockTransform>());
// Presence of the marker switches on the full security-header set for website responses.
services.AddSingleton<WebsiteHostingMarker>();
@@ -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<WebsiteOptions>().Bind(configuration.GetSection(WebsiteOptions.SectionName));
services.AddSingleton<HtmlMarkerInjector>();
services.AddSingleton<IIndexHtmlCache>(provider => provider.GetRequiredService<HtmlMarkerInjector>());
// The shared CMS data block of the pages (siteUrl plus what each module contributes).
services.TryAddEnumerable(ServiceDescriptor.Scoped<IHtmlPageTransform, CmsDataBlockTransform>());
return services;
}
@@ -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`).
@@ -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 `<picture>`. Same idea as the packages (`../README.md`): for every `NAME.input.json` the host's template must give exactly `NAME.expected.html` (between `<!--CMS:HERO-HTML-->` and `<!--/CMS:HERO-HTML-->`) and `NAME.expected-preload.html` (between `<!--CMS:HERO-PRELOAD-->` and `<!--/CMS:HERO-PRELOAD-->` 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 (`&` `&amp;`, `<` `&lt;`, `>` `&gt;`, `"` `&quot;`, `'` `&#39;`). A new line in the title becomes `<br>` (after escaping).
## Output, HERO-HTML
`<picture class="cms-hero-picture">` + (when a `tall` webp variant exists: `<source media="(orientation: portrait)" srcset="TALL" sizes="100vw" type="image/webp">`) + `<img class="cms-hero-image" src="SRC"` + (when a `wide` webp variant exists: ` srcset="WIDE" sizes="100vw"`) + ` width="W" height="H" alt="ALT"` + (focus: ` style="object-position:X% Y%"`) + ` fetchpriority="high">` + `</picture>` + `<h1 class="cms-hero-title">` + (tagline: `<span class="cms-hero-tagline">TAGLINE</span> `) + `<span class="cms-hero-name">TITLE</span></h1>` + (when there are buttons: `<p class="cms-hero-buttons">` + `<a class="cms-hero-button" href="TARGET">LABEL</a>`... + `</p>`).
`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: `<link rel="preload" as="image" imagesrcset="TALL" imagesizes="100vw" media="(orientation: portrait)" fetchpriority="high">` 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/<hash>/wide-1600.webp`, `/media/hero/<hash>/tall-960.avif`.
@@ -0,0 +1 @@
<link rel="preload" as="image" imagesrcset="/media/hero/a&quot;b/w800.webp 800w" imagesizes="100vw" fetchpriority="high">
@@ -0,0 +1 @@
<picture class="cms-hero-picture"><img class="cms-hero-image" src="/media/hero/a&quot;b/w1600.webp" srcset="/media/hero/a&quot;b/w800.webp 800w" sizes="100vw" width="1600" height="1067" alt="Een &quot;foto&quot; &lt;script&gt;" fetchpriority="high"></picture><h1 class="cms-hero-title"><span class="cms-hero-tagline">&lt;i&gt;x&lt;/i&gt;</span> <span class="cms-hero-name">&lt;b&gt;&quot;Andrea&quot; &amp; &#39;Slop&#39;&lt;/b&gt;</span></h1><p class="cms-hero-buttons"><a class="cms-hero-button" href="/a?b=1&amp;c=&quot;2&quot;">&lt;Goed&gt;</a></p>
@@ -0,0 +1,58 @@
{
"display": "slideshow",
"title": "<b>\"Andrea\" & 'Slop'</b>",
"tagline": "<i>x</i>",
"buttons": [
{ "label": "javascript", "target": "javascript:alert(1)" },
{ "label": "Protocolvrij", "target": "//evil.example/x" },
{ "label": "<Goed>", "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\" <script>",
"decorative": false,
"image": {
"width": 1600,
"height": 1067,
"src": "/media/hero/a\"b/w1600.webp",
"variants": [
{
"ratio": "wide",
"width": 800,
"type": "image/webp",
"url": "/media/hero/a\"b/w800.webp"
},
{
"ratio": "wide",
"width": 400,
"type": "image/webp",
"url": "https://evil.example/w400.webp"
}
]
}
}
]
}
@@ -0,0 +1 @@
<link rel="preload" as="image" href="/media/hero/abc123/w2560.webp" fetchpriority="high">
@@ -0,0 +1 @@
<picture class="cms-hero-picture"><img class="cms-hero-image" src="/media/hero/abc123/w2560.webp" width="2560" height="1702" alt="Lifestyle fotografie" fetchpriority="high"></picture><h1 class="cms-hero-title"><span class="cms-hero-name">Andrea Slop</span></h1>
@@ -0,0 +1,17 @@
{
"display": "single",
"title": "Andrea Slop",
"buttons": [],
"slides": [
{
"id": "a1",
"alt": "Lifestyle fotografie",
"decorative": false,
"image": {
"width": 2560,
"height": 1702,
"src": "/media/hero/abc123/w2560.webp"
}
}
]
}
@@ -0,0 +1,13 @@
{
"display": "slideshow",
"title": "Titel",
"buttons": [],
"slides": [
{
"id": "x",
"alt": "",
"decorative": false,
"image": { "width": 1, "height": 1, "src": "/m.webp" }
}
]
}
@@ -0,0 +1 @@
<link rel="preload" as="image" imagesrcset="/media/hero/3f9a1c/tall-640.webp 640w, /media/hero/3f9a1c/tall-960.webp 960w" imagesizes="100vw" media="(orientation: portrait)" fetchpriority="high"><link rel="preload" as="image" imagesrcset="/media/hero/3f9a1c/wide-960.webp 960w, /media/hero/3f9a1c/wide-1600.webp 1600w" imagesizes="100vw" media="(orientation: landscape)" fetchpriority="high">
@@ -0,0 +1 @@
<picture class="cms-hero-picture"><source media="(orientation: portrait)" srcset="/media/hero/3f9a1c/tall-640.webp 640w, /media/hero/3f9a1c/tall-960.webp 960w" sizes="100vw" type="image/webp"><img class="cms-hero-image" src="/media/hero/3f9a1c/wide-1600.webp" srcset="/media/hero/3f9a1c/wide-960.webp 960w, /media/hero/3f9a1c/wide-1600.webp 1600w" sizes="100vw" width="1600" height="1067" alt="Zwangerschapsfoto in de duinen" style="object-position:50% 55%" fetchpriority="high"></picture><h1 class="cms-hero-title"><span class="cms-hero-tagline">Lifestyle fotograaf · Huizen</span> <span class="cms-hero-name">Andrea Slop</span></h1><p class="cms-hero-buttons"><a class="cms-hero-button" href="/over-mij">Lees meer</a></p>
@@ -0,0 +1,76 @@
{
"display": "slideshow",
"title": "Andrea Slop",
"tagline": "Lifestyle fotograaf · Huizen",
"lead": null,
"buttons": [{ "label": "Lees meer", "target": "/over-mij" }],
"slides": [
{
"id": "11111111-1111-1111-1111-111111111111",
"alt": "Zwangerschapsfoto in de duinen",
"decorative": false,
"image": {
"width": 1600,
"height": 1067,
"focus": { "x": 0.5, "y": 0.55 },
"src": "/media/hero/3f9a1c/wide-1600.webp",
"variants": [
{
"ratio": "wide",
"width": 1600,
"type": "image/webp",
"url": "/media/hero/3f9a1c/wide-1600.webp"
},
{
"ratio": "wide",
"width": 960,
"type": "image/webp",
"url": "/media/hero/3f9a1c/wide-960.webp"
},
{
"ratio": "wide",
"width": 1600,
"type": "image/avif",
"url": "/media/hero/3f9a1c/wide-1600.avif"
},
{
"ratio": "wide",
"width": 960,
"type": "image/avif",
"url": "/media/hero/3f9a1c/wide-960.avif"
},
{
"ratio": "tall",
"width": 960,
"type": "image/webp",
"url": "/media/hero/3f9a1c/tall-960.webp"
},
{
"ratio": "tall",
"width": 640,
"type": "image/webp",
"url": "/media/hero/3f9a1c/tall-640.webp"
},
{
"ratio": "tall",
"width": 960,
"type": "image/avif",
"url": "/media/hero/3f9a1c/tall-960.avif"
}
]
}
},
{
"id": "22222222-2222-2222-2222-222222222222",
"alt": "Knusse newbornfoto met de familie",
"decorative": false,
"image": {
"width": 1600,
"height": 1067,
"focus": { "x": 0.45, "y": 0.5 },
"src": "/media/hero/7b2e90/wide-1600.webp",
"variants": []
}
}
]
}
@@ -0,0 +1 @@
<link rel="preload" as="image" href="/media/hero/abc123/w1600.webp" fetchpriority="high">
@@ -0,0 +1 @@
<picture class="cms-hero-picture"><img class="cms-hero-image" src="/media/hero/abc123/w1600.webp" width="1600" height="1067" alt="" fetchpriority="high"></picture><h1 class="cms-hero-title"><span class="cms-hero-tagline">Fotografie</span> <span class="cms-hero-name">Andrea<br>Slop</span></h1><p class="cms-hero-buttons"><a class="cms-hero-button" href="#contact">Boek een shoot</a><a class="cms-hero-button" href="https://andreaslop.nl/portfolio">Portfolio</a></p>
@@ -0,0 +1,23 @@
{
"display": "slideshow",
"title": "Andrea\nSlop",
"tagline": "Fotografie",
"buttons": [
{ "label": "Boek een shoot", "target": "#contact" },
{ "label": "Portfolio", "target": "https://andreaslop.nl/portfolio" },
{ "label": "Derde knop", "target": "/derde" }
],
"slides": [
{
"id": "a1",
"alt": "",
"decorative": true,
"image": {
"width": 1600,
"height": 1067,
"src": "/media/hero/abc123/w1600.webp",
"variants": []
}
}
]
}
@@ -0,0 +1,73 @@
{
"note": "Seed for the ASF hero on the test CMS. Focus points are a first estimate from looking at the photos (x and y between 0 and 1, from the top left); Bryan adjusts them in the admin. Sources are the existing exports in web/src/assets (not camera originals; never upscale).",
"display": "slideshow",
"title": "Andrea Slop",
"tagline": "Lifestyle fotograaf · Huizen",
"buttons": [{ "label": "Lees meer", "target": "/over-mij" }],
"slides": [
{
"file": "hero-8.jpg",
"width": 1600,
"height": 1067,
"alt": "Zwangerschapsfoto in de duinen",
"focus": { "x": 0.5, "y": 0.55 },
"subject": "belly and hands"
},
{
"file": "hero-7.jpg",
"width": 1600,
"height": 1067,
"alt": "Knusse newbornfoto met de familie",
"focus": { "x": 0.45, "y": 0.5 },
"subject": "the kiss on the baby"
},
{
"file": "hero-1.jpg",
"width": 2560,
"height": 1702,
"alt": "Lifestyle fotografie",
"focus": { "x": 0.55, "y": 0.6 },
"subject": "tattoo and heather"
},
{
"file": "hero-2.jpg",
"width": 1600,
"height": 1067,
"alt": "Zwangerschapsshoot in de buitenlucht",
"focus": { "x": 0.45, "y": 0.45 },
"subject": "the couple"
},
{
"file": "hero-3.jpg",
"width": 1600,
"height": 1067,
"alt": "Newbornshoot van een pasgeboren baby",
"focus": { "x": 0.45, "y": 0.4 },
"subject": "the baby's face"
},
{
"file": "hero-4.jpg",
"width": 2048,
"height": 1362,
"alt": "Spontaan portret buiten",
"focus": { "x": 0.45, "y": 0.35 },
"subject": "the face"
},
{
"file": "hero-5.jpg",
"width": 1600,
"height": 1067,
"alt": "Natuurlijke lifestylefoto",
"focus": { "x": 0.5, "y": 0.55 },
"subject": "the hands with the ring"
},
{
"file": "hero-6.jpg",
"width": 2048,
"height": 1362,
"alt": "Portret in de natuur",
"focus": { "x": 0.5, "y": 0.35 },
"subject": "the face"
}
]
}
@@ -0,0 +1,287 @@
using System.Text.Json;
using FluentAssertions;
using FsCheck;
using FsCheck.Fluent;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using SlpModularCms.Core.Hosting.Website;
using SlpModularCms.Core.Media;
using SlpModularCms.Modules.Hero.Models;
using SlpModularCms.Modules.Hero.Services;
namespace SlpModularCms.Modules.Hero.Tests;
/// <summary>
/// The HTML written between the hero markers must be exactly what the website expects: the golden files of the website
/// repository (Golden/SOURCE.md names the commit) are run through <see cref="HeroPictureRenderer"/>.
/// </summary>
public class HeroGoldenTests
{
private static string Dir => Path.Combine(AppContext.BaseDirectory, "Golden", "host-injection", "hero");
private static readonly JsonSerializerOptions Web = new(JsonSerializerDefaults.Web);
public static IEnumerable<object[]> Cases()
=> Directory.GetFiles(Dir, "*.input.json").Select(f => new object[] { Path.GetFileName(f)[..^".input.json".Length] }).OrderBy(o => (string)o[0]);
// The expected files end with one newline that is not part of the HTML.
private static string Expected(string file)
{
var text = File.ReadAllText(Path.Combine(Dir, file));
return text.EndsWith('\n') ? text[..^1] : text;
}
private static PublicHeroDto? Input(string name)
=> JsonSerializer.Deserialize<PublicHeroDto?>(File.ReadAllText(Path.Combine(Dir, name + ".input.json")), Web);
[Fact]
public void TheGoldenFiles_AreThere() => Cases().Count().Should().BeGreaterThanOrEqualTo(6);
[Theory]
[MemberData(nameof(Cases))]
public void TheRegion_MatchesTheGoldenFile(string name)
=> HeroPictureRenderer.Render(Input(name)).Region.Should().Be(Expected(name + ".expected.html"));
[Theory]
[MemberData(nameof(Cases))]
public void ThePreload_MatchesTheGoldenFile(string name)
=> HeroPictureRenderer.Render(Input(name)).Preload.Should().Be(Expected(name + ".expected-preload.html"));
[Fact]
public void ThePreloadAndThePicture_ShareTheirSrcsetSizesAndMedia()
{
var injection = HeroPictureRenderer.Render(Input("hero-standard"));
foreach (var set in new[] { "/media/hero/3f9a1c/tall-640.webp 640w, /media/hero/3f9a1c/tall-960.webp 960w", "/media/hero/3f9a1c/wide-960.webp 960w, /media/hero/3f9a1c/wide-1600.webp 1600w" })
{
injection.Region.Should().Contain($"srcset=\"{set}\"");
injection.Preload.Should().Contain($"imagesrcset=\"{set}\"");
}
injection.Region.Should().Contain("media=\"(orientation: portrait)\"");
injection.Preload.Should().Contain("media=\"(orientation: portrait)\"").And.Contain("media=\"(orientation: landscape)\"");
}
}
public class HeroPictureRendererTests
{
private static PublicHeroDto Hero(PublicImageDto? image = null, string title = "Titel", string? tagline = null, params HeroButtonDto[] buttons)
=> new("single", title, tagline, null, buttons,
[new PublicSlideDto("s1", "Een foto", false, image ?? Image())]);
private static PublicImageDto Image(FocusDto? focus = null, params HeroVariantDto[] variants)
=> new(1600, 1067, focus ?? new FocusDto(0.5, 0.5, 1), "/media/hero/0123456789abcdef/wide-1600.webp", variants);
[Theory]
[InlineData(0.5, 0.55, "50% 55%")]
[InlineData(0.455, 0.0, "45.5% 0%")]
[InlineData(1.0, 1.0, "100% 100%")]
[InlineData(0.123456, 0.987654, "12.35% 98.77%")]
public void TheFocus_BecomesAnObjectPosition(double x, double y, string expected)
=> HeroPictureRenderer.Render(Hero(Image(new FocusDto(x, y, 1)))).Region.Should().Contain($" style=\"object-position:{expected}\"");
[Theory]
[InlineData(-0.1, 0.5)]
[InlineData(0.5, 1.1)]
[InlineData(double.NaN, 0.5)]
public void AnInvalidFocus_GivesNoStyle(double x, double y)
=> HeroPictureRenderer.Render(Hero(Image(new FocusDto(x, y, 1)))).Region.Should().NotContain("style=");
[Fact]
public void WithoutATall_ThereIsOnePreload_WithoutMedia()
{
var wide = new HeroVariantDto("wide", 960, 640, "image/webp", "/media/hero/0123456789abcdef/wide-960.webp");
var injection = HeroPictureRenderer.Render(Hero(Image(null, wide)));
injection.Preload.Should().Be("<link rel=\"preload\" as=\"image\" imagesrcset=\"/media/hero/0123456789abcdef/wide-960.webp 960w\" imagesizes=\"100vw\" fetchpriority=\"high\">");
}
[Fact]
public void AvifVariants_NeverAppearInThePictureOrThePreload()
{
var variants = new[]
{
new HeroVariantDto("wide", 960, 640, "image/webp", "/media/hero/0123456789abcdef/wide-960.webp"),
new HeroVariantDto("wide", 960, 640, "image/avif", "/media/hero/0123456789abcdef/wide-960.avif"),
};
var injection = HeroPictureRenderer.Render(Hero(Image(null, variants)));
(injection.Region + injection.Preload).Should().NotContain("avif");
}
[Fact]
public void ATitleWithoutSlides_OrWithoutATitle_RendersNothing()
{
HeroPictureRenderer.Render(new PublicHeroDto("single", "Titel", null, null, [], [])).IsEmpty.Should().BeTrue();
HeroPictureRenderer.Render(Hero(title: " ")).IsEmpty.Should().BeTrue();
HeroPictureRenderer.Render(null).IsEmpty.Should().BeTrue();
}
[Fact]
public void ThePictureIsTheFirstUsableSlide_NotJustTheFirst()
{
var hero = new PublicHeroDto("slideshow", "Titel", null, null, [], [
new PublicSlideDto("a", "", false, Image()),
new PublicSlideDto("b", "Tweede", false, Image()),
]);
HeroPictureRenderer.Render(hero).Region.Should().Contain("alt=\"Tweede\"");
}
[Fact]
public void NoTextOfTheCmsCanBreakOutOfTheHtml()
{
var hero = Hero(Image(), "<script>alert(1)</script>\n\"x\" & 'y'", "<img src=x onerror=alert(1)>", new HeroButtonDto("<b>", "/ok?a=1&b=\"2\""));
var html = HeroPictureRenderer.Render(hero).Region;
html.Should().NotContain("<script").And.NotContain("<img src=x").And.NotContain("<b>");
html.Should().Contain("&lt;script&gt;alert(1)&lt;/script&gt;<br>&quot;x&quot; &amp; &#39;y&#39;");
}
[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("<script");
return true;
}).Check(Config.QuickThrowOnFailure.WithMaxTest(1000));
}
public class HeroHtmlTransformTests
{
private static readonly HtmlTransformContext Context = new("https://test.andreaslop.nl");
private const string Page =
"<head><!--CMS:HERO-PRELOAD-->baked preload<!--/CMS:HERO-PRELOAD--></head>" +
"<body><!--CMS:HERO-HTML-->baked hero<!--/CMS:HERO-HTML--><p>rest</p></body>";
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<IHeroPageModel>();
model.GetAsync(default).ReturnsForAnyArgs(hero);
return new HeroHtmlTransform(model);
}
[Theory]
[InlineData("<p>nothing</p>", false)]
[InlineData("<!--CMS:HERO-HTML--><!--/CMS:HERO-HTML-->", true)]
[InlineData("<!--CMS:HERO-PRELOAD--><!--/CMS:HERO-PRELOAD-->", true)]
[InlineData("<!--CMS:OFFERINGS-HTML--><!--/CMS:OFFERINGS-HTML-->", 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("<!--CMS:HERO-HTML--><picture class=\"cms-hero-picture\">").And.Contain("</h1><!--/CMS:HERO-HTML-->");
html.Should().Contain("<!--CMS:HERO-PRELOAD--><link rel=\"preload\" as=\"image\"").And.Contain("><!--/CMS:HERO-PRELOAD-->");
html.Should().NotContain("baked").And.Contain("<p>rest</p>");
}
[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("<body><!--CMS:HERO-HTML-->x<!--/CMS:HERO-HTML--></body>", 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<IPublicHeroService>();
publicHero.GetActiveAsync(default).ReturnsForAnyArgs(hero);
var store = Substitute.For<IMediaStore>();
store.ExistsAsync(default!, default).ReturnsForAnyArgs(true);
return (new HeroPageModel(publicHero, store, NullLogger<HeroPageModel>.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<PublicHeroDto>();
(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<ICmsDataBlockContributor>();
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("<!--CMS:DATA--><script type=\"application/json\" id=\"cms-data\">{}</script>", new HtmlTransformContext("https://x"), default);
var json = html["<script type=\"application/json\" id=\"cms-data\">".Length..^"</script>".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);
}
}
@@ -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()
{
@@ -27,6 +27,10 @@
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<None Include="Golden\**" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SlpModularCms.Modules.Hero\SlpModularCms.Modules.Hero.csproj" />
</ItemGroup>
@@ -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<IHeroService, HeroService>();
services.AddScoped<IPublicHeroService, PublicHeroService>();
services.AddScoped<IHeroImageService, HeroImageService>();
services.AddScoped<IHeroPageModel, HeroPageModel>();
services.AddScoped<IHtmlPageTransform, HeroHtmlTransform>();
services.AddScoped<ICmsDataBlockContributor, HeroDataContributor>();
services.AddScoped<HeroMediaCleanup>();
services.AddHostedService<HeroMediaCleanupService>();
}
@@ -55,7 +55,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository
=> context.HeroImages.FirstOrDefaultAsync(i => i.Id == id, cancellationToken);
public async Task<IReadOnlyList<HeroImage>> GetImagesAsync(IReadOnlyCollection<Guid> 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<HeroImage?> GetImageBySha256Async(string sha256, CancellationToken cancellationToken)
=> context.HeroImages.FirstOrDefaultAsync(i => i.OriginalSha256 == sha256, cancellationToken);
@@ -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<bool> 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<HeroImageDto> SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken)
{
var image = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException();
@@ -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;
/// <summary>
/// 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.
/// </summary>
public interface IHeroPageModel
{
Task<PublicHeroDto?> GetAsync(CancellationToken cancellationToken);
}
public sealed class HeroPageModel(IPublicHeroService publicHero, IMediaStore store, ILogger<HeroPageModel> logger) : IHeroPageModel
{
public async Task<PublicHeroDto?> 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;
}
}
/// <summary>Fills the hero regions of a page: <c>&lt;!--CMS:HERO-HTML--&gt;</c> in the body and <c>&lt;!--CMS:HERO-PRELOAD--&gt;</c> in the head. Fail-open: no hero means the baked page stays.</summary>
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("<!--" + HtmlRegion + "-->", StringComparison.Ordinal)
|| html.Contains("<!--" + PreloadRegion + "-->", StringComparison.Ordinal);
public async Task<string> 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);
}
}
/// <summary>The <c>hero</c> key of the page data block: the complete public hero (all slides), or null.</summary>
public sealed class HeroDataContributor(IHeroPageModel model) : ICmsDataBlockContributor
{
public string Key => "hero";
public int Order => 200;
public async Task<object?> GetAsync(HtmlTransformContext context, CancellationToken cancellationToken)
=> await model.GetAsync(cancellationToken);
}
@@ -0,0 +1,213 @@
using System.Globalization;
using System.Text;
using SlpModularCms.Modules.Hero.Models;
namespace SlpModularCms.Modules.Hero.Services;
/// <summary>The two pieces written into a page: the hero itself and the preload links for the head. Both empty = leave the baked page.</summary>
public sealed record HeroInjection(string Region, string Preload)
{
public static readonly HeroInjection None = new(string.Empty, string.Empty);
public bool IsEmpty => Region.Length == 0;
}
/// <summary>
/// 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 <c>srcset</c>, <c>sizes</c> and <c>media</c> values are the same text in both. Pure; everything is HTML-encoded.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
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("<picture class=\"cms-hero-picture\">");
if (tall.Length > 0)
{
html.Append("<source media=\"").Append(Portrait).Append("\" srcset=\"").Append(Encode(tall)).Append("\" sizes=\"100vw\" type=\"image/webp\">");
}
html.Append("<img class=\"cms-hero-image\" src=\"").Append(Encode(image.Src)).Append('"');
if (wide.Length > 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\"></picture>");
html.Append("<h1 class=\"cms-hero-title\">");
if (!string.IsNullOrWhiteSpace(hero.Tagline))
{
html.Append("<span class=\"cms-hero-tagline\">").Append(Encode(hero.Tagline)).Append("</span> ");
}
html.Append("<span class=\"cms-hero-name\">").Append(string.Join("<br>", hero.Title.Replace("\r\n", "\n").Split('\n').Select(Encode))).Append("</span></h1>");
var buttons = (hero.Buttons ?? []).Where(IsUsable).Take(2).ToList();
if (buttons.Count > 0)
{
html.Append("<p class=\"cms-hero-buttons\">");
foreach (var button in buttons)
{
html.Append("<a class=\"cms-hero-button\" href=\"").Append(Encode(button.Target)).Append("\">").Append(Encode(button.Label)).Append("</a>");
}
html.Append("</p>");
}
return html.ToString();
}
private static string Preload(string src, string wide, string tall)
{
const string head = "<link rel=\"preload\" as=\"image\"";
const string tail = " fetchpriority=\"high\">";
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);
/// <summary>A path of this host: one leading slash, not a protocol-relative address, no backslash.</summary>
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<HeroVariantDto> 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"));
/// <summary><c>X% Y%</c> from a focus point inside the image (at most two decimals, no trailing zeros), or null without a valid one.</summary>
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("&amp;"); break;
case '<': builder.Append("&lt;"); break;
case '>': builder.Append("&gt;"); break;
case '"': builder.Append("&quot;"); break;
case '\'': builder.Append("&#39;"); break;
default: builder.Append(c); break;
}
}
return builder.ToString();
}
}
@@ -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("<head><!--CMS:DATA--><script type=\"application/json\" id=\"cms-data\">{\"baked\":true}</script></head>", Context, default);
var html = await DataBlock().ApplyAsync("<head><!--CMS:DATA--><script type=\"application/json\" id=\"cms-data\">{\"baked\":true}</script></head>", Context, default);
html.Should().StartWith("<head><script type=\"application/json\" id=\"cms-data\">").And.EndWith("</script></head>");
var json = html["<head><script type=\"application/json\" id=\"cms-data\">".Length..^"</script></head>".Length];
@@ -114,7 +117,7 @@ public class OfferingsHtmlTransformTests
Banner("top", null);
Banner("bottom", null);
var html = await Sut().ApplyAsync("<!--CMS:DATA-->", Context, default);
var html = await DataBlock().ApplyAsync("<!--CMS:DATA-->", Context, default);
var inner = html["<script type=\"application/json\" id=\"cms-data\">".Length..^"</script>".Length];
inner.Should().NotContain("<").And.NotContain(">").And.NotContain("&").And.NotContain("\u2028");
@@ -34,6 +34,8 @@ public class OfferingsModule : IModule
services.AddScoped<IOfferingsService, OfferingsService>();
services.AddScoped<IIndexHtmlMarkerProvider, OfferingsIndexMarkers>();
services.AddScoped<IHtmlPageTransform, OfferingsHtmlTransform>();
services.AddScoped<ICmsDataBlockContributor, OfferingsDataContributor>();
services.AddScoped<ICmsDataBlockContributor, BannersDataContributor>();
services.AddScoped<IOfferingBannerRepository, OfferingBannerRepository>();
services.AddScoped<IOfferingBannersService, OfferingBannersService>();
services.AddScoped<IOfferingCategoryRepository, OfferingCategoryRepository>();
@@ -0,0 +1,30 @@
using SlpModularCms.Core.Hosting.Website;
using SlpModularCms.Modules.Offerings.Data.Entities;
namespace SlpModularCms.Modules.Offerings.Services;
/// <summary>The <c>offerings</c> key of the page data block: the same list the public endpoint answers.</summary>
public sealed class OfferingsDataContributor(IOfferingsService offerings) : ICmsDataBlockContributor
{
public string Key => "offerings";
public int Order => 100;
public async Task<object?> GetAsync(HtmlTransformContext context, CancellationToken cancellationToken)
=> await offerings.GetOfferingsAsync();
}
/// <summary>The <c>banners</c> key of the page data block: the active top and bottom banner (null when there is none).</summary>
public sealed class BannersDataContributor(IOfferingBannersService banners) : ICmsDataBlockContributor
{
public string Key => "banners";
public int Order => 110;
public async Task<object?> GetAsync(HtmlTransformContext context, CancellationToken cancellationToken)
{
var top = await banners.GetActiveAsync(OfferingBannerPositions.Top);
var bottom = await banners.GetActiveAsync(OfferingBannerPositions.Bottom);
return new { top, bottom };
}
}
@@ -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<string> ApplyAsync(string html, HtmlTransformContext context, CancellationToken cancellationToken)
{
var wantsData = html.Contains("<!--" + DataMarker + "-->", StringComparison.Ordinal);
var wantsOfferings = wantsData
|| html.Contains("<!--" + OfferingsRegion + "-->", StringComparison.Ordinal)
var wantsOfferings = html.Contains("<!--" + OfferingsRegion + "-->", StringComparison.Ordinal)
|| html.Contains("<!--" + JsonLdMarker, StringComparison.Ordinal)
|| html.Contains(PriceAttribute + "=", StringComparison.Ordinal);
var wantsTop = wantsData || html.Contains("<!--" + BannerTopRegion + "-->", StringComparison.Ordinal);
var wantsBottom = wantsData || html.Contains("<!--" + BannerBottomRegion + "-->", StringComparison.Ordinal);
var wantsTop = html.Contains("<!--" + BannerTopRegion + "-->", StringComparison.Ordinal);
var wantsBottom = html.Contains("<!--" + BannerBottomRegion + "-->", 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;
}
/// <summary>The data block: the answers of the public API plus the address of the site, safe inside a script element.</summary>
public static string DataBlock(string siteUrl, IReadOnlyList<OfferingDto> live, PublicOfferingBannerDto? top, PublicOfferingBannerDto? bottom)
{
var json = JsonSerializer.Serialize(
new { siteUrl, offerings = live, banners = new { top, bottom } }, ApiJson);
return "<script type=\"application/json\" id=\"" + DataBlockId + "\">" + HtmlMarkerEditor.EscapeForScript(json) + "</script>";
}
private static int? FindPrice(IReadOnlyList<OfferingDto> live, string slug)
=> live.FirstOrDefault(o => string.Equals(o.Slug, slug, StringComparison.Ordinal)) is { } offering
? CmsPageHtml.WholeEuros(offering.Price)