diff --git a/aidlc-docs/features/media-library/assumptions-and-open-questions.md b/aidlc-docs/features/media-library/assumptions-and-open-questions.md
index 691b1fa..e4d56f5 100644
--- a/aidlc-docs/features/media-library/assumptions-and-open-questions.md
+++ b/aidlc-docs/features/media-library/assumptions-and-open-questions.md
@@ -21,3 +21,10 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu
| 15 | **Selection range** with shift-click and "select all": across pages or the loaded page? | The loaded list (the clean-up list is loaded fully, the library list incrementally; "select all" says how many are loaded and offers "select all N" for a filtered list). | Strictly the current page: simpler, less useful for a clean-up of hundreds. | Selection component |
| 16 | **Deleting files from the store** when a photo is deleted. | The original and the set directories of that photo are deleted through `IMediaStore` after the database rows; a set shared with another use (same hash) is kept until no use references it. | Soft delete first (see 12). | `IMediaStore.DeleteSetAsync`, `HeroRepository.GetReferencedSetHashesAsync` |
| 17 | **Language of the screen**: nl and en like the rest of the admin. | Yes, `media.*` keys in both files; terms: "Mediabibliotheek", "Opruimen", "Alleen ongebruikte foto's". | Dutch only: remove one file. | `frontend/src/i18n/locales` |
+| 18 | **Phase A built (2026-11-17, on assumptions)**: what is in the first step? | Read-only only: the usage contract (`IMediaUsageProvider`, `MediaLibraryService`, pure `CleanupSelection`), the Hero provider and the selection components in the frontend (`PhotoSelectionList`, `BulkActionBar`, selection rules). **No endpoint, no screen, no delete, no migration, no address change yet.** | Wire the screen and endpoints next (list, storage, clean-up preview) and then delete (needs a Hero delete path and Bryan's check of assumptions 3, 7 and 10). | `Core/Media/Library`, `Modules.Hero/Services/HeroMediaUsageProvider.cs`, `frontend/src/features/media` |
+| 19 | The **position** of a slide in "Hero, slide 3". | Rank by `SortOrder` within its hero, counting slides that are switched off, 1-based; a slide that is off still counts as a use and is shown "(uit/off)". | Count only active slides, or show the slide's title instead. | `HeroMediaUsageProvider.ListUsesAsync` |
+| 20 | The **thumbnail** of a Hero photo in the library. | The smallest published WebP variant of the current set; none yet (a grey "no preview") while the set is not cut. | Use the full-frame preview (`full-*.webp`), which shows the whole picture instead of the wide crop. | `HeroMediaUsageProvider.Thumbnail` |
+| 21 | A **name** for a photo. | Photos have no file name today (`HeroImage` does not store it), so the library shows a neutral label (date and size); a name field comes with the library's own tables (phase B). | Store the original file name at upload now (a small Hero migration, additive). | `PhotoItem.name`, phase B |
+| 22 | **Select all** and ranges with photos that cannot be selected (in use during a clean-up). | They are skipped by "select all" and by shift-ranges; the header box shows "some" when only part is selected. | Include them but refuse at confirmation. | `PhotoSelectionList`, `selection.ts` |
+| 23 | Where does Hero **list all photos** (performance)? | In memory, newest first, as the rest of the Hero repository does (a few dozen photos; the MySQL provider has limits with Guid lists). Paging comes with the screen when the count grows. | Server-side paging by `CreatedAt` (needs an index). | `HeroRepository.GetAllImagesReadOnlyAsync` |
+| 24 | **Tile ratios of the ASF mosaic** (assumption 1). | Asked of the ASF session through SLS-Main (2026-11-17); until then the design only names "tiles with a fixed set of ratios per page". | Each answer only adds use definitions. | Application design section 4 |
diff --git a/frontend/src/features/media/components/BulkActionBar.tsx b/frontend/src/features/media/components/BulkActionBar.tsx
new file mode 100644
index 0000000..f58084d
--- /dev/null
+++ b/frontend/src/features/media/components/BulkActionBar.tsx
@@ -0,0 +1,62 @@
+import type { ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Button } from '@/components/ui/button';
+
+export interface BulkAction {
+ id: string;
+ label: string;
+ /** A destructive action (delete) is drawn in the warning colour. */
+ destructive?: boolean;
+ disabled?: boolean;
+ icon?: ReactNode;
+ run: () => void;
+}
+
+interface BulkActionBarProps {
+ count: number;
+ actions: readonly BulkAction[];
+ onClear: () => void;
+ /** Extra text on the bar, for example the bytes the selection takes. */
+ summary?: ReactNode;
+}
+
+/**
+ * The actions on the selected photos. The actions are data, so more of them (tags, move) can be added without touching
+ * the list. It shows nothing while nothing is selected.
+ */
+export function BulkActionBar({ count, actions, onClear, summary }: BulkActionBarProps) {
+ const { t } = useTranslation();
+ if (count === 0) return null;
+ return (
+
+
+ {t('media.bulk.selected', { count })}
+
+ {summary &&
{summary} }
+
+
+ {t('media.bulk.clear')}
+
+ {actions.map((action) => (
+
+ {action.icon}
+ {action.label}
+
+ ))}
+
+
+ );
+}
diff --git a/frontend/src/features/media/components/PhotoSelectionList.test.tsx b/frontend/src/features/media/components/PhotoSelectionList.test.tsx
new file mode 100644
index 0000000..2c8ce7b
--- /dev/null
+++ b/frontend/src/features/media/components/PhotoSelectionList.test.tsx
@@ -0,0 +1,121 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { useState } from 'react';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import i18n from '@/i18n/config';
+import { emptySelection, type Selection } from '../lib/selection';
+import { BulkActionBar } from './BulkActionBar';
+import { PhotoSelectionList, type PhotoItem } from './PhotoSelectionList';
+
+const items: PhotoItem[] = [
+ { id: 'p1', name: 'Foto 1', bytes: 2048, createdAt: '2026-11-17T10:00:00Z', uses: [{ module: 'hero', kind: 'slide', position: 3, active: true }] },
+ { id: 'p2', name: 'Foto 2', bytes: 500, createdAt: '2026-11-16T10:00:00Z', uses: [] },
+ { id: 'p3', name: 'Foto 3', bytes: 1048576, createdAt: '2026-11-15T10:00:00Z', uses: [{ module: 'hero', kind: 'slide', position: 1, active: false }] },
+ { id: 'p4', name: 'Foto 4', bytes: 10, createdAt: '2026-11-14T10:00:00Z', uses: [] },
+];
+
+function Harness({ disabled }: { disabled?: (item: PhotoItem) => boolean }) {
+ const [selection, setSelection] = useState(emptySelection);
+ return (
+ <>
+
+ setSelection(emptySelection)} />
+ >
+ );
+}
+
+beforeEach(async () => {
+ await i18n.changeLanguage('nl');
+});
+
+describe('PhotoSelectionList', () => {
+ it('shows each photo with where it is used, or that it is not used', () => {
+ render( );
+
+ expect(screen.getByTestId('photo-usage-p1')).toHaveTextContent('Hero, slide 3');
+ expect(screen.getByTestId('photo-usage-p2')).toHaveTextContent('Niet gebruikt');
+ expect(screen.getByTestId('photo-usage-p3')).toHaveTextContent('Hero, slide 1 (uit)');
+ });
+
+ it('selects a photo with a click and announces the count', async () => {
+ render( );
+
+ await userEvent.click(screen.getByRole('checkbox', { name: 'Foto 2' }));
+
+ expect(screen.getByRole('checkbox', { name: 'Foto 2' })).toBeChecked();
+ expect(screen.getByTestId('photo-selection-status')).toHaveTextContent('1 foto geselecteerd');
+ expect(screen.getByTestId('bulk-count')).toHaveTextContent('1 foto geselecteerd');
+ });
+
+ it('selects a range with shift-click', async () => {
+ render( );
+
+ const user = userEvent.setup();
+
+ await user.click(screen.getByRole('checkbox', { name: 'Foto 1' }));
+ await user.keyboard('{Shift>}');
+ await user.click(screen.getByRole('checkbox', { name: 'Foto 3' }));
+ await user.keyboard('{/Shift}');
+
+ expect(screen.getByRole('checkbox', { name: 'Foto 2' })).toBeChecked();
+ expect(screen.getByRole('checkbox', { name: 'Foto 3' })).toBeChecked();
+ expect(screen.getByRole('checkbox', { name: 'Foto 4' })).not.toBeChecked();
+ });
+
+ it('works with the keyboard: Space toggles the focused photo', async () => {
+ render( );
+
+ screen.getByRole('checkbox', { name: 'Foto 4' }).focus();
+ await userEvent.keyboard(' ');
+
+ expect(screen.getByRole('checkbox', { name: 'Foto 4' })).toBeChecked();
+ });
+
+ it('select all shows the in-between state for part of the list and clears everything on a second click', async () => {
+ render( );
+ const all = screen.getByRole('checkbox', { name: 'Alles selecteren' }) as HTMLInputElement;
+
+ await userEvent.click(screen.getByRole('checkbox', { name: 'Foto 1' }));
+ expect(all.indeterminate).toBe(true);
+
+ await userEvent.click(all);
+ expect(screen.getByRole('checkbox', { name: 'Foto 4' })).toBeChecked();
+ expect(all).toBeChecked();
+
+ await userEvent.click(all);
+ expect(screen.queryByTestId('bulk-action-bar')).not.toBeInTheDocument();
+ });
+
+ it('leaves out photos that cannot be selected, from select all and from ranges', async () => {
+ render( item.uses.length > 0} />);
+
+ expect(screen.getByRole('checkbox', { name: 'Foto 1' })).toBeDisabled();
+ await userEvent.click(screen.getByRole('checkbox', { name: 'Alles selecteren' }));
+
+ expect(screen.getByRole('checkbox', { name: 'Foto 2' })).toBeChecked();
+ expect(screen.getByRole('checkbox', { name: 'Foto 4' })).toBeChecked();
+ expect(screen.getByRole('checkbox', { name: 'Foto 1' })).not.toBeChecked();
+ expect(screen.getByTestId('bulk-count')).toHaveTextContent('2 foto');
+ });
+
+ it('shows a message when there are no photos', () => {
+ render( );
+
+ expect(screen.getByTestId('photo-list-empty')).toHaveTextContent('Er zijn geen foto');
+ });
+});
+
+describe('BulkActionBar', () => {
+ it('shows nothing without a selection, then the count and the actions, and clears the selection', async () => {
+ render( );
+ expect(screen.queryByTestId('bulk-action-bar')).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getByRole('checkbox', { name: 'Foto 1' }));
+ expect(screen.getByRole('toolbar', { name: 'Acties op de selectie' })).toBeInTheDocument();
+ expect(screen.getByTestId('bulk-action-delete')).toHaveTextContent('Verwijderen');
+
+ await userEvent.click(screen.getByTestId('bulk-clear'));
+ expect(screen.queryByTestId('bulk-action-bar')).not.toBeInTheDocument();
+ expect(screen.getByRole('checkbox', { name: 'Foto 1' })).not.toBeChecked();
+ });
+});
diff --git a/frontend/src/features/media/components/PhotoSelectionList.tsx b/frontend/src/features/media/components/PhotoSelectionList.tsx
new file mode 100644
index 0000000..cb87ab6
--- /dev/null
+++ b/frontend/src/features/media/components/PhotoSelectionList.tsx
@@ -0,0 +1,132 @@
+import { useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Checkbox } from '@/components/ui/checkbox';
+import { selectAll, selectRange, stateOf, type Selection } from '../lib/selection';
+
+export interface PhotoUse {
+ /** The module key, for example `hero`; the screen translates it. */
+ module: string;
+ /** The kind of place, for example `slide`. */
+ kind: string;
+ position?: number | null;
+ active: boolean;
+}
+
+export interface PhotoItem {
+ id: string;
+ thumbnailUrl?: string | null;
+ name: string;
+ bytes: number;
+ createdAt: string;
+ uses: readonly PhotoUse[];
+}
+
+interface PhotoSelectionListProps {
+ items: readonly PhotoItem[];
+ selection: Selection;
+ onSelectionChange: (selection: Selection) => void;
+ /** Photos that cannot be selected (for example in use during a clean-up). */
+ isDisabled?: (item: PhotoItem) => boolean;
+}
+
+function formatBytes(bytes: number, language: string) {
+ const units = ['B', 'KB', 'MB', 'GB'];
+ let value = bytes;
+ let unit = 0;
+ while (value >= 1024 && unit < units.length - 1) {
+ value /= 1024;
+ unit++;
+ }
+ return `${new Intl.NumberFormat(language, { maximumFractionDigits: unit === 0 ? 0 : 1 }).format(value)} ${units[unit]}`;
+}
+
+/**
+ * The photos with a checkbox each: click or Space to toggle, shift-click for a range, a "select all" box in the header
+ * (with the in-between state), and a live announcement of the count. One component for the library and the clean-up.
+ */
+export function PhotoSelectionList({ items, selection, onSelectionChange, isDisabled }: PhotoSelectionListProps) {
+ const { t, i18n } = useTranslation();
+ const anchor = useRef(null);
+ const selectable = items.filter((item) => !isDisabled?.(item));
+ const selectableIds = selectable.map((item) => item.id);
+ const state = stateOf(selection, selectableIds);
+ const dateFormat = new Intl.DateTimeFormat(i18n.language, { dateStyle: 'medium', timeStyle: 'short' });
+
+ const onItemClick = (id: string, checked: boolean, shift: boolean) => {
+ onSelectionChange(selectRange(selection, selectableIds, shift ? anchor.current : null, id, checked));
+ anchor.current = id;
+ };
+
+ const usageLabel = (use: PhotoUse) => {
+ const place = t(`media.use.${use.kind}`, { defaultValue: use.kind });
+ const where = use.position ? `${place} ${use.position}` : place;
+ return `${t(`media.module.${use.module}`, { defaultValue: use.module })}, ${where}${use.active ? '' : ` (${t('media.use.off')})`}`;
+ };
+
+ if (items.length === 0) {
+ return (
+
+ {t('media.list.empty')}
+
+ );
+ }
+
+ return (
+
+
+ onSelectionChange(state === 'all' ? new Set() : selectAll(selectableIds))}
+ />
+ {t('media.list.selectAll')}
+
+ {t('media.bulk.selected', { count: selection.size })}
+
+
+
+ {items.map((item) => {
+ const disabled = isDisabled?.(item) ?? false;
+ const labelId = `photo-${item.id}-label`;
+ return (
+
+ undefined}
+ onClick={(event) => onItemClick(item.id, event.currentTarget.checked, event.shiftKey)}
+ />
+ {item.thumbnailUrl ? (
+
+ ) : (
+
+ {t('media.list.noThumbnail')}
+
+ )}
+
+
+ {item.name}
+
+
+ {dateFormat.format(new Date(item.createdAt))} ยท {formatBytes(item.bytes, i18n.language)}
+
+
+ {item.uses.length === 0 ? (
+ {t('media.use.none')}
+ ) : (
+ {item.uses.map(usageLabel).join('; ')}
+ )}
+
+
+
+ );
+ })}
+
+
+ );
+}
diff --git a/frontend/src/features/media/lib/selection.test.ts b/frontend/src/features/media/lib/selection.test.ts
new file mode 100644
index 0000000..2a2eebf
--- /dev/null
+++ b/frontend/src/features/media/lib/selection.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+import { emptySelection, prune, selectAll, selectRange, stateOf, toggle } from './selection';
+
+const ids = ['a', 'b', 'c', 'd', 'e'];
+
+describe('selection rules', () => {
+ it('toggles one photo on and off without changing the original set', () => {
+ const one = toggle(emptySelection, 'b');
+ expect([...one]).toEqual(['b']);
+ expect([...toggle(one, 'b')]).toEqual([]);
+ expect(emptySelection.size).toBe(0);
+ });
+
+ it('selects a range from the anchor to the target, in either direction', () => {
+ expect([...selectRange(emptySelection, ids, 'b', 'd', true)].sort()).toEqual(['b', 'c', 'd']);
+ expect([...selectRange(emptySelection, ids, 'd', 'b', true)].sort()).toEqual(['b', 'c', 'd']);
+ });
+
+ it('clears a range when the target is switched off', () => {
+ const all = selectAll(ids);
+ expect([...selectRange(all, ids, 'a', 'c', false)].sort()).toEqual(['d', 'e']);
+ });
+
+ it('only changes the target without an anchor or with an anchor that is gone', () => {
+ expect([...selectRange(emptySelection, ids, null, 'c', true)]).toEqual(['c']);
+ expect([...selectRange(emptySelection, ids, 'zzz', 'c', true)]).toEqual(['c']);
+ });
+
+ it('ignores a target that is not in the list', () => {
+ const selection = new Set(['a']);
+ expect(selectRange(selection, ids, 'a', 'nope', true)).toBe(selection);
+ });
+
+ it('reports none, some and all', () => {
+ expect(stateOf(emptySelection, ids)).toBe('none');
+ expect(stateOf(new Set(['a']), ids)).toBe('some');
+ expect(stateOf(selectAll(ids), ids)).toBe('all');
+ expect(stateOf(selectAll(ids), [])).toBe('none');
+ });
+
+ it('drops ids that left the list and keeps the same object when nothing changes', () => {
+ const selection = new Set(['a', 'x']);
+ expect([...prune(selection, ids)]).toEqual(['a']);
+ const clean = new Set(['a']);
+ expect(prune(clean, ids)).toBe(clean);
+ });
+});
diff --git a/frontend/src/features/media/lib/selection.ts b/frontend/src/features/media/lib/selection.ts
new file mode 100644
index 0000000..342b041
--- /dev/null
+++ b/frontend/src/features/media/lib/selection.ts
@@ -0,0 +1,51 @@
+/**
+ * The selection of photos in the library, as pure functions over a set of ids. The list component keeps the state; these
+ * functions are the rules (toggle, range with shift-click, all, none), so they are easy to test.
+ */
+
+export type Selection = ReadonlySet;
+
+export const emptySelection: Selection = new Set();
+
+export function selectAll(ids: readonly string[]): Selection {
+ return new Set(ids);
+}
+
+export function toggle(selection: Selection, id: string): Selection {
+ const next = new Set(selection);
+ if (!next.delete(id)) next.add(id);
+ return next;
+}
+
+/**
+ * Shift-click: every photo between the anchor (the last one clicked) and the target gets the state of the target's new
+ * value. `ids` is the displayed order. Without a known anchor, or an anchor that is no longer in the list, only the
+ * target changes.
+ */
+export function selectRange(selection: Selection, ids: readonly string[], anchor: string | null, target: string, value: boolean): Selection {
+ const to = ids.indexOf(target);
+ if (to < 0) return selection;
+ const from = anchor === null ? -1 : ids.indexOf(anchor);
+ const [start, end] = from < 0 ? [to, to] : [Math.min(from, to), Math.max(from, to)];
+ const next = new Set(selection);
+ for (const id of ids.slice(start, end + 1)) {
+ if (value) next.add(id);
+ else next.delete(id);
+ }
+ return next;
+}
+
+/** Drops ids that are no longer in the list (after a delete or a filter change). */
+export function prune(selection: Selection, ids: readonly string[]): Selection {
+ const visible = new Set(ids);
+ const next = new Set([...selection].filter((id) => visible.has(id)));
+ return next.size === selection.size ? selection : next;
+}
+
+export type SelectionState = 'none' | 'some' | 'all';
+
+export function stateOf(selection: Selection, ids: readonly string[]): SelectionState {
+ if (ids.length === 0) return 'none';
+ const count = ids.filter((id) => selection.has(id)).length;
+ return count === 0 ? 'none' : count === ids.length ? 'all' : 'some';
+}
diff --git a/frontend/src/i18n/locales/en/translation.json b/frontend/src/i18n/locales/en/translation.json
index 438d053..694e495 100644
--- a/frontend/src/i18n/locales/en/translation.json
+++ b/frontend/src/i18n/locales/en/translation.json
@@ -781,5 +781,21 @@
"hasChanges": "unsaved changes",
"hasErrors": "has errors"
}
+ },
+ "media": {
+ "module": { "hero": "Hero" },
+ "use": { "slide": "slide", "none": "Not used", "off": "off" },
+ "list": {
+ "label": "Photos",
+ "empty": "There are no photos.",
+ "selectAll": "Select all",
+ "noThumbnail": "No preview"
+ },
+ "bulk": {
+ "label": "Actions on the selection",
+ "selected_one": "{{count}} photo selected",
+ "selected_other": "{{count}} photos selected",
+ "clear": "Clear selection"
+ }
}
}
diff --git a/frontend/src/i18n/locales/nl/translation.json b/frontend/src/i18n/locales/nl/translation.json
index 24729ed..53725a7 100644
--- a/frontend/src/i18n/locales/nl/translation.json
+++ b/frontend/src/i18n/locales/nl/translation.json
@@ -781,5 +781,21 @@
"hasChanges": "niet-opgeslagen wijzigingen",
"hasErrors": "bevat fouten"
}
+ },
+ "media": {
+ "module": { "hero": "Hero" },
+ "use": { "slide": "slide", "none": "Niet gebruikt", "off": "uit" },
+ "list": {
+ "label": "Foto's",
+ "empty": "Er zijn geen foto's.",
+ "selectAll": "Alles selecteren",
+ "noThumbnail": "Geen voorbeeld"
+ },
+ "bulk": {
+ "label": "Acties op de selectie",
+ "selected_one": "{{count}} foto geselecteerd",
+ "selected_other": "{{count}} foto's geselecteerd",
+ "clear": "Selectie wissen"
+ }
}
}
diff --git a/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs b/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs
new file mode 100644
index 0000000..4c8a827
--- /dev/null
+++ b/src/SlpModularCms.Core.Tests/Media/MediaLibraryTests.cs
@@ -0,0 +1,91 @@
+using FluentAssertions;
+using SlpModularCms.Core.Media.Library;
+using Xunit;
+
+namespace SlpModularCms.Core.Tests.Media;
+
+public class MediaLibraryTests
+{
+ private static readonly DateTimeOffset Now = new(2026, 11, 17, 12, 0, 0, TimeSpan.Zero);
+
+ private static MediaLibraryItem Item(int daysOld, bool used = false, long bytes = 1000, string module = "hero")
+ {
+ var photo = new MediaPhoto(module, Guid.NewGuid(), bytes, 1600, 1067, Now.AddDays(-daysOld), null);
+ IReadOnlyList uses = used ? [new MediaUse(module, photo.Id, "slide", 1, true)] : [];
+ return new MediaLibraryItem(photo, uses);
+ }
+
+ [Fact]
+ public void Cleanup_selects_photos_older_than_the_period_newest_first()
+ {
+ var items = new[] { Item(3), Item(10), Item(30), Item(8) };
+
+ var selected = CleanupSelection.Select(items, Now, 7, onlyUnused: false);
+
+ selected.Select(i => (Now - i.Photo.CreatedAt).Days).Should().Equal(8, 10, 30);
+ }
+
+ [Fact]
+ public void Cleanup_only_unused_leaves_out_photos_in_use_but_all_photos_does_not()
+ {
+ var used = Item(20, used: true);
+ var unused = Item(20);
+
+ CleanupSelection.Select([used, unused], Now, 7, onlyUnused: true).Should().ContainSingle().Which.Should().Be(unused);
+ CleanupSelection.Select([used, unused], Now, 7, onlyUnused: false).Should().HaveCount(2);
+ }
+
+ [Fact]
+ public void A_photo_used_only_by_an_inactive_slide_still_counts_as_used()
+ {
+ var photo = new MediaPhoto("hero", Guid.NewGuid(), 10, 100, 100, Now.AddDays(-40), null);
+ var item = new MediaLibraryItem(photo, [new MediaUse("hero", photo.Id, "slide", 2, Active: false)]);
+
+ CleanupSelection.Select([item], Now, 7, onlyUnused: true).Should().BeEmpty();
+ }
+
+ [Theory]
+ [InlineData(-5, 1)]
+ [InlineData(0, 1)]
+ [InlineData(7, 7)]
+ [InlineData(365, 365)]
+ [InlineData(4000, 365)]
+ public void The_period_stays_inside_the_slider_range(int days, int expected) => CleanupSelection.ClampDays(days).Should().Be(expected);
+
+ [Fact]
+ public void A_photo_exactly_at_the_boundary_is_not_selected_yet()
+ {
+ var item = Item(7);
+
+ CleanupSelection.Select([item], Now, 7, onlyUnused: false).Should().BeEmpty();
+ }
+
+ [Fact]
+ public void Cleanup_bytes_adds_up_the_originals() => CleanupSelection.Bytes([Item(9, bytes: 100), Item(9, bytes: 250)]).Should().Be(350);
+
+ [Fact]
+ public async Task The_library_merges_all_modules_newest_first_and_attaches_the_uses()
+ {
+ var oldHero = new MediaPhoto("hero", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-5), null);
+ var newGallery = new MediaPhoto("gallery", Guid.NewGuid(), 1, 1, 1, Now.AddDays(-1), null);
+ var heroUse = new MediaUse("hero", oldHero.Id, "slide", 3, true);
+ var library = new MediaLibraryService([new FakeProvider("hero", [oldHero], [heroUse]), new FakeProvider("gallery", [newGallery], [])]);
+
+ var items = await library.ListAsync(CancellationToken.None);
+
+ items.Select(i => i.Photo.Module).Should().Equal("gallery", "hero");
+ items[0].InUse.Should().BeFalse();
+ items[1].Uses.Should().ContainSingle().Which.Should().Be(heroUse);
+ library.Modules.Should().Equal("gallery", "hero");
+ }
+
+ private sealed class FakeProvider(string module, MediaPhoto[] photos, MediaUse[] uses) : IMediaUsageProvider
+ {
+ public string Module => module;
+
+ public Task> ListPhotosAsync(CancellationToken cancellationToken) => Task.FromResult>(photos);
+
+ public Task> ListUsesAsync(IReadOnlyCollection photoIds, CancellationToken cancellationToken)
+ => Task.FromResult>(uses.Where(u => photoIds.Contains(u.PhotoId)).ToList());
+ }
+}
diff --git a/src/SlpModularCms.Core/Media/Library/CleanupSelection.cs b/src/SlpModularCms.Core/Media/Library/CleanupSelection.cs
new file mode 100644
index 0000000..6adb8c7
--- /dev/null
+++ b/src/SlpModularCms.Core/Media/Library/CleanupSelection.cs
@@ -0,0 +1,30 @@
+namespace SlpModularCms.Core.Media.Library;
+
+///
+/// The photos a clean-up would preselect: uploaded before the period and, by default, not used anywhere. Pure, so it is
+/// easy to test. The period is measured from the upload date (assumption 8 of the media-library list).
+///
+public static class CleanupSelection
+{
+ public const int DefaultDays = 7;
+ public const int MinDays = 1;
+ public const int MaxDays = 365;
+
+ /// The days kept inside the slider range.
+ public static int ClampDays(int days) => Math.Clamp(days, MinDays, MaxDays);
+
+ /// Items uploaded more than days before , newest first; with only those no module uses.
+ public static IReadOnlyList Select(IEnumerable items, DateTimeOffset now, int days, bool onlyUnused)
+ {
+ var cutoff = now.AddDays(-ClampDays(days));
+ return items
+ .Where(item => item.Photo.CreatedAt < cutoff)
+ .Where(item => !onlyUnused || !item.InUse)
+ .OrderByDescending(item => item.Photo.CreatedAt)
+ .ThenBy(item => item.Photo.Id)
+ .ToList();
+ }
+
+ /// The bytes the given items take (originals; the variants are counted by the storage service).
+ public static long Bytes(IEnumerable items) => items.Sum(item => item.Photo.Bytes);
+}
diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs
new file mode 100644
index 0000000..7c34f13
--- /dev/null
+++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryService.cs
@@ -0,0 +1,32 @@
+namespace SlpModularCms.Core.Media.Library;
+
+/// The library over all modules that report photos: one list, newest first, each photo with its uses. Read-only.
+public interface IMediaLibraryService
+{
+ /// All photos of all modules with their uses, newest first.
+ Task> ListAsync(CancellationToken cancellationToken);
+
+ /// The modules that report photos (the screen warns about a module that is not in this list).
+ IReadOnlyList Modules { get; }
+}
+
+public sealed class MediaLibraryService(IEnumerable providers) : IMediaLibraryService
+{
+ private readonly IMediaUsageProvider[] _providers = providers.ToArray();
+
+ public IReadOnlyList Modules => _providers.Select(p => p.Module).OrderBy(m => m, StringComparer.Ordinal).ToList();
+
+ public async Task> ListAsync(CancellationToken cancellationToken)
+ {
+ var items = new List();
+ foreach (var provider in _providers)
+ {
+ var photos = await provider.ListPhotosAsync(cancellationToken);
+ var uses = await provider.ListUsesAsync(photos.Select(p => p.Id).ToList(), cancellationToken);
+ var byPhoto = uses.ToLookup(u => u.PhotoId);
+ items.AddRange(photos.Select(photo => new MediaLibraryItem(photo, byPhoto[photo.Id].ToList())));
+ }
+
+ return items.OrderByDescending(i => i.Photo.CreatedAt).ThenBy(i => i.Photo.Id).ToList();
+ }
+}
diff --git a/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs b/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs
new file mode 100644
index 0000000..99023b3
--- /dev/null
+++ b/src/SlpModularCms.Core/Media/Library/MediaLibraryTypes.cs
@@ -0,0 +1,34 @@
+namespace SlpModularCms.Core.Media.Library;
+
+/// A photo as the library shows it. The module that owns it fills it; the library only reads.
+/// The module key (for example hero ); with it names the photo.
+/// A public address of a small variant, or null while no variant exists yet.
+public sealed record MediaPhoto(string Module, Guid Id, long Bytes, int Width, int Height, DateTimeOffset CreatedAt, string? ThumbnailUrl);
+
+/// One place where a photo is used. The library shows it as "module, place kind, position" (for example "Hero, slide 3").
+/// What kind of place (for example slide ); the screen translates it.
+/// The 1-based position inside the place, or null when it has none.
+/// False when the place is switched off (still a use: the photo is kept).
+public sealed record MediaUse(string Module, Guid PhotoId, string PlaceKind, int? Position, bool Active);
+
+/// A photo with everything that uses it.
+public sealed record MediaLibraryItem(MediaPhoto Photo, IReadOnlyList Uses)
+{
+ public bool InUse => Uses.Count > 0;
+}
+
+///
+/// What a module tells the media library. Read-only: the library never changes a module's data through this contract
+/// (deleting and detaching come in a later step). The answers are computed from the module's own data, never copied.
+///
+public interface IMediaUsageProvider
+{
+ /// The module key, lower case, equal to its media area when it has one.
+ string Module { get; }
+
+ /// The photos of this module, newest first.
+ Task> ListPhotosAsync(CancellationToken cancellationToken);
+
+ /// Where the given photos are used (only photos of this module).
+ Task> ListUsesAsync(IReadOnlyCollection photoIds, CancellationToken cancellationToken);
+}
diff --git a/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs b/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs
index 6b93cc4..4fdd8bd 100644
--- a/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs
+++ b/src/SlpModularCms.Core/Media/MediaServiceCollectionExtensions.cs
@@ -22,6 +22,7 @@ public static class MediaServiceCollectionExtensions
services.TryAddSingleton();
services.TryAddSingleton();
services.TryAddSingleton();
+ services.TryAddScoped();
if (!services.Any(d => d.ImplementationType == typeof(ImageProcessorSelfTest)))
{
services.AddHostedService();
diff --git a/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs b/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs
new file mode 100644
index 0000000..8d34332
--- /dev/null
+++ b/src/SlpModularCms.Modules.Hero.Tests/HeroMediaUsageProviderTests.cs
@@ -0,0 +1,51 @@
+using FluentAssertions;
+using SlpModularCms.Core.Media.Library;
+using SlpModularCms.Modules.Hero.Models;
+using SlpModularCms.Modules.Hero.Services;
+using Xunit;
+
+namespace SlpModularCms.Modules.Hero.Tests;
+
+public class HeroMediaUsageProviderTests
+{
+ [Fact]
+ public async Task Lists_the_images_newest_first_with_a_thumbnail_and_reports_one_use_per_slide_with_its_position()
+ {
+ using var rig = new HeroTestRig();
+ var a = await rig.Upload(HeroTestRig.Photo(seed: 1));
+ rig.Time.Now = rig.Time.Now.AddMinutes(5);
+ var b = await rig.Upload(HeroTestRig.Photo(seed: 2));
+ rig.Time.Now = rig.Time.Now.AddMinutes(5);
+ var unused = await rig.Upload(HeroTestRig.Photo(seed: 3));
+ await rig.Service.SaveAsync(
+ new HeroSaveRequest("Titel", null, null, "single", [],
+ [new HeroSlideRequest(null, Guid.Parse(b.Id), "tweede"), new HeroSlideRequest(null, Guid.Parse(a.Id), "eerste", IsActive: false)]),
+ HeroTestRig.Admin, CancellationToken.None);
+ var provider = new HeroMediaUsageProvider(rig.Repository);
+
+ var photos = await provider.ListPhotosAsync(CancellationToken.None);
+ var uses = await provider.ListUsesAsync(photos.Select(p => p.Id).ToList(), CancellationToken.None);
+
+ provider.Module.Should().Be("hero");
+ photos.Select(p => p.Id).Should().Equal(Guid.Parse(unused.Id), Guid.Parse(b.Id), Guid.Parse(a.Id));
+ photos.Should().OnlyContain(p => p.ThumbnailUrl != null && p.ThumbnailUrl.StartsWith("/media/hero/"));
+ uses.Should().HaveCount(2);
+ uses.Single(u => u.PhotoId == Guid.Parse(b.Id)).Should().Be(new MediaUse("hero", Guid.Parse(b.Id), "slide", 1, true));
+ uses.Single(u => u.PhotoId == Guid.Parse(a.Id)).Should().Be(new MediaUse("hero", Guid.Parse(a.Id), "slide", 2, false));
+ uses.Should().NotContain(u => u.PhotoId == Guid.Parse(unused.Id));
+ }
+
+ [Fact]
+ public async Task Reading_changes_nothing()
+ {
+ using var rig = new HeroTestRig();
+ var image = await rig.Upload(HeroTestRig.Photo());
+ var provider = new HeroMediaUsageProvider(rig.Repository);
+
+ await provider.ListPhotosAsync(CancellationToken.None);
+ await provider.ListUsesAsync([Guid.Parse(image.Id)], CancellationToken.None);
+
+ (await rig.Repository.CountImagesAsync(CancellationToken.None)).Should().Be(1);
+ rig.Db.ChangeTracker.HasChanges().Should().BeFalse();
+ }
+}
diff --git a/src/SlpModularCms.Modules.Hero/HeroModule.cs b/src/SlpModularCms.Modules.Hero/HeroModule.cs
index 1850048..939508c 100644
--- a/src/SlpModularCms.Modules.Hero/HeroModule.cs
+++ b/src/SlpModularCms.Modules.Hero/HeroModule.cs
@@ -7,6 +7,7 @@ using Microsoft.Extensions.DependencyInjection;
using SlpModularCms.Core.Hosting;
using SlpModularCms.Core.Hosting.Website;
using SlpModularCms.Core.Media;
+using SlpModularCms.Core.Media.Library;
using SlpModularCms.Core.Media.Magick;
using SlpModularCms.Core.Modules;
using SlpModularCms.Core.Texts;
@@ -44,6 +45,7 @@ public class HeroModule : IModule
services.AddScoped();
services.AddScoped();
services.AddScoped();
+ services.AddScoped();
services.AddScoped();
services.AddScoped();
services.AddScoped();
diff --git a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs
index 76f7e1f..2b2126f 100644
--- a/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs
+++ b/src/SlpModularCms.Modules.Hero/Repositories/HeroRepository.cs
@@ -22,6 +22,12 @@ public interface IHeroRepository
/// Images whose set is missing or does not match their focus, oldest first (tracked).
Task CountImagesAsync(CancellationToken cancellationToken);
+ /// All images, newest first, not tracked (the media library lists them).
+ Task> GetAllImagesReadOnlyAsync(CancellationToken cancellationToken);
+
+ /// All slides, not tracked (where each image is used).
+ Task> GetAllSlidesReadOnlyAsync(CancellationToken cancellationToken);
+
Task> GetImagesNeedingRenderAsync(CancellationToken cancellationToken);
/// Images with a complete set made before the full-frame preview existed (tracked).
@@ -76,6 +82,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository
public Task CountImagesAsync(CancellationToken cancellationToken) => context.HeroImages.CountAsync(cancellationToken);
+ public async Task> GetAllImagesReadOnlyAsync(CancellationToken cancellationToken)
+ => (await context.HeroImages.AsNoTracking().ToListAsync(cancellationToken)).OrderByDescending(i => i.CreatedAt).ToList();
+
+ public async Task> GetAllSlidesReadOnlyAsync(CancellationToken cancellationToken)
+ => await context.HeroSlides.AsNoTracking().ToListAsync(cancellationToken);
+
public async Task> GetImagesNeedingRenderAsync(CancellationToken cancellationToken)
=> (await context.HeroImages.ToListAsync(cancellationToken)).Where(HeroMapping.NeedsRender).OrderBy(i => i.CreatedAt).ToList();
diff --git a/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs b/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs
new file mode 100644
index 0000000..e386da1
--- /dev/null
+++ b/src/SlpModularCms.Modules.Hero/Services/HeroMediaUsageProvider.cs
@@ -0,0 +1,55 @@
+using SlpModularCms.Core.Media;
+using SlpModularCms.Core.Media.Library;
+using SlpModularCms.Modules.Hero.Data.Entities;
+using SlpModularCms.Modules.Hero.Repositories;
+
+namespace SlpModularCms.Modules.Hero.Services;
+
+///
+/// Tells the media library which hero images exist and where they are used (one use per slide, with its position in the
+/// hero). Read-only: nothing of the hero changes through this class.
+///
+public class HeroMediaUsageProvider(IHeroRepository repository) : IMediaUsageProvider
+{
+ public const string SlideKind = "slide";
+
+ public string Module => HeroMapping.Area;
+
+ public async Task> ListPhotosAsync(CancellationToken cancellationToken)
+ {
+ var images = await repository.GetAllImagesReadOnlyAsync(cancellationToken);
+ return images
+ .Select(i => new MediaPhoto(Module, i.Id, i.Bytes, i.Width, i.Height, i.CreatedAt, Thumbnail(i)))
+ .ToList();
+ }
+
+ public async Task> ListUsesAsync(IReadOnlyCollection photoIds, CancellationToken cancellationToken)
+ {
+ var wanted = photoIds.ToHashSet();
+ var slides = await repository.GetAllSlidesReadOnlyAsync(cancellationToken);
+
+ // The position of a slide is its place in its hero, in display order (1-based), also for slides that are off.
+ var uses = new List();
+ foreach (var hero in slides.GroupBy(s => s.HeroId))
+ {
+ var ordered = hero.OrderBy(s => s.SortOrder).ThenBy(s => s.Id).ToList();
+ for (var index = 0; index < ordered.Count; index++)
+ {
+ var slide = ordered[index];
+ if (wanted.Contains(slide.ImageId))
+ {
+ uses.Add(new MediaUse(Module, slide.ImageId, SlideKind, index + 1, slide.IsActive));
+ }
+ }
+ }
+
+ return uses;
+ }
+
+ /// The smallest published WebP of the set; null while the set is not cut yet.
+ private static string? Thumbnail(HeroImage image)
+ {
+ var pick = HeroMapping.Published(image).Where(v => v.Type == ImageFormat.WebP.MimeType()).OrderBy(v => v.Width).FirstOrDefault();
+ return pick is null || string.IsNullOrEmpty(image.SetHash) ? null : MediaPaths.Url(HeroMapping.Area, image.SetHash, pick.FileName);
+ }
+}