diff --git a/openapi/slpsoftware.v1.json b/openapi/slpsoftware.v1.json index e65cc6b..a13b49e 100644 --- a/openapi/slpsoftware.v1.json +++ b/openapi/slpsoftware.v1.json @@ -927,6 +927,10 @@ "isActive": { "type": "boolean" }, + "ownCrop": { + "default": false, + "type": "boolean" + }, "sortOrder": { "format": "int32", "pattern": "^-?(?:0|[1-9]\\d*)$", @@ -3683,6 +3687,164 @@ ] } }, + "/api/v1/hero/slides/{id}/focus": { + "delete": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroSlideAdminDto" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/HeroSlideAdminDto" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/HeroSlideAdminDto" + } + } + }, + "description": "OK" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + }, + "description": "Not Found" + } + }, + "tags": [ + "HeroSlides" + ] + }, + "put": { + "parameters": [ + { + "in": "path", + "name": "id", + "required": true, + "schema": { + "format": "uuid", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/HeroFocusRequest" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroFocusRequest" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/HeroFocusRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HeroSlideAdminDto" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/HeroSlideAdminDto" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/HeroSlideAdminDto" + } + } + }, + "description": "OK" + }, + "400": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + }, + "description": "Bad Request" + }, + "404": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + }, + "text/plain": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + }, + "description": "Not Found" + } + }, + "tags": [ + "HeroSlides" + ] + } + }, "/api/v1/media-library/cleanup-preview": { "get": { "parameters": [ @@ -4457,6 +4619,9 @@ { "name": "HeroImages" }, + { + "name": "HeroSlides" + }, { "name": "Auth" }, diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroSlideCropTests.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroSlideCropTests.cs new file mode 100644 index 0000000..6b7ce58 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero.Tests/HeroSlideCropTests.cs @@ -0,0 +1,175 @@ +using FluentAssertions; +using SlpModularCms.Modules.Hero.Models; +using SlpModularCms.Modules.Hero.Services; +using Xunit; + +namespace SlpModularCms.Modules.Hero.Tests; + +/// A crop per slide (phase 2, step B): the same photo can have another crop on each slide (Bryan, 2026-11-17). +public class HeroSlideCropTests +{ + private static HeroSaveRequest Request(params HeroSlideRequest[] slides) + => new("Titel", null, null, "slideshow", [], slides); + + private static async Task<(HeroTestRig Rig, Guid ImageId, Guid SlideA, Guid SlideB)> TwoSlidesOnOnePhotoAsync() + { + var rig = new HeroTestRig(); + var image = await rig.Upload(HeroTestRig.Photo()); + var imageId = Guid.Parse(image.Id); + var saved = await rig.Service.SaveAsync(Request(new HeroSlideRequest(null, imageId, "een"), new HeroSlideRequest(null, imageId, "twee")), HeroTestRig.Admin, CancellationToken.None); + return (rig, imageId, Guid.Parse(saved.Slides[0].Id), Guid.Parse(saved.Slides[1].Id)); + } + + [Fact] + public async Task A_slide_without_a_crop_of_its_own_maps_exactly_like_its_photo() + { + var (rig, imageId, slideA, _) = await TwoSlidesOnOnePhotoAsync(); + using var _r = rig; + + var admin = await rig.Service.GetAsync(CancellationToken.None); + var photoSet = rig.Db.HeroImages.Single(i => i.Id == imageId).SetHash; + + admin.Slides.Should().OnlyContain(s => !s.OwnCrop); + var publicHero = (await rig.Public.GetActiveAsync(CancellationToken.None))!; + publicHero.Slides.Should().HaveCount(2); + publicHero.Slides.SelectMany(s => s.Image.Variants).Should().OnlyContain(v => v.Url.Contains(photoSet)); + slideA.Should().NotBeEmpty(); + } + + [Fact] + public async Task Two_slides_with_one_photo_and_different_crops_get_two_sets_and_two_addresses() + { + var (rig, imageId, slideA, slideB) = await TwoSlidesOnOnePhotoAsync(); + using var _r = rig; + var photoSet = rig.Db.HeroImages.Single(i => i.Id == imageId).SetHash; + + var first = await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.1, 0.2, 1.5)), HeroTestRig.Admin, CancellationToken.None); + first.Should().NotBeNull(); + first!.OwnCrop.Should().BeTrue(); + first.Image.Processing.Should().BeTrue("its own set still has to be cut"); + first.Image.Focus.Should().Be(new FocusDto(0.1, 0.2, 1.5)); + + // Until the slide's set is complete the photo's set stays live. + (await rig.Public.GetActiveAsync(CancellationToken.None))!.Slides.SelectMany(s => s.Image.Variants).Should().OnlyContain(v => v.Url.Contains(photoSet)); + + await rig.Images.SetSlideFocusAsync(slideB, new HeroFocusRequest(new FocusDto(0.8, 0.7, 1.2)), HeroTestRig.Admin, CancellationToken.None); + (await rig.RenderPending()).Should().Be(2); + + var slides = rig.Db.HeroSlides.OrderBy(s => s.SortOrder).ToList(); + slides[0].SetHash.Should().NotBeNullOrEmpty().And.NotBe(photoSet); + slides[1].SetHash.Should().NotBeNullOrEmpty().And.NotBe(photoSet).And.NotBe(slides[0].SetHash); + + var publicHero = (await rig.Public.GetActiveAsync(CancellationToken.None))!; + publicHero.Slides[0].Image.Variants.Should().OnlyContain(v => v.Url.Contains(slides[0].SetHash!)); + publicHero.Slides[1].Image.Variants.Should().OnlyContain(v => v.Url.Contains(slides[1].SetHash!)); + publicHero.Slides[0].Image.Focus.Should().Be(new FocusDto(0.1, 0.2, 1.5)); + rig.Db.HeroImages.Single(i => i.Id == imageId).SetHash.Should().Be(photoSet, "the photo's own set and crop are untouched"); + + var admin = await rig.Service.GetAsync(CancellationToken.None); + admin.Slides.Select(s => s.Image.Processing).Should().AllBeEquivalentTo(false); + admin.Slides.Select(s => s.Image.Focus).Should().BeEquivalentTo([new FocusDto(0.1, 0.2, 1.5), new FocusDto(0.8, 0.7, 1.2)], o => o.WithStrictOrdering()); + } + + [Fact] + public async Task The_same_crop_on_two_slides_shares_one_set_and_a_crop_equal_to_the_photos_shares_its_set() + { + var (rig, imageId, slideA, slideB) = await TwoSlidesOnOnePhotoAsync(); + using var _r = rig; + var photo = rig.Db.HeroImages.Single(i => i.Id == imageId); + var photoSet = photo.SetHash; + + await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.3, 0.3, 1.3)), HeroTestRig.Admin, CancellationToken.None); + await rig.Images.SetSlideFocusAsync(slideB, new HeroFocusRequest(new FocusDto(0.3, 0.3, 1.3)), HeroTestRig.Admin, CancellationToken.None); + await rig.RenderPending(); + var slides = rig.Db.HeroSlides.OrderBy(s => s.SortOrder).ToList(); + slides[0].SetHash.Should().Be(slides[1].SetHash, "the set hash is computed from the photo and the crop, so equal crops are one set"); + + // A crop equal to the photo's own crop needs no cutting at all: it shares the photo's set. + await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(photo.FocusX, photo.FocusY, photo.Zoom)), HeroTestRig.Admin, CancellationToken.None); + await rig.RenderPending(); + rig.Db.HeroSlides.Single(s => s.Id == slideA).SetHash.Should().Be(photoSet); + } + + [Fact] + public async Task The_old_set_of_a_slide_stays_live_until_the_new_one_is_complete() + { + var (rig, _, slideA, _) = await TwoSlidesOnOnePhotoAsync(); + using var _r = rig; + await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.2, 0.2, 1.4)), HeroTestRig.Admin, CancellationToken.None); + await rig.RenderPending(); + var firstSet = rig.Db.HeroSlides.Single(s => s.Id == slideA).SetHash; + + var again = await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.6, 0.6, 1.1)), HeroTestRig.Admin, CancellationToken.None); + + again!.Image.Processing.Should().BeTrue(); + rig.Db.HeroSlides.Single(s => s.Id == slideA).SetHash.Should().Be(firstSet); + (await rig.Public.GetActiveAsync(CancellationToken.None))!.Slides[0].Image.Variants.Should().OnlyContain(v => v.Url.Contains(firstSet!)); + + await rig.RenderPending(); + rig.Db.HeroSlides.Single(s => s.Id == slideA).SetHash.Should().NotBe(firstSet); + } + + [Fact] + public async Task Resetting_a_slide_uses_the_photos_crop_and_set_again() + { + var (rig, imageId, slideA, _) = await TwoSlidesOnOnePhotoAsync(); + using var _r = rig; + var photoSet = rig.Db.HeroImages.Single(i => i.Id == imageId).SetHash; + await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.2, 0.2, 1.4)), HeroTestRig.Admin, CancellationToken.None); + await rig.RenderPending(); + + var reset = await rig.Images.ResetSlideFocusAsync(slideA, HeroTestRig.Admin, CancellationToken.None); + + reset!.OwnCrop.Should().BeFalse(); + reset.Image.Processing.Should().BeFalse(); + var slide = rig.Db.HeroSlides.Single(s => s.Id == slideA); + slide.HasOwnCrop.Should().BeFalse(); + slide.SetHash.Should().BeNull(); + (await rig.Public.GetActiveAsync(CancellationToken.None))!.Slides[0].Image.Variants.Should().OnlyContain(v => v.Url.Contains(photoSet)); + } + + [Fact] + public async Task Saving_the_hero_keeps_the_crop_of_a_slide_and_another_photo_drops_it() + { + var (rig, imageId, slideA, slideB) = await TwoSlidesOnOnePhotoAsync(); + using var _r = rig; + await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.2, 0.2, 1.4)), HeroTestRig.Admin, CancellationToken.None); + await rig.RenderPending(); + var other = await rig.Upload(HeroTestRig.Photo(seed: 9)); + + await rig.Service.SaveAsync(Request(new HeroSlideRequest(slideA, imageId, "een, aangepast"), new HeroSlideRequest(slideB, Guid.Parse(other.Id), "twee")), HeroTestRig.Admin, CancellationToken.None); + rig.Db.HeroSlides.Single(s => s.Id == slideA).HasOwnCrop.Should().BeTrue("saving the texts does not touch the crop"); + + await rig.Service.SaveAsync(Request(new HeroSlideRequest(slideA, Guid.Parse(other.Id), "een"), new HeroSlideRequest(slideB, Guid.Parse(other.Id), "twee")), HeroTestRig.Admin, CancellationToken.None); + rig.Db.HeroSlides.Single(s => s.Id == slideA).HasOwnCrop.Should().BeFalse("a crop made for another photo means nothing"); + } + + [Fact] + public async Task An_unknown_slide_gives_null() + { + using var rig = new HeroTestRig(); + var request = new HeroFocusRequest(new FocusDto(0.5, 0.5, 1)); + + (await rig.Images.SetSlideFocusAsync(Guid.NewGuid(), request, HeroTestRig.Admin, CancellationToken.None)).Should().BeNull(); + (await rig.Images.ResetSlideFocusAsync(Guid.NewGuid(), HeroTestRig.Admin, CancellationToken.None)).Should().BeNull(); + } + + [Fact] + public async Task The_clean_up_keeps_the_set_of_a_slide_and_a_slide_set_nobody_uses_goes_after_the_retention() + { + var (rig, _, slideA, _) = await TwoSlidesOnOnePhotoAsync(); + using var _r = rig; + await rig.Images.SetSlideFocusAsync(slideA, new HeroFocusRequest(new FocusDto(0.2, 0.2, 1.4)), HeroTestRig.Admin, CancellationToken.None); + await rig.RenderPending(); + var slideSet = rig.Db.HeroSlides.Single(s => s.Id == slideA).SetHash!; + rig.Time.Now = rig.Time.Now.AddDays(30); + + await rig.Cleanup.RunOnceAsync(CancellationToken.None); + (await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Select(x => x.SetHash).Should().Contain(slideSet, "a slide uses it"); + + await rig.Images.ResetSlideFocusAsync(slideA, HeroTestRig.Admin, CancellationToken.None); + rig.Time.Now = rig.Time.Now.AddDays(30); + await rig.Cleanup.RunOnceAsync(CancellationToken.None); + (await rig.Store.ListSetsAsync("hero", CancellationToken.None)).Select(x => x.SetHash).Should().NotContain(slideSet); + } +} diff --git a/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs index e1d05f9..625fb46 100644 --- a/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs +++ b/src/SlpModularCms.Modules.Hero/Controllers/HeroControllers.cs @@ -180,6 +180,37 @@ public class HeroImagesController(IHeroImageService service, IOptionsThe crop of one slide (crop per use). Administrators only. +[ApiController] +[Route("hero/slides")] +[Authorize(Policy = "AdminOnly")] +public class HeroSlidesController(IHeroImageService service) : ControllerBase +{ + /// + /// A crop for this slide only, applied at once without saving the hero. The same photo on another slide keeps its own + /// crop. Answers with the slide as the admin sees it (processing while its set is being cut). + /// + [HttpPut("{id:guid}/focus")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task SetFocus(Guid id, [FromBody] HeroFocusRequest request, CancellationToken cancellationToken) + { + var slide = await service.SetSlideFocusAsync(id, request, HeroCaller.Id(User), cancellationToken); + return slide is null ? NotFound(new { error = "not_found", message = HttpTexts.From(HttpContext).Get(HeroTexts.Image.NotFound) }) : Ok(slide); + } + + /// Takes the slide's own crop away: it uses the crop of its photo again. + [HttpDelete("{id:guid}/focus")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + public async Task ResetFocus(Guid id, CancellationToken cancellationToken) + { + var slide = await service.ResetSlideFocusAsync(id, HeroCaller.Id(User), cancellationToken); + return slide is null ? NotFound(new { error = "not_found", message = HttpTexts.From(HttpContext).Get(HeroTexts.Image.NotFound) }) : Ok(slide); + } +} + internal static class HeroCaller { public static Guid Id(ClaimsPrincipal user) diff --git a/src/SlpModularCms.Modules.Hero/Data/Entities/HeroEntities.cs b/src/SlpModularCms.Modules.Hero/Data/Entities/HeroEntities.cs index 5c825b3..5eb885e 100644 --- a/src/SlpModularCms.Modules.Hero/Data/Entities/HeroEntities.cs +++ b/src/SlpModularCms.Modules.Hero/Data/Entities/HeroEntities.cs @@ -34,6 +34,34 @@ public class HeroSlide public bool Decorative { get; set; } public int SortOrder { get; set; } public bool IsActive { get; set; } = true; + + // The slide's OWN crop (phase 2, crop per use). All null = no override: the slide uses its photo's crop and set exactly + // as before. FocusX/FocusY/Zoom set = the slide has its own crop (the wide and tall overrides are optional on top). + public double? FocusX { get; set; } + public double? FocusY { get; set; } + public double? Zoom { get; set; } + public double? WideFocusX { get; set; } + public double? WideFocusY { get; set; } + public double? WideZoom { get; set; } + public double? TallFocusX { get; set; } + public double? TallFocusY { get; set; } + public double? TallZoom { get; set; } + + /// The set cut for the slide's own crop; empty until it is complete (the photo's set stays live until then). + public string? SetHash { get; set; } + public List? Variants { get; set; } + + /// True when the slide has a crop of its own. + public bool HasOwnCrop => FocusX is not null && FocusY is not null; + + public void ClearOwnCrop() + { + (FocusX, FocusY, Zoom) = (null, null, null); + (WideFocusX, WideFocusY, WideZoom) = (null, null, null); + (TallFocusX, TallFocusY, TallZoom) = (null, null, null); + SetHash = null; + Variants = null; + } } /// A stored image: the original (never served), where the subject is, and the current set of variants. diff --git a/src/SlpModularCms.Modules.Hero/Data/HeroDbContext.cs b/src/SlpModularCms.Modules.Hero/Data/HeroDbContext.cs index 8bc1846..6942f69 100644 --- a/src/SlpModularCms.Modules.Hero/Data/HeroDbContext.cs +++ b/src/SlpModularCms.Modules.Hero/Data/HeroDbContext.cs @@ -44,6 +44,17 @@ public class HeroDbContext(DbContextOptions options) : DbContext( // Not unique: re-ordering updates several rows in one save and must not trip over itself. entity.HasIndex(e => new { e.HeroId, e.SortOrder }); entity.HasIndex(e => e.ImageId); + entity.Ignore(e => e.HasOwnCrop); + entity.Property(e => e.SetHash).HasMaxLength(16); + entity.Property(e => e.Variants) + .HasConversion( + variants => variants == null ? null : JsonSerializer.Serialize(variants, (JsonSerializerOptions?)null), + json => json == null ? null : JsonSerializer.Deserialize>(json, (JsonSerializerOptions?)null)) + .HasColumnType("longtext") + .Metadata.SetValueComparer(new ValueComparer?>( + (a, b) => (a ?? new List()).SequenceEqual(b ?? new List()), + v => v == null ? 0 : v.Aggregate(0, (hash, item) => HashCode.Combine(hash, item.GetHashCode())), + v => v == null ? null : v.ToList())); // Restrict: an image that a slide still uses cannot be deleted (the service answers 409 first). entity.HasOne(e => e.Image).WithMany().HasForeignKey(e => e.ImageId).OnDelete(DeleteBehavior.Restrict); diff --git a/src/SlpModularCms.Modules.Hero/Migrations/20261117202757_AddSlideCrop.Designer.cs b/src/SlpModularCms.Modules.Hero/Migrations/20261117202757_AddSlideCrop.Designer.cs new file mode 100644 index 0000000..53eb562 --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Migrations/20261117202757_AddSlideCrop.Designer.cs @@ -0,0 +1,291 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using SlpModularCms.Modules.Hero.Data; + +#nullable disable + +namespace SlpModularCms.Modules.Hero.Migrations +{ + [DbContext(typeof(HeroDbContext))] + [Migration("20261117202757_AddSlideCrop")] + partial class AddSlideCrop + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.9") + .HasAnnotation("Relational:MaxIdentifierLength", 64); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Button1Label") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Button1Target") + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("Button2Label") + .HasMaxLength(100) + .HasColumnType("varchar(100)"); + + b.Property("Button2Target") + .HasMaxLength(500) + .HasColumnType("varchar(500)"); + + b.Property("Display") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("varchar(20)"); + + b.Property("Language") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("LastModifiedByUserId") + .HasColumnType("char(36)"); + + b.Property("Lead") + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("Tagline") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(1000) + .HasColumnType("varchar(1000)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.HasIndex("Language") + .IsUnique(); + + b.ToTable("Heroes", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroImage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Bytes") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime"); + + b.Property("CreatedByUserId") + .HasColumnType("char(36)"); + + b.Property("DeletedAt") + .HasColumnType("datetime"); + + b.Property("FocusX") + .HasColumnType("double"); + + b.Property("FocusY") + .HasColumnType("double"); + + b.Property("Height") + .HasColumnType("int"); + + b.Property("LastUsedAt") + .HasColumnType("datetime"); + + b.Property("OriginalFileName") + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("OriginalKey") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("OriginalSha256") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("varchar(64)"); + + b.Property("SetHash") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("SourceFormat") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("TallFocusX") + .HasColumnType("double"); + + b.Property("TallFocusY") + .HasColumnType("double"); + + b.Property("TallZoom") + .HasColumnType("double"); + + b.Property("Variants") + .IsRequired() + .HasColumnType("longtext"); + + b.Property("WideFocusX") + .HasColumnType("double"); + + b.Property("WideFocusY") + .HasColumnType("double"); + + b.Property("WideZoom") + .HasColumnType("double"); + + b.Property("Width") + .HasColumnType("int"); + + b.Property("Zoom") + .HasColumnType("double"); + + b.HasKey("Id"); + + b.HasIndex("OriginalSha256") + .IsUnique(); + + b.ToTable("HeroImages", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroRetiredFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Key") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("varchar(200)"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("varchar(10)"); + + b.Property("RetiredAt") + .HasColumnType("datetime"); + + b.HasKey("Id"); + + b.ToTable("HeroRetiredFiles", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroSlide", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("char(36)"); + + b.Property("Alt") + .IsRequired() + .HasMaxLength(600) + .HasColumnType("varchar(600)"); + + b.Property("Decorative") + .HasColumnType("tinyint(1)"); + + b.Property("FocusX") + .HasColumnType("double"); + + b.Property("FocusY") + .HasColumnType("double"); + + b.Property("HeroId") + .HasColumnType("char(36)"); + + b.Property("ImageId") + .HasColumnType("char(36)"); + + b.Property("IsActive") + .HasColumnType("tinyint(1)"); + + b.Property("SetHash") + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("TallFocusX") + .HasColumnType("double"); + + b.Property("TallFocusY") + .HasColumnType("double"); + + b.Property("TallZoom") + .HasColumnType("double"); + + b.Property("Variants") + .HasColumnType("longtext"); + + b.Property("WideFocusX") + .HasColumnType("double"); + + b.Property("WideFocusY") + .HasColumnType("double"); + + b.Property("WideZoom") + .HasColumnType("double"); + + b.Property("Zoom") + .HasColumnType("double"); + + b.HasKey("Id"); + + b.HasIndex("ImageId"); + + b.HasIndex("HeroId", "SortOrder"); + + b.ToTable("HeroSlides", (string)null); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroSlide", b => + { + b.HasOne("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", null) + .WithMany("Slides") + .HasForeignKey("HeroId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("SlpModularCms.Modules.Hero.Data.Entities.HeroImage", "Image") + .WithMany() + .HasForeignKey("ImageId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Image"); + }); + + modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroContent", b => + { + b.Navigation("Slides"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/SlpModularCms.Modules.Hero/Migrations/20261117202757_AddSlideCrop.cs b/src/SlpModularCms.Modules.Hero/Migrations/20261117202757_AddSlideCrop.cs new file mode 100644 index 0000000..966814d --- /dev/null +++ b/src/SlpModularCms.Modules.Hero/Migrations/20261117202757_AddSlideCrop.cs @@ -0,0 +1,129 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace SlpModularCms.Modules.Hero.Migrations +{ + /// + public partial class AddSlideCrop : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "FocusX", + table: "HeroSlides", + type: "double", + nullable: true); + + migrationBuilder.AddColumn( + name: "FocusY", + table: "HeroSlides", + type: "double", + nullable: true); + + migrationBuilder.AddColumn( + name: "SetHash", + table: "HeroSlides", + type: "varchar(16)", + maxLength: 16, + nullable: true); + + migrationBuilder.AddColumn( + name: "TallFocusX", + table: "HeroSlides", + type: "double", + nullable: true); + + migrationBuilder.AddColumn( + name: "TallFocusY", + table: "HeroSlides", + type: "double", + nullable: true); + + migrationBuilder.AddColumn( + name: "TallZoom", + table: "HeroSlides", + type: "double", + nullable: true); + + migrationBuilder.AddColumn( + name: "Variants", + table: "HeroSlides", + type: "longtext", + nullable: true); + + migrationBuilder.AddColumn( + name: "WideFocusX", + table: "HeroSlides", + type: "double", + nullable: true); + + migrationBuilder.AddColumn( + name: "WideFocusY", + table: "HeroSlides", + type: "double", + nullable: true); + + migrationBuilder.AddColumn( + name: "WideZoom", + table: "HeroSlides", + type: "double", + nullable: true); + + migrationBuilder.AddColumn( + name: "Zoom", + table: "HeroSlides", + type: "double", + nullable: true); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "FocusX", + table: "HeroSlides"); + + migrationBuilder.DropColumn( + name: "FocusY", + table: "HeroSlides"); + + migrationBuilder.DropColumn( + name: "SetHash", + table: "HeroSlides"); + + migrationBuilder.DropColumn( + name: "TallFocusX", + table: "HeroSlides"); + + migrationBuilder.DropColumn( + name: "TallFocusY", + table: "HeroSlides"); + + migrationBuilder.DropColumn( + name: "TallZoom", + table: "HeroSlides"); + + migrationBuilder.DropColumn( + name: "Variants", + table: "HeroSlides"); + + migrationBuilder.DropColumn( + name: "WideFocusX", + table: "HeroSlides"); + + migrationBuilder.DropColumn( + name: "WideFocusY", + table: "HeroSlides"); + + migrationBuilder.DropColumn( + name: "WideZoom", + table: "HeroSlides"); + + migrationBuilder.DropColumn( + name: "Zoom", + table: "HeroSlides"); + } + } +} diff --git a/src/SlpModularCms.Modules.Hero/Migrations/HeroDbContextModelSnapshot.cs b/src/SlpModularCms.Modules.Hero/Migrations/HeroDbContextModelSnapshot.cs index 822eb07..5803ae9 100644 --- a/src/SlpModularCms.Modules.Hero/Migrations/HeroDbContextModelSnapshot.cs +++ b/src/SlpModularCms.Modules.Hero/Migrations/HeroDbContextModelSnapshot.cs @@ -206,6 +206,12 @@ namespace SlpModularCms.Modules.Hero.Migrations b.Property("Decorative") .HasColumnType("tinyint(1)"); + b.Property("FocusX") + .HasColumnType("double"); + + b.Property("FocusY") + .HasColumnType("double"); + b.Property("HeroId") .HasColumnType("char(36)"); @@ -215,9 +221,37 @@ namespace SlpModularCms.Modules.Hero.Migrations b.Property("IsActive") .HasColumnType("tinyint(1)"); + b.Property("SetHash") + .HasMaxLength(16) + .HasColumnType("varchar(16)"); + b.Property("SortOrder") .HasColumnType("int"); + b.Property("TallFocusX") + .HasColumnType("double"); + + b.Property("TallFocusY") + .HasColumnType("double"); + + b.Property("TallZoom") + .HasColumnType("double"); + + b.Property("Variants") + .HasColumnType("longtext"); + + b.Property("WideFocusX") + .HasColumnType("double"); + + b.Property("WideFocusY") + .HasColumnType("double"); + + b.Property("WideZoom") + .HasColumnType("double"); + + b.Property("Zoom") + .HasColumnType("double"); + b.HasKey("Id"); b.HasIndex("ImageId"); diff --git a/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs b/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs index 1bf836b..b23941d 100644 --- a/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs +++ b/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs @@ -33,7 +33,8 @@ public record HeroImageDto( public record HeroButtonDto(string Label, string Target); -public record HeroSlideAdminDto(string Id, string ImageId, string Alt, bool Decorative, bool IsActive, int SortOrder, HeroImageDto Image); +/// A slide for the admin. is the photo as THIS slide shows it (its own crop and set when ); its Id is always the photo's id. +public record HeroSlideAdminDto(string Id, string ImageId, string Alt, bool Decorative, bool IsActive, int SortOrder, HeroImageDto Image, bool OwnCrop = false); /// What the admin edits. When no hero exists yet is null and the fields hold the defaults. public record HeroAdminDto( diff --git a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs index 9aa01c1..d485d55 100644 --- a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs +++ b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs @@ -48,6 +48,15 @@ public interface IHeroRepository Task> GetImagesNeedingRenderAsync(CancellationToken cancellationToken); + /// One slide with its photo, tracked (a new crop for the slide); null when there is none or its photo is in the trash. + Task GetSlideAsync(Guid id, CancellationToken cancellationToken); + + /// The slide as stored right now, with its photo, not tracked. + Task GetSlideFreshAsync(Guid id, CancellationToken cancellationToken); + + /// Slides with a crop of their own whose set is missing or does not match that crop, in hero order (tracked). + Task> GetSlidesNeedingRenderAsync(CancellationToken cancellationToken); + /// Images with a complete set made before the full-frame preview existed (tracked). Task> GetImagesNeedingPreviewAsync(CancellationToken cancellationToken); @@ -133,6 +142,18 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository public async Task> GetImagesNeedingPreviewAsync(CancellationToken cancellationToken) => (await context.HeroImages.Where(i => i.DeletedAt == null).ToListAsync(cancellationToken)).Where(HeroMapping.NeedsPreview).OrderBy(i => i.CreatedAt).ToList(); + public Task GetSlideAsync(Guid id, CancellationToken cancellationToken) + => context.HeroSlides.Include(s => s.Image).FirstOrDefaultAsync(s => s.Id == id && s.Image != null && s.Image.DeletedAt == null, cancellationToken); + + public Task GetSlideFreshAsync(Guid id, CancellationToken cancellationToken) + => context.HeroSlides.AsNoTracking().Include(s => s.Image).FirstOrDefaultAsync(s => s.Id == id && s.Image != null && s.Image.DeletedAt == null, cancellationToken); + + public async Task> GetSlidesNeedingRenderAsync(CancellationToken cancellationToken) + => (await context.HeroSlides.Include(s => s.Image).Where(s => s.FocusX != null && s.FocusY != null).ToListAsync(cancellationToken)) + .Where(s => s.Image is { DeletedAt: null } && HeroMapping.SlideNeedsRender(s)) + .OrderBy(s => s.SortOrder) + .ToList(); + public Task GetImageFreshAsync(Guid id, CancellationToken cancellationToken) => context.HeroImages.AsNoTracking().FirstOrDefaultAsync(i => i.Id == id && i.DeletedAt == null, cancellationToken); @@ -154,7 +175,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository } public async Task> GetReferencedSetHashesAsync(CancellationToken cancellationToken) - => (await context.HeroImages.Select(i => i.SetHash).ToListAsync(cancellationToken)).ToHashSet(StringComparer.Ordinal); + { + // The sets of the photos and the own sets of slides with a crop of their own. + var sets = (await context.HeroImages.Select(i => i.SetHash).ToListAsync(cancellationToken)).ToHashSet(StringComparer.Ordinal); + sets.UnionWith((await context.HeroSlides.Select(s => s.SetHash).ToListAsync(cancellationToken)).Where(h => !string.IsNullOrEmpty(h))!); + return sets; + } public async Task> GetReferencedOriginalKeysAsync(CancellationToken cancellationToken) => (await context.HeroImages.Select(i => i.OriginalKey).ToListAsync(cancellationToken)).ToHashSet(StringComparer.Ordinal); diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs index 80eca6d..9e97095 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroImageService.cs @@ -54,6 +54,16 @@ public interface IHeroImageService /// Task SetFocusAsync(Guid imageId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken); + /// + /// A crop for ONE slide (crop per use): the same photo can have another crop on another slide. Applied at once, without + /// saving the hero; the slide's own set is cut in the background and the slide switches to it when it is complete (until + /// then it shows the photo's set). Returns the slide as the admin sees it (processing), or null when there is no such slide. + /// + Task SetSlideFocusAsync(Guid slideId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken); + + /// Takes the slide's own crop away: it uses the photo's crop and set again. Null when there is no such slide. + Task ResetSlideFocusAsync(Guid slideId, Guid callerId, CancellationToken cancellationToken); + /// One image as the admin sees it now (including whether it is still being prepared). Null when there is no such image. Task GetImageAsync(Guid imageId, CancellationToken cancellationToken); @@ -219,6 +229,67 @@ public class HeroImageService( return await GetImageAsync(imageId, cancellationToken); } + public async Task SetSlideFocusAsync(Guid slideId, HeroFocusRequest request, Guid callerId, CancellationToken cancellationToken) + { + var slide = await repository.GetSlideAsync(slideId, cancellationToken); + if (slide is null) + { + return null; + } + + var general = request.Focus.ToSetting().Normalize(); + (slide.FocusX, slide.FocusY, slide.Zoom) = (general.X, general.Y, general.Zoom); + Apply(request.Wide, v => (slide.WideFocusX, slide.WideFocusY, slide.WideZoom) = v); + Apply(request.Tall, v => (slide.TallFocusX, slide.TallFocusY, slide.TallZoom) = v); + await repository.SaveChangesAsync(cancellationToken); + signal?.Reset(slideId); + signal?.Notify(); + + logger.LogInformation("Hero slide {SlideId} got a crop of its own from user {UserId}; its variants are cut in the background", slideId, callerId); + return await GetSlideAsync(slideId, cancellationToken); + } + + public async Task ResetSlideFocusAsync(Guid slideId, Guid callerId, CancellationToken cancellationToken) + { + var slide = await repository.GetSlideAsync(slideId, cancellationToken); + if (slide is null) + { + return null; + } + + var oldSet = slide.SetHash; + slide.ClearOwnCrop(); + if (!string.IsNullOrEmpty(oldSet) && oldSet != slide.Image!.SetHash) + { + repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = oldSet, RetiredAt = _time.GetUtcNow() }); + } + + await repository.SaveChangesAsync(cancellationToken); + signal?.Reset(slideId); + indexCache?.Invalidate(); + + logger.LogInformation("Hero slide {SlideId} uses the crop of its photo again (reset by user {UserId})", slideId, callerId); + return await GetSlideAsync(slideId, cancellationToken); + } + + private async Task GetSlideAsync(Guid slideId, CancellationToken cancellationToken) + { + var slide = await repository.GetSlideFreshAsync(slideId, cancellationToken); + if (slide is null) + { + return null; + } + + var dto = HeroMapping.ToSlideAdmin(slide); + if (!slide.HasOwnCrop) + { + return dto; + } + + var progress = RenderProgress(slideId); + return dto with { Image = dto.Image with { Failed = IsRenderFailed(slideId), RenderDone = progress?.Done, RenderTotal = progress?.Total } }; + } + public async Task GetImageAsync(Guid imageId, CancellationToken cancellationToken) { var image = await repository.GetImageFreshAsync(imageId, cancellationToken); @@ -238,19 +309,43 @@ public class HeroImageService( public async Task RetryRenderAsync(Guid imageId, CancellationToken cancellationToken) { - _ = await repository.GetImageAsync(imageId, cancellationToken) ?? throw new HeroImageNotFoundException(); + // The id is a photo's or the id of a slide with a crop of its own (both are renderer keys). + if (await repository.GetImageAsync(imageId, cancellationToken) is null && await repository.GetSlideAsync(imageId, cancellationToken) is null) + { + throw new HeroImageNotFoundException(); + } + signal?.Reset(imageId); signal?.Notify(); } public async Task<(int Total, int NeedRender, int NeedPreview)> GetRenderBacklogAsync(CancellationToken cancellationToken) - => (await repository.CountImagesAsync(cancellationToken), (await repository.GetImagesNeedingRenderAsync(cancellationToken)).Count, (await repository.GetImagesNeedingPreviewAsync(cancellationToken)).Count); + => (await repository.CountImagesAsync(cancellationToken), (await repository.GetImagesNeedingRenderAsync(cancellationToken)).Count + (await repository.GetSlidesNeedingRenderAsync(cancellationToken)).Count, (await repository.GetImagesNeedingPreviewAsync(cancellationToken)).Count); public async Task RenderNextPendingAsync(IReadOnlySet skip, CancellationToken cancellationToken) { var image = (await repository.GetImagesNeedingRenderAsync(cancellationToken)).FirstOrDefault(i => !skip.Contains(i.Id)); if (image is null) { + // Then the slides that have a crop of their own. + var slide = (await repository.GetSlidesNeedingRenderAsync(cancellationToken)).FirstOrDefault(s => !skip.Contains(s.Id)); + if (slide is not null) + { + try + { + return await RenderSlideAsync(slide, cancellationToken); + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + logger.LogError(exception, "Hero slide {SlideId}: cutting the variants failed.", slide.Id); + throw new HeroImageRenderException(slide.Id, exception); + } + finally + { + signal?.ClearProgress(slide.Id); + } + } + // Nothing to cut: add the full-frame preview to complete sets that were made before it existed. var old = (await repository.GetImagesNeedingPreviewAsync(cancellationToken)).FirstOrDefault(i => !skip.Contains(i.Id)); return old is null ? null : await AddPreviewAsync(old, cancellationToken); @@ -305,6 +400,65 @@ public class HeroImageService( } } + /// Cuts the set of a slide's own crop. A crop equal to the photo's own crop shares the photo's set (same hash, no cutting). + private async Task RenderSlideAsync(HeroSlide slide, CancellationToken cancellationToken) + { + var photo = slide.Image!; + var effective = HeroMapping.Effective(slide)!; + var target = HeroMapping.TargetSetHash(effective); + var oldSet = slide.SetHash ?? string.Empty; + + if (target == photo.SetHash && photo.Variants.Count > 0) + { + slide.SetHash = target; + slide.Variants = [.. photo.Variants]; + await repository.SaveChangesAsync(cancellationToken); + indexCache?.Invalidate(); + logger.LogInformation("Hero slide {SlideId}: its crop equals the crop of its photo, so it shares the photo's set.", slide.Id); + return slide.Id; + } + + var watch = System.Diagnostics.Stopwatch.StartNew(); + logger.LogInformation("Hero slide {SlideId}: cutting the variants of its own crop starts ({Width}x{Height}).", slide.Id, photo.Width, photo.Height); + Dictionary files; + List variants; + using (await gate.EnterAsync(cancellationToken)) + { + var file = await store.OpenReadAsync(photo.OriginalKey, cancellationToken) + ?? throw new ImageRejectedException(ImageRejection.Unavailable, "The stored original is missing."); + using var memory = new MemoryStream(); + await using (file.Content) + { + await file.Content.CopyToAsync(memory, cancellationToken); + } + + var storedFormat = ImageFormatExtensions.FromExtension(Path.GetExtension(photo.OriginalKey).TrimStart('.')); + (files, variants) = await RenderSetAsync(effective, memory.ToArray(), storedFormat, (done, total) => signal?.SetProgress(slide.Id, done, total), cancellationToken); + } + + await store.PutSetAsync(HeroMapping.Area, target, files, cancellationToken); + + // The crop may have changed (or the slide may be gone) while the set was cut: then it stays pending at the newest crop. + var current = await repository.GetSlideFreshAsync(slide.Id, cancellationToken); + if (current is null || !current.HasOwnCrop || HeroMapping.TargetSetHash(HeroMapping.Effective(current)!) != target) + { + logger.LogInformation("Hero slide {SlideId}: recut superseded, its crop changed while its variants were being cut.", slide.Id); + return slide.Id; + } + + slide.SetHash = target; + slide.Variants = variants; + if (oldSet.Length > 0 && oldSet != target) + { + repository.AddRetired(new HeroRetiredFile { Id = Guid.NewGuid(), Kind = "set", Key = oldSet, RetiredAt = _time.GetUtcNow() }); + } + + await repository.SaveChangesAsync(cancellationToken); + indexCache?.Invalidate(); + logger.LogInformation("Hero slide {SlideId}: {Variants} variants cut in {Seconds:0.0} s", slide.Id, variants.Count, watch.Elapsed.TotalSeconds); + return slide.Id; + } + private async Task RenderAsync(HeroImage image, CancellationToken cancellationToken) { diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroMapping.cs b/src/SlpModularCms.Modules.Hero/Services/HeroMapping.cs index f32ed56..159c96e 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroMapping.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroMapping.cs @@ -47,6 +47,49 @@ public static class HeroMapping _ => format.ToString().ToUpperInvariant(), }; + /// + /// The photo as a slide shows it: the photo itself when the slide has no crop of its own, else a copy of the photo with the + /// slide's crop and, once complete, the slide's own set (until then the photo's set stays live). Never saved. + /// + public static HeroImage? Effective(HeroSlide slide) + { + var photo = slide.Image; + if (photo is null || !slide.HasOwnCrop) + { + return photo; + } + + var ready = slide.Variants is { Count: > 0 } && !string.IsNullOrEmpty(slide.SetHash); + return new HeroImage + { + Id = photo.Id, + OriginalSha256 = photo.OriginalSha256, + OriginalKey = photo.OriginalKey, + SourceFormat = photo.SourceFormat, + Width = photo.Width, + Height = photo.Height, + Bytes = photo.Bytes, + CreatedAt = photo.CreatedAt, + CreatedByUserId = photo.CreatedByUserId, + FocusX = slide.FocusX!.Value, + FocusY = slide.FocusY!.Value, + Zoom = slide.Zoom ?? 1.0, + WideFocusX = slide.WideFocusX, + WideFocusY = slide.WideFocusY, + WideZoom = slide.WideZoom, + TallFocusX = slide.TallFocusX, + TallFocusY = slide.TallFocusY, + TallZoom = slide.TallZoom, + SetHash = ready ? slide.SetHash! : photo.SetHash, + Variants = ready ? slide.Variants! : photo.Variants, + }; + } + + /// True when the slide has its own crop and its own set is missing or was cut for another crop (the work of the renderer). + public static bool SlideNeedsRender(HeroSlide slide) + => slide.HasOwnCrop && slide.Image is not null && Effective(slide) is { } effective + && (slide.Variants is not { Count: > 0 } || slide.SetHash != TargetSetHash(effective)); + /// The variants websites and the admin lists use: everything except the full-frame preview. public static IEnumerable Published(HeroImage image) => image.Variants.Where(v => v.Ratio != VariantPlanner.PreviewRatioName); @@ -121,10 +164,11 @@ public static class HeroMapping } var slides = hero.Slides - .Where(s => s.IsActive && s.Image is { Variants.Count: > 0 } && (s.Decorative || !string.IsNullOrWhiteSpace(s.Alt))) - .OrderBy(s => s.SortOrder) + .Select(s => (Slide: s, Image: Effective(s))) + .Where(x => x.Slide.IsActive && x.Image is { Variants.Count: > 0 } && (x.Slide.Decorative || !string.IsNullOrWhiteSpace(x.Slide.Alt))) + .OrderBy(x => x.Slide.SortOrder) .Take(Math.Max(1, maxPublishedSlides)) - .Select(s => new PublicSlideDto(s.Id.ToString(), s.Decorative ? string.Empty : s.Alt, s.Decorative, ToPublicImage(s.Image!))) + .Select(x => new PublicSlideDto(x.Slide.Id.ToString(), x.Slide.Decorative ? string.Empty : x.Slide.Alt, x.Slide.Decorative, ToPublicImage(x.Image!))) .ToList(); return new PublicHeroDto(hero.Display, hero.Title, hero.Tagline, hero.Lead, Buttons(hero), slides); @@ -152,6 +196,10 @@ public static class HeroMapping byRatio); } + /// One slide for the admin, with the photo as the slide shows it. + public static HeroSlideAdminDto ToSlideAdmin(HeroSlide s) + => new(s.Id.ToString(), s.ImageId.ToString(), s.Alt, s.Decorative, s.IsActive, s.SortOrder, ToImageDto(Effective(s)!), s.HasOwnCrop); + public static HeroAdminDto ToAdmin(HeroContent? hero, DateTimeOffset now, int maxPublishedSlides) { if (hero is null) @@ -162,7 +210,7 @@ public static class HeroMapping var slides = hero.Slides .Where(s => s.Image is not null) .OrderBy(s => s.SortOrder) - .Select(s => new HeroSlideAdminDto(s.Id.ToString(), s.ImageId.ToString(), s.Alt, s.Decorative, s.IsActive, s.SortOrder, ToImageDto(s.Image!))) + .Select(s => new HeroSlideAdminDto(s.Id.ToString(), s.ImageId.ToString(), s.Alt, s.Decorative, s.IsActive, s.SortOrder, ToImageDto(Effective(s)!), s.HasOwnCrop)) .ToList(); return new HeroAdminDto( diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroService.cs b/src/SlpModularCms.Modules.Hero/Services/HeroService.cs index 162b691..b32245a 100644 --- a/src/SlpModularCms.Modules.Hero/Services/HeroService.cs +++ b/src/SlpModularCms.Modules.Hero/Services/HeroService.cs @@ -44,7 +44,8 @@ public class HeroService( { Slides = dto.Slides.Select(s => { - var id = Guid.Parse(s.ImageId); + // A slide with its own crop is cut under its own id (its progress and failures are the slide's, not the photo's). + var id = s.OwnCrop ? Guid.Parse(s.Id) : Guid.Parse(s.ImageId); var progress = imageService.RenderProgress(id); var failed = imageService.IsRenderFailed(id); return failed || progress is not null @@ -113,6 +114,12 @@ public class HeroService( } keep.Add(slide.Id); + if (slide.ImageId != r.ImageId && slide.ImageId != Guid.Empty) + { + // Another photo on the slide: a crop made for the old photo means nothing for the new one. + slide.ClearOwnCrop(); + } + slide.ImageId = r.ImageId; slide.Image = images[r.ImageId]; slide.Decorative = r.Decorative;