Files
slp-modular-cms/src/SlpModularCms.Modules.Hero/Models/HeroModels.cs
T
SluijsensandClaude Sonnet 5.5 1b542dee98 Hero: grote foto's in de achtergrond robuust en sneller, voortgang en opnieuw proberen; admin zonder inline script
- Een decode voor de hele set, per breedte eenmaal geschaald voor WebP en AVIF (6000x4000: 21,1 s -> 6,4 s per set)
- Eigen limiet per set (Media:RenderSetTimeoutSeconds 600), harde limiet rond een foto, de renderer stopt nooit door een uitzondering, een mislukte foto wacht tot de volgende ronde en houdt de rij niet op
- Logging per foto (start, per variant, einde, fout); voortgang per variant in de admin; nieuwe uitsnede na focuswijziging zichtbaar (oude afbeelding blijft, shimmer); knop Opnieuw proberen
- Thema-script als /theme-init.js (CSP script-src 'self'), test en smoke-controle op inline scripts

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 22:23:15 +01:00

267 lines
10 KiB
C#

using System.ComponentModel.DataAnnotations;
using System.Text;
using System.Text.Json.Serialization;
using SlpModularCms.Core.Media;
using SlpModularCms.Modules.Hero.Data.Entities;
namespace SlpModularCms.Modules.Hero.Models;
public record FocusDto(double X, double Y, double Zoom)
{
public FocusSetting ToSetting() => new(X, Y, Zoom);
public static FocusDto From(FocusSetting focus) => new(focus.X, focus.Y, focus.Zoom);
}
public record HeroVariantDto(string Ratio, int Width, int Height, string Type, string Url);
public record HeroImageDto(
string Id,
int Width,
int Height,
FocusDto Focus,
FocusDto? WideFocus,
FocusDto? TallFocus,
string Src,
IReadOnlyList<HeroVariantDto> Variants,
bool Processing = false,
bool Failed = false,
int? RenderDone = null,
int? RenderTotal = null);
public record HeroButtonDto(string Label, string Target);
public record HeroSlideAdminDto(string Id, string ImageId, string Alt, bool Decorative, bool IsActive, int SortOrder, HeroImageDto Image);
/// <summary>What the admin edits. When no hero exists yet <see cref="Id"/> is null and the fields hold the defaults.</summary>
public record HeroAdminDto(
string? Id,
string Title,
string? Tagline,
string? Lead,
string Display,
IReadOnlyList<HeroButtonDto> Buttons,
bool IsActive,
DateTimeOffset? StartsAt,
DateTimeOffset? EndsAt,
IReadOnlyList<HeroSlideAdminDto> Slides,
bool IsLive,
DateTimeOffset? UpdatedAt,
int MaxPublishedSlides);
/// <summary>The image of a published slide. <see cref="Src"/> is the largest WebP of the wide ratio.</summary>
public record PublicImageDto(
int Width,
int Height,
FocusDto Focus,
string Src,
IReadOnlyList<HeroVariantDto> Variants,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] IReadOnlyDictionary<string, FocusDto>? FocusByRatio = null);
public record PublicSlideDto(string Id, string Alt, bool Decorative, PublicImageDto Image);
/// <summary>What visitors and websites get: only content, never the schedule or on/off switches. The same shape is written into <c>#cms-data</c>.</summary>
public record PublicHeroDto(
string Display,
string Title,
string? Tagline,
string? Lead,
IReadOnlyList<HeroButtonDto> Buttons,
IReadOnlyList<PublicSlideDto> Slides);
// ----- requests ----------------------------------------------------------------------------------------------------
public record HeroButtonRequest(string? Label, string? Target);
public record HeroSlideRequest(Guid? Id, Guid ImageId, string? Alt, bool Decorative = false, bool IsActive = true);
/// <summary>A changed focus of one image; it takes effect when the hero is saved (the admin keeps it locally until then).</summary>
public record HeroImageFocusRequest(Guid ImageId, FocusDto Focus, FocusDto? Wide = null, FocusDto? Tall = null);
public record HeroFocusRequest(FocusDto Focus, FocusDto? Wide = null, FocusDto? Tall = null) : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var texts = HeroTexts.From(validationContext);
foreach (var (name, value) in new[] { (nameof(Focus), Focus), (nameof(Wide), Wide), (nameof(Tall), Tall) })
{
if (value is not null && !value.ToSetting().IsValid)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.FocusInvalid, args: ("maxZoom", FocusSetting.MaxZoom)), [name]);
}
}
if (Focus is null)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.FocusInvalid, args: ("maxZoom", FocusSetting.MaxZoom)), [nameof(Focus)]);
}
}
}
/// <summary>The whole hero in one go (full replace). Nothing here is trusted: <see cref="Validate"/> is the one place that checks it.</summary>
public record HeroSaveRequest(
string? Title,
string? Tagline,
string? Lead,
string? Display,
IReadOnlyList<HeroButtonRequest>? Buttons,
bool IsActive,
DateTimeOffset? StartsAt,
DateTimeOffset? EndsAt,
IReadOnlyList<HeroSlideRequest>? Slides,
IReadOnlyList<HeroImageFocusRequest>? ImageFocus = null) : IValidatableObject
{
public const int TitleMax = 200;
public const int TitleMaxLines = 5;
public const int TaglineMax = 120;
public const int LeadMax = 600;
public const int ButtonLabelMax = 50;
public const int ButtonTargetMax = 500;
public const int ButtonsMax = 2;
public const int AltMax = 300;
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var texts = HeroTexts.From(validationContext);
var title = HeroText.Clean(Title, keepLineBreaks: true);
if (title.Length == 0)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Title.Required), [nameof(Title)]);
}
else
{
if (title.Length > TitleMax)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Title.TooLong, args: ("max", TitleMax)), [nameof(Title)]);
}
if (title.Count(c => c == '\n') + 1 > TitleMaxLines)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Title.TooManyLines, args: ("max", TitleMaxLines)), [nameof(Title)]);
}
}
if (HeroText.Clean(Tagline, keepLineBreaks: false).Length > TaglineMax)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.TaglineTooLong, args: ("max", TaglineMax)), [nameof(Tagline)]);
}
if (HeroText.Clean(Lead, keepLineBreaks: true).Length > LeadMax)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.LeadTooLong, args: ("max", LeadMax)), [nameof(Lead)]);
}
if (!HeroDisplays.IsValid(Display ?? HeroDisplays.Single))
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.DisplayInvalid), [nameof(Display)]);
}
var buttons = Buttons ?? [];
if (buttons.Count > ButtonsMax)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.TooMany, args: ("max", ButtonsMax)), [nameof(Buttons)]);
}
for (var i = 0; i < buttons.Count; i++)
{
var label = HeroText.Clean(buttons[i].Label, keepLineBreaks: false);
var target = (buttons[i].Target ?? string.Empty).Trim();
if (label.Length == 0 && target.Length == 0)
{
continue;
}
if (label.Length == 0 || target.Length == 0)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.Incomplete), [$"{nameof(Buttons)}[{i}]"]);
continue;
}
if (label.Length > ButtonLabelMax)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.LabelTooLong, args: ("max", ButtonLabelMax)), [$"{nameof(Buttons)}[{i}].Label"]);
}
if (target.Length > ButtonTargetMax)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.TargetTooLong, args: ("max", ButtonTargetMax)), [$"{nameof(Buttons)}[{i}].Target"]);
}
else if (ButtonTargetValidator.Validate(target) == ButtonTargetKind.Invalid)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Button.TargetInvalid), [$"{nameof(Buttons)}[{i}].Target"]);
}
}
if (StartsAt is not null && EndsAt is not null && EndsAt <= StartsAt)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.EndAfterStart), [nameof(EndsAt)]);
}
var focusEdits = ImageFocus ?? [];
for (var i = 0; i < focusEdits.Count; i++)
{
var edit = focusEdits[i];
var valid = edit.ImageId != Guid.Empty
&& edit.Focus is not null && edit.Focus.ToSetting().IsValid
&& (edit.Wide is null || edit.Wide.ToSetting().IsValid)
&& (edit.Tall is null || edit.Tall.ToSetting().IsValid);
if (!valid)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.FocusInvalid, args: ("maxZoom", FocusSetting.MaxZoom)), [$"{nameof(ImageFocus)}[{i}]"]);
}
}
var slides = Slides ?? [];
for (var i = 0; i < slides.Count; i++)
{
var slide = slides[i];
if (slide.ImageId == Guid.Empty)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Slide.ImageRequired), [$"{nameof(Slides)}[{i}].ImageId"]);
}
var alt = HeroText.Clean(slide.Alt, keepLineBreaks: false);
if (!slide.Decorative && alt.Length == 0)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Slide.AltRequired), [$"{nameof(Slides)}[{i}].Alt"]);
}
else if (alt.Length > AltMax)
{
yield return new ValidationResult(texts.Get(HeroTexts.Validation.Slide.AltTooLong, args: ("max", AltMax)), [$"{nameof(Slides)}[{i}].Alt"]);
}
}
}
}
/// <summary>Plain text handling: stored as typed, minus control characters; encoding happens where the text is written.</summary>
public static class HeroText
{
public static string Clean(string? value, bool keepLineBreaks)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
var text = value.Replace("\r\n", "\n").Replace('\r', '\n');
var builder = new StringBuilder(text.Length);
foreach (var c in text)
{
if (c == '\n')
{
builder.Append(keepLineBreaks ? '\n' : ' ');
}
else if (!char.IsControl(c) && c != '\u2028' && c != '\u2029')
{
builder.Append(c);
}
}
return builder.ToString().Trim();
}
}
/// <summary>What an upload is allowed to be on this host, for the admin to show: derived from the same sources as the validation.</summary>
public record HeroUploadLimitsDto(IReadOnlyList<string> Formats, long MaxUploadBytes, int MaxMegapixels);