Mediabibliotheek fase A: gebruikscontract, opruimselectie en selectiecomponent #21
@@ -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 |
|
||||
|
||||
@@ -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 (
|
||||
<div
|
||||
role="toolbar"
|
||||
aria-label={t('media.bulk.label')}
|
||||
data-testid="bulk-action-bar"
|
||||
className="sticky bottom-0 z-10 flex flex-wrap items-center gap-3 rounded-md border bg-background px-4 py-2 shadow-md"
|
||||
>
|
||||
<span className="text-sm font-medium" data-testid="bulk-count">
|
||||
{t('media.bulk.selected', { count })}
|
||||
</span>
|
||||
{summary && <span className="text-sm text-muted-foreground">{summary}</span>}
|
||||
<div className="ml-auto flex flex-wrap items-center gap-2">
|
||||
<Button type="button" variant="ghost" size="sm" onClick={onClear} data-testid="bulk-clear">
|
||||
{t('media.bulk.clear')}
|
||||
</Button>
|
||||
{actions.map((action) => (
|
||||
<Button
|
||||
key={action.id}
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={action.destructive ? 'destructive' : 'outline'}
|
||||
disabled={action.disabled}
|
||||
onClick={action.run}
|
||||
data-testid={`bulk-action-${action.id}`}
|
||||
>
|
||||
{action.icon}
|
||||
{action.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<Selection>(emptySelection);
|
||||
return (
|
||||
<>
|
||||
<PhotoSelectionList items={items} selection={selection} onSelectionChange={setSelection} isDisabled={disabled} />
|
||||
<BulkActionBar count={selection.size} actions={[{ id: 'delete', label: 'Verwijderen', destructive: true, run: vi.fn() }]} onClear={() => 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(<Harness />);
|
||||
|
||||
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(<Harness />);
|
||||
|
||||
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(<Harness />);
|
||||
|
||||
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(<Harness />);
|
||||
|
||||
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(<Harness />);
|
||||
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(<Harness disabled={(item) => 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(<PhotoSelectionList items={[]} selection={emptySelection} onSelectionChange={vi.fn()} />);
|
||||
|
||||
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(<Harness />);
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<string | null>(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 (
|
||||
<p className="rounded-md border border-dashed p-6 text-center text-sm text-muted-foreground" data-testid="photo-list-empty">
|
||||
{t('media.list.empty')}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div data-testid="photo-selection-list">
|
||||
<div className="flex items-center gap-3 border-b px-2 py-2">
|
||||
<Checkbox
|
||||
aria-label={t('media.list.selectAll')}
|
||||
data-testid="photo-select-all"
|
||||
checked={state === 'all'}
|
||||
indeterminate={state === 'some'}
|
||||
disabled={selectableIds.length === 0}
|
||||
onChange={() => onSelectionChange(state === 'all' ? new Set() : selectAll(selectableIds))}
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground">{t('media.list.selectAll')}</span>
|
||||
<span className="sr-only" role="status" aria-live="polite" data-testid="photo-selection-status">
|
||||
{t('media.bulk.selected', { count: selection.size })}
|
||||
</span>
|
||||
</div>
|
||||
<ul className="divide-y" aria-label={t('media.list.label')}>
|
||||
{items.map((item) => {
|
||||
const disabled = isDisabled?.(item) ?? false;
|
||||
const labelId = `photo-${item.id}-label`;
|
||||
return (
|
||||
<li key={item.id} className="flex items-center gap-3 px-2 py-2" data-testid={`photo-row-${item.id}`}>
|
||||
<Checkbox
|
||||
aria-labelledby={labelId}
|
||||
data-testid={`photo-select-${item.id}`}
|
||||
checked={selection.has(item.id)}
|
||||
disabled={disabled}
|
||||
onChange={() => undefined}
|
||||
onClick={(event) => onItemClick(item.id, event.currentTarget.checked, event.shiftKey)}
|
||||
/>
|
||||
{item.thumbnailUrl ? (
|
||||
<img src={item.thumbnailUrl} alt="" loading="lazy" className="size-14 shrink-0 rounded object-cover" />
|
||||
) : (
|
||||
<span className="flex size-14 shrink-0 items-center justify-center rounded bg-muted text-xs text-muted-foreground">
|
||||
{t('media.list.noThumbnail')}
|
||||
</span>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<p id={labelId} className="truncate text-sm font-medium">
|
||||
{item.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{dateFormat.format(new Date(item.createdAt))} · {formatBytes(item.bytes, i18n.language)}
|
||||
</p>
|
||||
<p className="text-xs" data-testid={`photo-usage-${item.id}`}>
|
||||
{item.uses.length === 0 ? (
|
||||
<span className="text-muted-foreground">{t('media.use.none')}</span>
|
||||
) : (
|
||||
<span>{item.uses.map(usageLabel).join('; ')}</span>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<string>;
|
||||
|
||||
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';
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<MediaUse> 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<IReadOnlyList<MediaPhoto>> ListPhotosAsync(CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<MediaPhoto>>(photos);
|
||||
|
||||
public Task<IReadOnlyList<MediaUse>> ListUsesAsync(IReadOnlyCollection<Guid> photoIds, CancellationToken cancellationToken)
|
||||
=> Task.FromResult<IReadOnlyList<MediaUse>>(uses.Where(u => photoIds.Contains(u.PhotoId)).ToList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public static class CleanupSelection
|
||||
{
|
||||
public const int DefaultDays = 7;
|
||||
public const int MinDays = 1;
|
||||
public const int MaxDays = 365;
|
||||
|
||||
/// <summary>The days kept inside the slider range.</summary>
|
||||
public static int ClampDays(int days) => Math.Clamp(days, MinDays, MaxDays);
|
||||
|
||||
/// <summary>Items uploaded more than <paramref name="days"/> days before <paramref name="now"/>, newest first; with <paramref name="onlyUnused"/> only those no module uses.</summary>
|
||||
public static IReadOnlyList<MediaLibraryItem> Select(IEnumerable<MediaLibraryItem> 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();
|
||||
}
|
||||
|
||||
/// <summary>The bytes the given items take (originals; the variants are counted by the storage service).</summary>
|
||||
public static long Bytes(IEnumerable<MediaLibraryItem> items) => items.Sum(item => item.Photo.Bytes);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
/// <summary>The library over all modules that report photos: one list, newest first, each photo with its uses. Read-only.</summary>
|
||||
public interface IMediaLibraryService
|
||||
{
|
||||
/// <summary>All photos of all modules with their uses, newest first.</summary>
|
||||
Task<IReadOnlyList<MediaLibraryItem>> ListAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The modules that report photos (the screen warns about a module that is not in this list).</summary>
|
||||
IReadOnlyList<string> Modules { get; }
|
||||
}
|
||||
|
||||
public sealed class MediaLibraryService(IEnumerable<IMediaUsageProvider> providers) : IMediaLibraryService
|
||||
{
|
||||
private readonly IMediaUsageProvider[] _providers = providers.ToArray();
|
||||
|
||||
public IReadOnlyList<string> Modules => _providers.Select(p => p.Module).OrderBy(m => m, StringComparer.Ordinal).ToList();
|
||||
|
||||
public async Task<IReadOnlyList<MediaLibraryItem>> ListAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var items = new List<MediaLibraryItem>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
namespace SlpModularCms.Core.Media.Library;
|
||||
|
||||
/// <summary>A photo as the library shows it. The module that owns it fills it; the library only reads.</summary>
|
||||
/// <param name="Module">The module key (for example <c>hero</c>); with <paramref name="Id"/> it names the photo.</param>
|
||||
/// <param name="ThumbnailUrl">A public address of a small variant, or null while no variant exists yet.</param>
|
||||
public sealed record MediaPhoto(string Module, Guid Id, long Bytes, int Width, int Height, DateTimeOffset CreatedAt, string? ThumbnailUrl);
|
||||
|
||||
/// <summary>One place where a photo is used. The library shows it as "module, place kind, position" (for example "Hero, slide 3").</summary>
|
||||
/// <param name="PlaceKind">What kind of place (for example <c>slide</c>); the screen translates it.</param>
|
||||
/// <param name="Position">The 1-based position inside the place, or null when it has none.</param>
|
||||
/// <param name="Active">False when the place is switched off (still a use: the photo is kept).</param>
|
||||
public sealed record MediaUse(string Module, Guid PhotoId, string PlaceKind, int? Position, bool Active);
|
||||
|
||||
/// <summary>A photo with everything that uses it.</summary>
|
||||
public sealed record MediaLibraryItem(MediaPhoto Photo, IReadOnlyList<MediaUse> Uses)
|
||||
{
|
||||
public bool InUse => Uses.Count > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public interface IMediaUsageProvider
|
||||
{
|
||||
/// <summary>The module key, lower case, equal to its media area when it has one.</summary>
|
||||
string Module { get; }
|
||||
|
||||
/// <summary>The photos of this module, newest first.</summary>
|
||||
Task<IReadOnlyList<MediaPhoto>> ListPhotosAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Where the given photos are used (only photos of this module).</summary>
|
||||
Task<IReadOnlyList<MediaUse>> ListUsesAsync(IReadOnlyCollection<Guid> photoIds, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -22,6 +22,7 @@ public static class MediaServiceCollectionExtensions
|
||||
services.TryAddSingleton<MediaAreaRegistry>();
|
||||
services.TryAddSingleton<IMediaStore, FileSystemMediaStore>();
|
||||
services.TryAddSingleton<IMediaUploadGuard, MediaUploadGuard>();
|
||||
services.TryAddScoped<Library.IMediaLibraryService, Library.MediaLibraryService>();
|
||||
if (!services.Any(d => d.ImplementationType == typeof(ImageProcessorSelfTest)))
|
||||
{
|
||||
services.AddHostedService<ImageProcessorSelfTest>();
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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<IHeroService, HeroService>();
|
||||
services.AddScoped<IPublicHeroService, PublicHeroService>();
|
||||
services.AddScoped<IHeroImageService, HeroImageService>();
|
||||
services.AddScoped<IMediaUsageProvider, HeroMediaUsageProvider>();
|
||||
services.AddScoped<IHeroPageModel, HeroPageModel>();
|
||||
services.AddScoped<IHtmlPageTransform, HeroHtmlTransform>();
|
||||
services.AddScoped<ICmsDataBlockContributor, HeroDataContributor>();
|
||||
|
||||
@@ -22,6 +22,12 @@ public interface IHeroRepository
|
||||
/// <summary>Images whose set is missing or does not match their focus, oldest first (tracked).</summary>
|
||||
Task<int> CountImagesAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>All images, newest first, not tracked (the media library lists them).</summary>
|
||||
Task<IReadOnlyList<HeroImage>> GetAllImagesReadOnlyAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>All slides, not tracked (where each image is used).</summary>
|
||||
Task<IReadOnlyList<HeroSlide>> GetAllSlidesReadOnlyAsync(CancellationToken cancellationToken);
|
||||
|
||||
Task<IReadOnlyList<HeroImage>> GetImagesNeedingRenderAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Images with a complete set made before the full-frame preview existed (tracked).</summary>
|
||||
@@ -76,6 +82,12 @@ public class HeroRepository(HeroDbContext context) : IHeroRepository
|
||||
|
||||
public Task<int> CountImagesAsync(CancellationToken cancellationToken) => context.HeroImages.CountAsync(cancellationToken);
|
||||
|
||||
public async Task<IReadOnlyList<HeroImage>> GetAllImagesReadOnlyAsync(CancellationToken cancellationToken)
|
||||
=> (await context.HeroImages.AsNoTracking().ToListAsync(cancellationToken)).OrderByDescending(i => i.CreatedAt).ToList();
|
||||
|
||||
public async Task<IReadOnlyList<HeroSlide>> GetAllSlidesReadOnlyAsync(CancellationToken cancellationToken)
|
||||
=> await context.HeroSlides.AsNoTracking().ToListAsync(cancellationToken);
|
||||
|
||||
public async Task<IReadOnlyList<HeroImage>> GetImagesNeedingRenderAsync(CancellationToken cancellationToken)
|
||||
=> (await context.HeroImages.ToListAsync(cancellationToken)).Where(HeroMapping.NeedsRender).OrderBy(i => i.CreatedAt).ToList();
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public class HeroMediaUsageProvider(IHeroRepository repository) : IMediaUsageProvider
|
||||
{
|
||||
public const string SlideKind = "slide";
|
||||
|
||||
public string Module => HeroMapping.Area;
|
||||
|
||||
public async Task<IReadOnlyList<MediaPhoto>> 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<IReadOnlyList<MediaUse>> ListUsesAsync(IReadOnlyCollection<Guid> 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<MediaUse>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The smallest published WebP of the set; null while the set is not cut yet.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user