Hero: planning en hero-brede aan/uit verwijderd (hero altijd aan, live zodra er een titel is); migratie, API, admin, tests en docs bijgewerkt

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 08:21:32 +01:00
co-authored by Claude Sonnet 5.5
parent ef62a3714f
commit b78e890f65
29 changed files with 341 additions and 285 deletions
+1 -7
View File
@@ -27,9 +27,6 @@ export const emptyHero = (): HeroAdminDto => ({
lead: null,
display: 'single',
buttons: [],
isActive: true,
startsAt: null,
endsAt: null,
slides: [],
isLive: false,
updatedAt: null,
@@ -106,10 +103,7 @@ export const heroHandlers = [
lead: body.lead,
display: body.display,
buttons: body.buttons,
isActive: body.isActive,
startsAt: body.startsAt,
endsAt: body.endsAt,
isLive: body.isActive && body.title.trim() !== '',
isLive: body.title.trim() !== '',
updatedAt: '2026-11-16T12:00:00Z',
slides: body.slides.map((s, i) => ({
id: s.id ?? `20000000-0000-0000-0000-00000000000${i}`,
@@ -103,7 +103,7 @@ describe('Hero page', () => {
expect(await screen.findByTestId('hero-form', {}, T)).toBeInTheDocument();
});
it('saves the texts, the buttons and the schedule, and shows the hero as live', async () => {
it('saves the texts and the buttons, and shows the hero as live', async () => {
await openPage();
await userEvent.type(screen.getByTestId('hero-title-input'), 'Websites,{enter}apps{enter}& meer.');
@@ -125,9 +125,6 @@ describe('Hero page', () => {
{ label: 'Bekijk pakketten', target: '#pakketten' },
{ label: 'Plan een gesprek', target: '#contact' },
],
isActive: true,
startsAt: null,
endsAt: null,
slides: [],
});
});
@@ -168,15 +165,12 @@ describe('Hero page', () => {
expect(await screen.findByTestId('hero-button-1-target-error')).toHaveTextContent(/Vul zowel de tekst als het doel|Fill in both the text and the target/);
});
it('wants the end after the start', async () => {
it('has no switch and no schedule: the hero is always on', async () => {
await openPage();
await userEvent.type(screen.getByTestId('hero-title-input'), 'Titel');
fireEvent.change(screen.getByTestId('hero-starts'), { target: { value: '2026-12-10T10:00' } });
fireEvent.change(screen.getByTestId('hero-ends'), { target: { value: '2026-12-01T10:00' } });
await userEvent.click(screen.getByTestId('hero-save'));
expect(await screen.findByTestId('hero-ends-error')).toHaveTextContent(/Het einde moet na het begin liggen\.|The end must be after the start\./);
expect(screen.queryByTestId('hero-active')).not.toBeInTheDocument();
expect(screen.queryByTestId('hero-starts')).not.toBeInTheDocument();
expect(screen.queryByTestId('hero-ends')).not.toBeInTheDocument();
});
});
@@ -650,7 +644,7 @@ describe('Order by dragging, wording and calm waiting', () => {
const help = screen.getByTestId('hero-help');
expect(help).toHaveTextContent(/#contact/);
expect(help).toHaveTextContent(/\/privacy/);
expect(help).toHaveTextContent(/Planning|Schedule/);
expect(help).not.toHaveTextContent(/Planning|Schedule/);
});
it('numbers the slides by their current order, also after the order changed', async () => {
+2 -28
View File
@@ -22,7 +22,7 @@ import { SortableSlide } from '../components/SortableSlide';
import { UnsavedChangesGuard } from '../components/UnsavedChangesGuard';
import { UploadProgress, type UploadItem } from '../components/UploadProgress';
import { mediaUrl } from '../lib/media';
import { fromLocalInput, heroFormSchema, toLocalInput, type HeroFormData } from '../schemas/hero';
import { heroFormSchema, type HeroFormData } from '../schemas/hero';
import { heroImageQuery, useHero, useHeroUploadLimits, useSaveHero, useUploadHeroImage } from '../services/hooks';
import type { HeroAdminDto, HeroFocusRequest, HeroImageDto, HeroSaveRequest } from '../services/types';
@@ -37,9 +37,6 @@ function toForm(hero: HeroAdminDto): HeroFormData {
lead: hero.lead ?? '',
display: hero.display,
buttons,
isActive: hero.isActive,
startsAt: toLocalInput(hero.startsAt),
endsAt: toLocalInput(hero.endsAt),
slides: hero.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.alt, decorative: s.decorative, isActive: s.isActive })),
};
}
@@ -51,9 +48,6 @@ function toRequest(values: HeroFormData, focusEdits: Record<string, HeroFocusReq
lead: values.lead || null,
display: values.display,
buttons: values.buttons.filter((b) => b.label !== '' && b.target !== ''),
isActive: values.isActive,
startsAt: fromLocalInput(values.startsAt),
endsAt: fromLocalInput(values.endsAt),
slides: values.slides.map((s) => ({ id: s.id, imageId: s.imageId, alt: s.decorative ? null : s.alt, decorative: s.decorative, isActive: s.isActive })),
imageFocus: Object.entries(focusEdits).map(([imageId, edit]) => ({ imageId, ...edit })),
};
@@ -117,7 +111,7 @@ export function HeroPage() {
<details className="max-w-3xl rounded-md border p-3 text-sm" data-testid="hero-help">
<summary className="cursor-pointer font-medium">{t('hero.help.heading')}</summary>
<dl className="mt-3 space-y-2">
{(['title', 'tagline', 'lead', 'buttons', 'display', 'slides', 'focus', 'schedule'] as const).map((key) => (
{(['title', 'tagline', 'lead', 'buttons', 'display', 'slides', 'focus'] as const).map((key) => (
<div key={key}>
<dt className="font-medium">{t(`hero.help.${key}.name`)}</dt>
<dd className="text-muted-foreground">{t(`hero.help.${key}.text`)}</dd>
@@ -387,26 +381,6 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
))}
</section>
<section className="space-y-3">
<h2 className="text-lg font-medium">{t('hero.schedule.title')}</h2>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" className="size-4 rounded border-input" data-testid="hero-active" {...register('isActive')} />
{t('hero.schedule.active')}
</label>
<div className="grid gap-3 sm:grid-cols-2">
<div className="space-y-1">
<Label htmlFor="hero-starts">{t('hero.schedule.starts')}</Label>
<Input id="hero-starts" type="datetime-local" data-testid="hero-starts" {...register('startsAt')} />
</div>
<div className="space-y-1">
<Label htmlFor="hero-ends">{t('hero.schedule.ends')}</Label>
<Input id="hero-ends" type="datetime-local" data-testid="hero-ends" {...register('endsAt')} />
<FieldError message={err(heroErrors.endsAt?.message)} testId="hero-ends-error" />
</div>
</div>
<p className="text-xs text-muted-foreground">{t('hero.schedule.hint')}</p>
</section>
<section
className={`space-y-3 rounded-md ${draggingFiles ? 'ring-2 ring-primary ring-offset-4' : ''}`}
onDragOver={(event) => {
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
import { fromLocalInput, heroFormSchema, isAllowedButtonTarget, toLocalInput } from './hero';
import { heroFormSchema, isAllowedButtonTarget } from './hero';
// The same cases as ButtonTargetValidatorTests in src/SlpModularCms.Modules.Hero.Tests/HeroRulesTests.cs.
describe('isAllowedButtonTarget', () => {
@@ -21,9 +21,6 @@ const base = {
lead: '',
display: 'single' as const,
buttons: [{ label: '', target: '' }, { label: '', target: '' }],
isActive: true,
startsAt: '',
endsAt: '',
slides: [],
};
@@ -49,12 +46,3 @@ describe('heroFormSchema', () => {
expect(heroFormSchema.safeParse({ ...base, slides }).success).toBe(true);
});
});
describe('local date inputs', () => {
it('round-trips an instant', () => {
const iso = '2026-12-01T09:30:00.000Z';
expect(fromLocalInput(toLocalInput(iso))).toBe(iso);
expect(toLocalInput(null)).toBe('');
expect(fromLocalInput('')).toBeNull();
});
});
@@ -62,35 +62,12 @@ export const heroFormSchema = z
lead: z.string().trim().max(LEAD_MAX, 'hero.errors.leadTooLong'),
display: z.enum(['single', 'slideshow']),
buttons: z.array(buttonSchema).length(2),
isActive: z.boolean(),
/** datetime-local value ("YYYY-MM-DDTHH:mm") in the browser's time zone, or ''. */
startsAt: z.string(),
endsAt: z.string(),
slides: z.array(slideSchema),
})
.superRefine((v, ctx) => {
if (v.title.replace(/\r\n/g, '\n').split('\n').length > TITLE_MAX_LINES) {
ctx.addIssue({ code: 'custom', path: ['title'], message: 'hero.errors.titleTooManyLines' });
}
if (v.startsAt !== '' && v.endsAt !== '' && fromLocalInput(v.endsAt)! <= fromLocalInput(v.startsAt)!) {
ctx.addIssue({ code: 'custom', path: ['endsAt'], message: 'hero.errors.endAfterStart' });
}
});
export type HeroFormData = z.infer<typeof heroFormSchema>;
/** ISO instant to the value of a datetime-local input (browser time zone). */
export function toLocalInput(iso: string | null): string {
if (!iso) return '';
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return '';
const pad = (n: number) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
/** Value of a datetime-local input to an ISO instant, or null when empty. */
export function fromLocalInput(value: string): string | null {
if (!value) return null;
const d = new Date(value);
return Number.isNaN(d.getTime()) ? null : d.toISOString();
}
@@ -58,9 +58,6 @@ export interface HeroAdminDto {
lead: string | null;
display: HeroDisplay;
buttons: HeroButtonDto[];
isActive: boolean;
startsAt: string | null;
endsAt: string | null;
slides: HeroSlideAdminDto[];
isLive: boolean;
updatedAt: string | null;
@@ -81,9 +78,6 @@ export interface HeroSaveRequest {
lead: string | null;
display: HeroDisplay;
buttons: HeroButtonDto[];
isActive: boolean;
startsAt: string | null;
endsAt: string | null;
slides: HeroSlideRequest[];
/** Changed focus points of images; they take effect with this save. */
imageFocus: HeroImageFocusRequest[];
+1 -13
View File
@@ -634,13 +634,6 @@
"label": "Button {{n}}: text",
"target": "Button {{n}}: target"
},
"schedule": {
"title": "Schedule",
"active": "Hero is switched on",
"starts": "Visible from",
"ends": "Visible until",
"hint": "Outside this period, or when the hero is switched off, the website keeps its standard hero."
},
"slides": {
"title": "Images",
"add": "Add image",
@@ -717,8 +710,7 @@
"buttonIncomplete": "Fill in both the text and the target of the button, or leave both empty.",
"buttonTargetInvalid": "Choose a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…).",
"altTooLong": "The description can have at most 300 characters.",
"altRequired": "Give a description or choose ‘Decoration only’.",
"endAfterStart": "The end must be after the start."
"altRequired": "Give a description or choose ‘Decoration only’."
},
"upload": {
"tooLarge": "The image is too large (at most {{max}} MB).",
@@ -762,10 +754,6 @@
"focus": {
"name": "Focus",
"text": "Show where the subject is in the photo, so a crop never cuts it off. For portrait screens, such as a phone, you can choose a separate point."
},
"schedule": {
"name": "Schedule",
"text": "The hero is only visible in the period from–until. Outside that period the website keeps its standard hero."
}
},
"unsaved": {
+1 -13
View File
@@ -634,13 +634,6 @@
"label": "Knop {{n}}: tekst",
"target": "Knop {{n}}: doel"
},
"schedule": {
"title": "Planning",
"active": "Hero is aangezet",
"starts": "Zichtbaar vanaf",
"ends": "Zichtbaar tot",
"hint": "Buiten deze periode, of als de hero is uitgezet, blijft de standaard hero van de website staan."
},
"slides": {
"title": "Afbeeldingen",
"add": "Afbeelding toevoegen",
@@ -717,8 +710,7 @@
"buttonIncomplete": "Vul zowel de tekst als het doel van de knop in, of laat beide leeg.",
"buttonTargetInvalid": "Kies een onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…).",
"altTooLong": "De beschrijving mag maximaal 300 tekens bevatten.",
"altRequired": "Geef een beschrijving of kies ‘Alleen versiering’.",
"endAfterStart": "Het einde moet na het begin liggen."
"altRequired": "Geef een beschrijving of kies ‘Alleen versiering’."
},
"upload": {
"tooLarge": "De afbeelding is te groot (maximaal {{max}} MB).",
@@ -762,10 +754,6 @@
"focus": {
"name": "Focus",
"text": "Geef aan waar het onderwerp op de foto staat, zodat een uitsnede er niets van afhakt. Voor staande schermen, zoals een telefoon, kun je een apart punt kiezen."
},
"schedule": {
"name": "Planning",
"text": "De hero is alleen zichtbaar in de periode van–tot. Buiten die periode blijft de standaard hero van de website staan."
}
},
"unsaved": {
-40
View File
@@ -562,22 +562,12 @@
"display": {
"type": "string"
},
"endsAt": {
"format": "date-time",
"type": [
"null",
"string"
]
},
"id": {
"type": [
"null",
"string"
]
},
"isActive": {
"type": "boolean"
},
"isLive": {
"type": "boolean"
},
@@ -601,13 +591,6 @@
},
"type": "array"
},
"startsAt": {
"format": "date-time",
"type": [
"null",
"string"
]
},
"tagline": {
"type": [
"null",
@@ -632,9 +615,6 @@
"lead",
"display",
"buttons",
"isActive",
"startsAt",
"endsAt",
"slides",
"isLive",
"updatedAt",
@@ -833,13 +813,6 @@
"string"
]
},
"endsAt": {
"format": "date-time",
"type": [
"null",
"string"
]
},
"imageFocus": {
"items": {
"$ref": "#/components/schemas/HeroImageFocusRequest"
@@ -849,9 +822,6 @@
"array"
]
},
"isActive": {
"type": "boolean"
},
"lead": {
"type": [
"null",
@@ -867,13 +837,6 @@
"array"
]
},
"startsAt": {
"format": "date-time",
"type": [
"null",
"string"
]
},
"tagline": {
"type": [
"null",
@@ -893,9 +856,6 @@
"lead",
"display",
"buttons",
"isActive",
"startsAt",
"endsAt",
"slides"
],
"type": "object"
-3
View File
@@ -146,9 +146,6 @@ $payload = [ordered]@{
lead = $(if ($seed.lead) { $seed.lead } else { $null })
display = $(if ($seed.display) { $seed.display } else { 'single' })
buttons = @($seed.buttons | Where-Object { $_ } | ForEach-Object { [ordered]@{ label = $_.label; target = $_.target } })
isActive = $true
startsAt = $null
endsAt = $null
slides = $requestSlides
imageFocus = $imageFocus
} | ConvertTo-Json -Depth 6
@@ -110,7 +110,7 @@ public class HeroAsfSiteE2ETests : IClassFixture<AsfSiteFactory>
await InScope(sp => sp.GetRequiredService<IHeroService>().SaveAsync(
new HeroSaveRequest(seed.GetProperty("title").GetString(), seed.GetProperty("tagline").GetString(), null, seed.GetProperty("display").GetString(),
seed.GetProperty("buttons").EnumerateArray().Select(b => new HeroButtonRequest(b.GetProperty("label").GetString(), b.GetProperty("target").GetString())).ToList(),
true, null, null, slides, focusEdits), caller, default));
slides, focusEdits), caller, default));
await InScope(async sp =>
{
@@ -131,7 +131,7 @@ public class HeroInjectionPipelineTests : IClassFixture<HeroInjectionFactory>
// 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 HeroSaveRequest("Andrea Slop", "Lifestyle fotograaf · Huizen", null, "slideshow", [new HeroButtonRequest("Lees meer", "/over-mij")],
[new HeroSlideRequest(null, Guid.Parse(image.Id), "Zwangerschapsfoto in de duinen")]), caller, default));
await InScope(async sp =>
{
@@ -189,28 +189,7 @@ public class HeroInjectionPipelineTests : IClassFixture<HeroInjectionFactory>
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");
// A media directory that lost its files leaves the baked hero too (no broken first image).
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");
@@ -9,7 +9,7 @@ namespace SlpModularCms.Modules.Hero.Tests;
public class HeroFocusSaveTests
{
private static HeroSaveRequest Save(Guid imageId, IReadOnlyList<HeroImageFocusRequest>? focus)
=> new("Andrea Slop", null, null, "single", [], true, null, null, [new HeroSlideRequest(null, imageId, "foto")], focus);
=> new("Andrea Slop", null, null, "single", [], [new HeroSlideRequest(null, imageId, "foto")], focus);
[Fact]
public async Task TheLiveHero_KeepsItsOldSet_UntilTheNewSetIsCut_AndThenSwitchesToIt()
@@ -112,7 +112,7 @@ public class HeroFocusSaveTests
var live = rig.Db.HeroImages.Single().SetHash;
// The save stops after the new files were written (here: the hero refers to a slide of another hero).
var failing = new HeroSaveRequest("Andrea Slop", null, null, "single", [], true, null, null, [new HeroSlideRequest(Guid.NewGuid(), id, "foto")],
var failing = new HeroSaveRequest("Andrea Slop", null, null, "single", [], [new HeroSlideRequest(Guid.NewGuid(), id, "foto")],
[new HeroImageFocusRequest(id, new FocusDto(0.9, 0.9, 2))]);
var act = async () => await rig.Service.SaveAsync(failing, HeroTestRig.Admin, default);
await act.Should().ThrowAsync<HeroSaveRejectedException>();
@@ -273,7 +273,7 @@ public class HeroFocusSaveTests
var ready = await rig.Upload(HeroTestRig.Photo(seed: 3));
var first = await rig.UploadWithoutRendering(HeroTestRig.Photo(seed: 1));
var second = await rig.UploadWithoutRendering(HeroTestRig.Photo(seed: 2));
var request = new HeroSaveRequest("Titel", null, null, "slideshow", [], true, null, null,
var request = new HeroSaveRequest("Titel", null, null, "slideshow", [],
[new HeroSlideRequest(null, Guid.Parse(first.Id), "een"), new HeroSlideRequest(null, Guid.Parse(second.Id), "twee"), new HeroSlideRequest(null, Guid.Parse(ready.Id), "drie")]);
var saved = await rig.Service.SaveAsync(request, HeroTestRig.Admin, default);
@@ -82,7 +82,7 @@ public class HeroSaveRequestValidationTests
private static HeroSaveRequest Valid() => new(
"Websites,\napps\n& meer.", null, "Een lead.", "single",
[new HeroButtonRequest("Bekijk pakketten", "#pakketten"), new HeroButtonRequest("Plan een gesprek", "#contact")],
true, null, null, []);
[]);
private static List<ValidationResult> Run(HeroSaveRequest request)
{
@@ -133,16 +133,6 @@ public class HeroSaveRequestValidationTests
Run(Valid() with { Buttons = [new HeroButtonRequest("", ""), new HeroButtonRequest(null, null)] }).Should().BeEmpty("empty buttons are ignored");
}
[Fact]
public void TheSchedule_MustRunForward()
{
var t = new DateTimeOffset(2026, 12, 1, 0, 0, 0, TimeSpan.Zero);
Members(Run(Valid() with { StartsAt = t, EndsAt = t })).Should().Contain("EndsAt");
Members(Run(Valid() with { StartsAt = t, EndsAt = t.AddDays(-1) })).Should().Contain("EndsAt");
Run(Valid() with { StartsAt = t, EndsAt = t.AddDays(1) }).Should().BeEmpty();
Run(Valid() with { StartsAt = null, EndsAt = t }).Should().BeEmpty();
}
[Fact]
public void ASlide_NeedsAnImage_AndAnAltTextOrTheDecorativeFlag()
{
@@ -310,23 +300,13 @@ public class HeroMappingTests
hero.Slides.Should().HaveCount(80);
}
[Theory]
[InlineData(true, null, null, true)]
[InlineData(false, null, null, false)]
[InlineData(true, "2026-11-17", null, false)]
[InlineData(true, "2026-11-16T12:00:00Z", null, true)]
[InlineData(true, null, "2026-11-16T12:00:00Z", false)]
[InlineData(true, null, "2026-11-16T12:00:01Z", true)]
[InlineData(true, "2026-11-01", "2026-12-01", true)]
public void TheScheduleAndTheSwitch_DecideWhetherItIsLive(bool active, string? start, string? end, bool live)
[Fact]
public void TheHeroIsAlwaysOn_ItIsLiveAsSoonAsItHasATitle()
{
var hero = Hero(Slide(0));
hero.IsActive = active;
hero.StartsAt = start is null ? null : DateTimeOffset.Parse(start, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal);
hero.EndsAt = end is null ? null : DateTimeOffset.Parse(end, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AssumeUniversal);
(HeroMapping.ToPublic(hero, Now, 50) is not null).Should().Be(live);
HeroMapping.ToAdmin(hero, Now, 50).IsLive.Should().Be(live);
(HeroMapping.ToPublic(hero, Now, 50) is not null).Should().BeTrue();
HeroMapping.ToAdmin(hero, Now, 50).IsLive.Should().BeTrue();
}
[Fact]
@@ -34,7 +34,7 @@ public class HeroSaveTimingTests(ITestOutputHelper output)
var slides = ids.Select(id => new HeroSlideRequest(null, id, "foto")).ToList();
var focus = ids.Select(id => new HeroImageFocusRequest(id, new FocusDto(0.3, 0.4, 1), null, null)).ToList();
watch.Restart();
await rig.Service.SaveAsync(new HeroSaveRequest("Andrea Slop", null, null, "slideshow", [], true, null, null, slides, focus), HeroTestRig.Admin, default);
await rig.Service.SaveAsync(new HeroSaveRequest("Andrea Slop", null, null, "slideshow", [], slides, focus), HeroTestRig.Admin, default);
output.WriteLine($"save request with 8 slides and 8 changed focus points: {watch.ElapsedMilliseconds} ms");
watch.Restart();
@@ -43,12 +43,12 @@ public class HeroSaveTimingTests(ITestOutputHelper output)
watch.Restart();
var again = focus.Select(f => f with { Focus = new FocusDto(0.6, 0.4, 1) }).ToList();
await rig.Service.SaveAsync(new HeroSaveRequest("Andrea Slop", null, null, "slideshow", [], true, null, null, slides, again), HeroTestRig.Admin, default);
await rig.Service.SaveAsync(new HeroSaveRequest("Andrea Slop", null, null, "slideshow", [], slides, again), HeroTestRig.Admin, default);
output.WriteLine($"save request with 8 changed focus points again: {watch.ElapsedMilliseconds} ms");
await rig.RenderPending();
watch.Restart();
await rig.Service.SaveAsync(new HeroSaveRequest("Andrea Slop", null, null, "slideshow", [], true, null, null, slides, null), HeroTestRig.Admin, default);
await rig.Service.SaveAsync(new HeroSaveRequest("Andrea Slop", null, null, "slideshow", [], slides, null), HeroTestRig.Admin, default);
output.WriteLine($"save without focus changes: {watch.ElapsedMilliseconds} ms");
}
}
@@ -147,12 +147,12 @@ public class HeroImageServiceTests
{
using var rig = new HeroTestRig();
var image = await rig.Upload(HeroTestRig.Photo());
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], true, null, null, [new HeroSlideRequest(null, Guid.Parse(image.Id), "foto")]), HeroTestRig.Admin, CancellationToken.None);
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], [new HeroSlideRequest(null, Guid.Parse(image.Id), "foto")]), HeroTestRig.Admin, CancellationToken.None);
var inUse = async () => await rig.Images.DeleteAsync(Guid.Parse(image.Id), HeroTestRig.Admin, CancellationToken.None);
await inUse.Should().ThrowAsync<HeroImageInUseException>();
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], true, null, null, []), HeroTestRig.Admin, CancellationToken.None);
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], []), HeroTestRig.Admin, CancellationToken.None);
await rig.Images.DeleteAsync(Guid.Parse(image.Id), HeroTestRig.Admin, CancellationToken.None);
rig.Db.HeroImages.Should().BeEmpty();
@@ -227,7 +227,7 @@ public class HeroImageServiceTests
public class HeroServiceTests
{
private static HeroSaveRequest Request(IReadOnlyList<HeroSlideRequest>? slides = null, string title = "Andrea Slop") => new(
title, "Lifestyle fotograaf", null, "slideshow", [new HeroButtonRequest("Lees meer", "/over-mij")], true, null, null, slides ?? []);
title, "Lifestyle fotograaf", null, "slideshow", [new HeroButtonRequest("Lees meer", "/over-mij")], slides ?? []);
[Fact]
public async Task TheFirstSave_CreatesTheHero_WithItsSlidesInOrder()
@@ -312,7 +312,7 @@ public class HeroServiceTests
using var rig = new HeroTestRig();
var saved = await rig.Service.SaveAsync(
new HeroSaveRequest("Websites,\r\napps\u0007\n& meer.", " <b>tag</b> ", "lead\nregel twee", "single", [new HeroButtonRequest(" Knop ", " #contact ")], true, null, null, []),
new HeroSaveRequest("Websites,\r\napps\u0007\n& meer.", " <b>tag</b> ", "lead\nregel twee", "single", [new HeroButtonRequest(" Knop ", " #contact ")], []),
HeroTestRig.Admin, CancellationToken.None);
saved.Title.Should().Be("Websites,\napps\n& meer.");
@@ -327,7 +327,7 @@ public class HeroServiceTests
using var rig = new HeroTestRig();
await rig.Service.SaveAsync(new HeroSaveRequest("Websites,\napps\n& meer.", null, "Lead.", "single",
[new HeroButtonRequest("Bekijk pakketten", "#pakketten"), new HeroButtonRequest("Plan een gesprek", "#contact")], true, null, null, null), HeroTestRig.Admin, CancellationToken.None);
[new HeroButtonRequest("Bekijk pakketten", "#pakketten"), new HeroButtonRequest("Plan een gesprek", "#contact")], null), HeroTestRig.Admin, CancellationToken.None);
var pub = (await rig.Public.GetActiveAsync(CancellationToken.None))!;
pub.Title.Should().Be("Websites,\napps\n& meer.");
@@ -336,20 +336,6 @@ public class HeroServiceTests
pub.Slides.Should().BeEmpty();
}
[Fact]
public async Task ThePublicHero_FollowsTheScheduleOfTheClock()
{
using var rig = new HeroTestRig();
var start = rig.Time.Now.AddDays(1);
await rig.Service.SaveAsync(Request() with { StartsAt = start, EndsAt = start.AddDays(7) }, HeroTestRig.Admin, CancellationToken.None);
(await rig.Public.GetActiveAsync(CancellationToken.None)).Should().BeNull();
rig.Time.Now = start.AddHours(1);
(await rig.Public.GetActiveAsync(CancellationToken.None)).Should().NotBeNull();
rig.Time.Now = start.AddDays(7);
(await rig.Public.GetActiveAsync(CancellationToken.None)).Should().BeNull();
}
[Fact]
public async Task WithoutAHero_TheAdminGetsEmptyDefaults_AndThePublicGetsNothing()
{
@@ -417,7 +403,7 @@ public class HeroMediaCleanupTests
// The same photo with the same focus comes back: the same set again, referenced by a new row.
var again = await rig.Upload(photo);
rig.Db.HeroImages.Single().SetHash.Should().Be(set);
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], true, null, null, [new HeroSlideRequest(null, Guid.Parse(again.Id), "foto")]), HeroTestRig.Admin, CancellationToken.None);
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], [new HeroSlideRequest(null, Guid.Parse(again.Id), "foto")]), HeroTestRig.Admin, CancellationToken.None);
rig.Time.Now = rig.Time.Now.AddDays(8);
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
@@ -447,7 +433,7 @@ public class HeroMediaCleanupTests
{
using var rig = new HeroTestRig();
var image = await rig.Upload(HeroTestRig.Photo());
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], true, null, null, [new HeroSlideRequest(null, Guid.Parse(image.Id), "foto")]), HeroTestRig.Admin, CancellationToken.None);
await rig.Service.SaveAsync(new HeroSaveRequest("Titel", null, null, "single", [], [new HeroSlideRequest(null, Guid.Parse(image.Id), "foto")]), HeroTestRig.Admin, CancellationToken.None);
rig.Time.Now = rig.Time.Now.AddDays(30);
await rig.Cleanup.RunOnceAsync(CancellationToken.None);
@@ -82,7 +82,7 @@ public sealed class HeroTestRig : IDisposable
public async Task<SlpModularCms.Modules.Hero.Models.HeroImageDto> SetFocus(Guid imageId, SlpModularCms.Modules.Hero.Models.HeroFocusRequest request)
{
await Service.SaveAsync(
new SlpModularCms.Modules.Hero.Models.HeroSaveRequest("Titel", null, null, "single", [], true, null, null, [],
new SlpModularCms.Modules.Hero.Models.HeroSaveRequest("Titel", null, null, "single", [], [],
[new SlpModularCms.Modules.Hero.Models.HeroImageFocusRequest(imageId, request.Focus, request.Wide, request.Tall)]),
Admin, CancellationToken.None);
await RenderPending();
@@ -2,7 +2,7 @@ using SlpModularCms.Core.Media;
namespace SlpModularCms.Modules.Hero.Data.Entities;
/// <summary>The hero of the site in one language: texts, up to two buttons, the display, the schedule and the slides.</summary>
/// <summary>The hero of the site in one language: texts, up to two buttons, the display and the slides.</summary>
public class HeroContent
{
public Guid Id { get; set; }
@@ -18,9 +18,6 @@ public class HeroContent
public string? Button1Target { get; set; }
public string? Button2Label { get; set; }
public string? Button2Target { get; set; }
public DateTimeOffset? StartsAt { get; set; }
public DateTimeOffset? EndsAt { get; set; }
public bool IsActive { get; set; } = true;
public DateTimeOffset UpdatedAt { get; set; }
public Guid LastModifiedByUserId { get; set; }
@@ -30,7 +30,6 @@ public class HeroDbContext(DbContextOptions<HeroDbContext> options) : DbContext(
entity.Property(e => e.Button1Target).HasMaxLength(500);
entity.Property(e => e.Button2Label).HasMaxLength(100);
entity.Property(e => e.Button2Target).HasMaxLength(500);
entity.Property(e => e.IsActive).IsRequired();
entity.Property(e => e.UpdatedAt).IsRequired();
entity.Property(e => e.LastModifiedByUserId).IsRequired();
entity.HasMany(e => e.Slides).WithOne().HasForeignKey(s => s.HeroId).OnDelete(DeleteBehavior.Cascade);
+1 -1
View File
@@ -16,7 +16,7 @@ using SlpModularCms.Modules.Hero.Services;
namespace SlpModularCms.Modules.Hero;
/// <summary>The manageable hero of a website: texts, buttons, slides with images, schedule; images are processed and served by the host.</summary>
/// <summary>The manageable hero of a website: texts, buttons, slides with images; images are processed and served by the host.</summary>
[ExcludeFromCodeCoverage]
public class HeroModule : IModule
{
@@ -29,7 +29,6 @@ public static class HeroTexts
public static readonly TextKey TooMany = new("hero.validation.button.tooMany", "max");
}
public static readonly TextKey EndAfterStart = new("hero.validation.schedule.endAfterStart");
public static class Slide
{
@@ -0,0 +1,247 @@
// <auto-generated />
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("20261117071410_RemoveHeroScheduleAndSwitch")]
partial class RemoveHeroScheduleAndSwitch
{
/// <inheritdoc />
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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Button1Label")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Button1Target")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<string>("Button2Label")
.HasMaxLength(100)
.HasColumnType("varchar(100)");
b.Property<string>("Button2Target")
.HasMaxLength(500)
.HasColumnType("varchar(500)");
b.Property<string>("Display")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<string>("Language")
.IsRequired()
.HasMaxLength(10)
.HasColumnType("varchar(10)");
b.Property<Guid>("LastModifiedByUserId")
.HasColumnType("char(36)");
b.Property<string>("Lead")
.HasMaxLength(1000)
.HasColumnType("varchar(1000)");
b.Property<string>("Tagline")
.HasMaxLength(200)
.HasColumnType("varchar(200)");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(1000)
.HasColumnType("varchar(1000)");
b.Property<DateTimeOffset>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<long>("Bytes")
.HasColumnType("bigint");
b.Property<DateTimeOffset>("CreatedAt")
.HasColumnType("datetime");
b.Property<Guid>("CreatedByUserId")
.HasColumnType("char(36)");
b.Property<double>("FocusX")
.HasColumnType("double");
b.Property<double>("FocusY")
.HasColumnType("double");
b.Property<int>("Height")
.HasColumnType("int");
b.Property<string>("OriginalKey")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("varchar(200)");
b.Property<string>("OriginalSha256")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("varchar(64)");
b.Property<string>("SetHash")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("varchar(16)");
b.Property<string>("SourceFormat")
.IsRequired()
.HasMaxLength(10)
.HasColumnType("varchar(10)");
b.Property<double?>("TallFocusX")
.HasColumnType("double");
b.Property<double?>("TallFocusY")
.HasColumnType("double");
b.Property<double?>("TallZoom")
.HasColumnType("double");
b.Property<string>("Variants")
.IsRequired()
.HasColumnType("longtext");
b.Property<double?>("WideFocusX")
.HasColumnType("double");
b.Property<double?>("WideFocusY")
.HasColumnType("double");
b.Property<double?>("WideZoom")
.HasColumnType("double");
b.Property<int>("Width")
.HasColumnType("int");
b.Property<double>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Key")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("varchar(200)");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(10)
.HasColumnType("varchar(10)");
b.Property<DateTimeOffset>("RetiredAt")
.HasColumnType("datetime");
b.HasKey("Id");
b.ToTable("HeroRetiredFiles", (string)null);
});
modelBuilder.Entity("SlpModularCms.Modules.Hero.Data.Entities.HeroSlide", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Alt")
.IsRequired()
.HasMaxLength(600)
.HasColumnType("varchar(600)");
b.Property<bool>("Decorative")
.HasColumnType("tinyint(1)");
b.Property<Guid>("HeroId")
.HasColumnType("char(36)");
b.Property<Guid>("ImageId")
.HasColumnType("char(36)");
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<int>("SortOrder")
.HasColumnType("int");
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
}
}
}
@@ -0,0 +1,50 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace SlpModularCms.Modules.Hero.Migrations
{
/// <inheritdoc />
public partial class RemoveHeroScheduleAndSwitch : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "EndsAt",
table: "Heroes");
migrationBuilder.DropColumn(
name: "IsActive",
table: "Heroes");
migrationBuilder.DropColumn(
name: "StartsAt",
table: "Heroes");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTimeOffset>(
name: "EndsAt",
table: "Heroes",
type: "datetime",
nullable: true);
migrationBuilder.AddColumn<bool>(
name: "IsActive",
table: "Heroes",
type: "tinyint(1)",
nullable: false,
defaultValue: false);
migrationBuilder.AddColumn<DateTimeOffset>(
name: "StartsAt",
table: "Heroes",
type: "datetime",
nullable: true);
}
}
}
@@ -46,12 +46,6 @@ namespace SlpModularCms.Modules.Hero.Migrations
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<DateTimeOffset?>("EndsAt")
.HasColumnType("datetime");
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<string>("Language")
.IsRequired()
.HasMaxLength(10)
@@ -64,9 +58,6 @@ namespace SlpModularCms.Modules.Hero.Migrations
.HasMaxLength(1000)
.HasColumnType("varchar(1000)");
b.Property<DateTimeOffset?>("StartsAt")
.HasColumnType("datetime");
b.Property<string>("Tagline")
.HasMaxLength(200)
.HasColumnType("varchar(200)");
@@ -43,9 +43,6 @@ public record HeroAdminDto(
string? Lead,
string Display,
IReadOnlyList<HeroButtonDto> Buttons,
bool IsActive,
DateTimeOffset? StartsAt,
DateTimeOffset? EndsAt,
IReadOnlyList<HeroSlideAdminDto> Slides,
bool IsLive,
DateTimeOffset? UpdatedAt,
@@ -62,7 +59,7 @@ public record PublicImageDto(
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>
/// <summary>What visitors and websites get: only content, never admin-only state. The same shape is written into <c>#cms-data</c>.</summary>
public record PublicHeroDto(
string Display,
string Title,
@@ -107,9 +104,6 @@ public record HeroSaveRequest(
string? Lead,
string? Display,
IReadOnlyList<HeroButtonRequest>? Buttons,
bool IsActive,
DateTimeOffset? StartsAt,
DateTimeOffset? EndsAt,
IReadOnlyList<HeroSlideRequest>? Slides,
IReadOnlyList<HeroImageFocusRequest>? ImageFocus = null) : IValidatableObject
{
@@ -195,11 +189,6 @@ public record HeroSaveRequest(
}
}
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++)
{
@@ -93,11 +93,8 @@ public static class HeroMapping
NeedsRender(image),
PreviewSrc: PreviewSrc(image));
public static bool IsLive(HeroContent hero, DateTimeOffset now)
=> hero.IsActive
&& !string.IsNullOrWhiteSpace(hero.Title)
&& (hero.StartsAt is null || hero.StartsAt <= now)
&& (hero.EndsAt is null || now < hero.EndsAt);
/// <summary>The hero is always on: it is live as soon as it has usable content (a title). There is no switch and no schedule (a deliberate choice; they may come back later, per slide).</summary>
public static bool IsLive(HeroContent hero) => !string.IsNullOrWhiteSpace(hero.Title);
private static List<HeroButtonDto> Buttons(HeroContent hero)
{
@@ -118,7 +115,7 @@ public static class HeroMapping
/// <summary>The published hero, or null when it is not live. Inactive slides and slides without a stored image are left out.</summary>
public static PublicHeroDto? ToPublic(HeroContent hero, DateTimeOffset now, int maxPublishedSlides)
{
if (!IsLive(hero, now))
if (!IsLive(hero))
{
return null;
}
@@ -159,7 +156,7 @@ public static class HeroMapping
{
if (hero is null)
{
return new HeroAdminDto(null, string.Empty, null, null, HeroDisplays.Single, [], true, null, null, [], false, null, maxPublishedSlides);
return new HeroAdminDto(null, string.Empty, null, null, HeroDisplays.Single, [], [], false, null, maxPublishedSlides);
}
var slides = hero.Slides
@@ -175,11 +172,8 @@ public static class HeroMapping
hero.Lead,
hero.Display,
Buttons(hero),
hero.IsActive,
hero.StartsAt,
hero.EndsAt,
slides,
IsLive(hero, now),
IsLive(hero),
hero.UpdatedAt,
maxPublishedSlides);
}
@@ -19,7 +19,7 @@ public interface IHeroService
/// <summary>The hero for the admin (empty defaults when none exists yet), with whether it is live right now.</summary>
Task<HeroAdminDto> GetAsync(CancellationToken cancellationToken);
/// <summary>Replaces the whole hero: texts, buttons, display, schedule and the ordered slide list.</summary>
/// <summary>Replaces the whole hero: texts, buttons, display and the ordered slide list.</summary>
Task<HeroAdminDto> SaveAsync(HeroSaveRequest request, Guid callerId, CancellationToken cancellationToken);
}
@@ -163,9 +163,6 @@ public class HeroService(
hero.Button2Label = buttons.Count > 1 ? buttons[1].Label : null;
hero.Button2Target = buttons.Count > 1 ? buttons[1].Target : null;
hero.IsActive = r.IsActive;
hero.StartsAt = r.StartsAt;
hero.EndsAt = r.EndsAt;
hero.UpdatedAt = now;
hero.LastModifiedByUserId = callerId;
}
@@ -175,7 +172,7 @@ public class HeroService(
public interface IPublicHeroService
{
/// <summary>The hero as websites get it, or null (no hero, switched off, outside the schedule or without a title).</summary>
/// <summary>The hero as websites get it, or null (no hero or without a title).</summary>
Task<PublicHeroDto?> GetActiveAsync(CancellationToken cancellationToken);
}
@@ -22,9 +22,6 @@
"targetInvalid": "Choose a part of the page (for example #contact), a page of the site (for example /privacy) or a full web address (https://…).",
"tooMany": "At most {max} buttons are possible."
},
"schedule": {
"endAfterStart": "The end must be after the start."
},
"slide": {
"imageRequired": "Every image in the list needs a photo.",
"imageUnknown": "An image in the list does not exist (any more).",
@@ -22,9 +22,6 @@
"targetInvalid": "Kies een onderdeel van de pagina (bijvoorbeeld #contact), een pagina van de site (bijvoorbeeld /privacy) of een volledig webadres (https://…).",
"tooMany": "Er zijn maximaal {max} knoppen mogelijk."
},
"schedule": {
"endAfterStart": "Het einde moet na het begin liggen."
},
"slide": {
"imageRequired": "Elke afbeelding in de lijst heeft een foto nodig.",
"imageUnknown": "Een afbeelding in de lijst bestaat niet (meer).",