Mediabibliotheek en Hero: kopie-schakelaar in de deploy-workflow (test), kiezer enkel en meervoud, hint bij gedeelde uitsnede, plan uitsnede per gebruik
Continuous Integration / config-sls (pull_request) Successful in 8s
Continuous Integration / config-asf (pull_request) Successful in 6s
Continuous Integration / changes (pull_request) Successful in 13s
Continuous Integration / backend-build (pull_request) Successful in 1m53s
Continuous Integration / compile-sites (pull_request) Successful in 1m54s
Continuous Integration / vulnerability-scan (pull_request) Successful in 1m56s
Continuous Integration / frontend-prepare (pull_request) Successful in 2m24s
Continuous Integration / frontend-build (pull_request) Successful in 35s
Continuous Integration / frontend-lint (pull_request) Successful in 38s
Continuous Integration / backend-test (pull_request) Successful in 4m18s
Continuous Integration / frontend-test (pull_request) Successful in 2m35s
Continuous Integration / publish-sls-test (pull_request) Skipped
Continuous Integration / publish-sls-production (pull_request) Skipped
Continuous Integration / deploy-sls-test (pull_request) Skipped
Continuous Integration / deploy-sls-production (pull_request) Skipped
Continuous Integration / publish-asf-test (pull_request) Skipped
Continuous Integration / deploy-asf-test (pull_request) Skipped
Continuous Integration / smoke-sls-test (pull_request) Skipped
Continuous Integration / smoke-asf-test (pull_request) Skipped
Continuous Integration / config-sls (pull_request) Successful in 8s
Continuous Integration / config-asf (pull_request) Successful in 6s
Continuous Integration / changes (pull_request) Successful in 13s
Continuous Integration / backend-build (pull_request) Successful in 1m53s
Continuous Integration / compile-sites (pull_request) Successful in 1m54s
Continuous Integration / vulnerability-scan (pull_request) Successful in 1m56s
Continuous Integration / frontend-prepare (pull_request) Successful in 2m24s
Continuous Integration / frontend-build (pull_request) Successful in 35s
Continuous Integration / frontend-lint (pull_request) Successful in 38s
Continuous Integration / backend-test (pull_request) Successful in 4m18s
Continuous Integration / frontend-test (pull_request) Successful in 2m35s
Continuous Integration / publish-sls-test (pull_request) Skipped
Continuous Integration / publish-sls-production (pull_request) Skipped
Continuous Integration / deploy-sls-test (pull_request) Skipped
Continuous Integration / deploy-sls-production (pull_request) Skipped
Continuous Integration / publish-asf-test (pull_request) Skipped
Continuous Integration / deploy-asf-test (pull_request) Skipped
Continuous Integration / smoke-sls-test (pull_request) Skipped
Continuous Integration / smoke-asf-test (pull_request) Skipped
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -15,6 +15,11 @@ on:
|
||||
description: 'Deploy ASF test (Andrea Slop Fotografie)'
|
||||
type: boolean
|
||||
default: false
|
||||
media_library_copy:
|
||||
description: 'Media library copy on the TEST deploys (Media__Library__CopyOnStartup in shared/env): unchanged, on or off'
|
||||
type: choice
|
||||
options: [unchanged, 'on', 'off']
|
||||
default: unchanged
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
push:
|
||||
@@ -555,6 +560,7 @@ jobs:
|
||||
service_name: ${{ vars.SERVICE_NAME_TEST }}
|
||||
health_check_url: ${{ vars.HEALTH_CHECK_URL_TEST }}
|
||||
run_db_backup: false
|
||||
media_library_copy: ${{ github.event.inputs.media_library_copy || 'unchanged' }}
|
||||
|
||||
# Production deploy ONLY on an explicit workflow_dispatch run with deploy_sls_production checked, and
|
||||
# only when that run is on a release/* branch (same rule as ASF) — never reachable from a plain push
|
||||
@@ -682,6 +688,7 @@ jobs:
|
||||
service_name: ${{ vars.SERVICE_NAME_ASF_TEST }}
|
||||
health_check_url: ${{ vars.HEALTH_CHECK_URL_ASF_TEST }}
|
||||
run_db_backup: false
|
||||
media_library_copy: ${{ github.event.inputs.media_library_copy || 'unchanged' }}
|
||||
|
||||
# --- Smoke tests of the deployed compositions (anonymous requests, see scripts/smoke-site.sh) ---
|
||||
# The CI tests the master CMS; this is the check that the composition of each site that was just deployed to test
|
||||
|
||||
@@ -37,6 +37,11 @@ on:
|
||||
required: false
|
||||
type: string
|
||||
default: scp
|
||||
media_library_copy:
|
||||
description: 'unchanged | on | off: sets Media__Library__CopyOnStartup in shared/env before the restart. TEST only, never production.'
|
||||
required: false
|
||||
type: string
|
||||
default: unchanged
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
@@ -211,6 +216,37 @@ jobs:
|
||||
ln -sf \"../../shared/modules/\$name\" \"$RELEASE_DIR/\$name\"; \
|
||||
done"
|
||||
|
||||
# The media library copy switch (migration plan of the media library, decision 13): the application reads
|
||||
# Media__Library__CopyOnStartup from the host environment file shared/env (D-16). The deploy account can edit that file,
|
||||
# nobody else needs a shell on the host. Only this ONE key is touched (nothing else of the file is read or printed, the
|
||||
# file holds secrets), only on a test environment, and only with a value that is exactly on, off or unchanged.
|
||||
# `on` makes the next start copy the photos into the library's tables and verify the copy (log line
|
||||
# "Media library copy verified: N photos and M uses"); `off` removes the key again (the default is off).
|
||||
- name: Set the media library copy switch (test only)
|
||||
if: inputs.media_library_copy != 'unchanged'
|
||||
env:
|
||||
SSH_USER: ${{ secrets.PI_MAIN_USERNAME }}
|
||||
SSH_PASS: ${{ secrets.PI_MAIN_PASSWORD }}
|
||||
SSH_PORT: ${{ secrets.PI_MAIN_PORT }}
|
||||
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
||||
run: |
|
||||
MODE="${{ inputs.media_library_copy }}"
|
||||
if [ "${{ inputs.environment }}" != "test" ]; then
|
||||
echo "The media library copy switch is for the test environment only (environment: ${{ inputs.environment }})." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ "$MODE" != "on" ] && [ "$MODE" != "off" ]; then
|
||||
echo "media_library_copy must be unchanged, on or off (got: $MODE)." >&2
|
||||
exit 1
|
||||
fi
|
||||
ENV_FILE="${{ inputs.deploy_path }}/shared/env"
|
||||
if [ "$MODE" = "on" ]; then
|
||||
rssh "touch $ENV_FILE && sed -i '/^Media__Library__CopyOnStartup=/d' $ENV_FILE && echo 'Media__Library__CopyOnStartup=true' >> $ENV_FILE"
|
||||
else
|
||||
rssh "touch $ENV_FILE && sed -i '/^Media__Library__CopyOnStartup=/d' $ENV_FILE"
|
||||
fi
|
||||
echo "Media__Library__CopyOnStartup is now: $(rssh "grep '^Media__Library__CopyOnStartup=' $ENV_FILE || echo '(not set = off)'")"
|
||||
|
||||
# Atomic release switch (FR-06, D-27): `ln -sfn` replaces the `current` symlink target in a
|
||||
# single filesystem operation, so there is no moment where `current` points at a half-written
|
||||
# directory. The process is then restarted so it picks up the new assemblies — a running .NET
|
||||
@@ -227,6 +263,20 @@ jobs:
|
||||
"ln -sfn $RELEASE_DIR ${{ inputs.deploy_path }}/current && \
|
||||
systemctl --user restart ${{ inputs.service_name }}"
|
||||
|
||||
# After a restart with the copy on, show the verification line of the copy in this run's log (the journal of the user
|
||||
# service), so nobody needs a shell on the host to see "Media library copy verified: N photos and M uses".
|
||||
- name: Report the media library copy (test only)
|
||||
if: inputs.media_library_copy == 'on'
|
||||
env:
|
||||
SSH_USER: ${{ secrets.PI_MAIN_USERNAME }}
|
||||
SSH_PASS: ${{ secrets.PI_MAIN_PASSWORD }}
|
||||
SSH_PORT: ${{ secrets.PI_MAIN_PORT }}
|
||||
SSH_HOST: ${{ secrets.PI_MAIN_ADDRESS }}
|
||||
run: |
|
||||
sleep 20
|
||||
rssh "journalctl --user -u ${{ inputs.service_name }} --since '-10 min' --no-pager 2>/dev/null | grep -E 'Media library copy|media library copy' | tail -5 || true"
|
||||
echo "Look for 'Media library copy verified: N photos and M uses'. An error line means the copy was rolled back and nothing was copied."
|
||||
|
||||
# Verifies the restart actually produced a healthy process before this run is allowed to
|
||||
# report success. Retries absorb process-startup time, which is about 10 seconds normally but
|
||||
# 30 seconds or more when the host is busy (a migration step, two services restarting at once
|
||||
|
||||
@@ -67,3 +67,6 @@ Kept while Bryan is away (2026-11-17): no questions to him, a most probable assu
|
||||
| 36 | **Choose from the library in a hero slide** (built 2026-11-17 at Bryan's request, before the migration). | Each slide has "Choose from library" next to its photo: the shared `ImagePicker` lists the library photos of the modules that can be chosen (now the hero's own photos, also those in no slide, never the trash) and a new photo can be uploaded on the spot with the hero's own upload (same checks, limits and background processing). Choosing only sets the slide's existing image id (no data model change). A photo that is already in another slide can be chosen again: it is the same photo, so its **crop is shared by the slides that use it** (the crop belongs to the photo in the hero today; a crop per slide comes with the library's own use records). | A separate crop per slide now would need the use records of phase 2 (or a copy of the photo). | `features/hero/components/LibraryPickerDialog.tsx`, `HeroPage.tsx` |
|
||||
| 37 | **Removing from the trash for good** (Bryan, 2026-11-17). | `POST media-library/purge {ids}` (at most 100) or `{all:true}` (the server empties the whole trash in batches). Only photos that are in the trash and used nowhere are removed; the module checks it again and answers per photo (`purged`, `notInTrash`, `inUse`, `failed`). The original and the cut set go through `IMediaStore`; a file another photo still shares stays. The UI asks a clear confirmation that says it cannot be undone and names the number (and the size for the whole trash); "Empty the trash" is disabled when the trash is empty. No separate waiting period. | A short undo window for a purge: not built (the trash itself is the undo). | `MediaLibraryService.PurgeAsync`, `HeroImageService.PurgeAsync`, `PurgeDialog` |
|
||||
| 38 | **A new crop applies at once, without saving the hero** (Bryan, 2026-11-17; replaces Hero assumption 1 of 2026-11-16, which said a focus change only takes effect when the hero is saved). | The focus dialog's Apply sends the crop at once (`PUT hero/images/{id}/focus`); the server cuts the new variants in the background and the photo switches to them when they are complete, so what is live changes only then, without another Save. The photo shows "Wordt verwerkt…", a 0-100% bar and the percentage on itself (no spinner); the upload keeps its own display. The counter "x of y processed" counts the current upload batch only. | Back to applying only on Save: restore the focus edits kept locally in `HeroPage`. | `HeroImageService.SetFocusAsync`, `HeroPage.applyFocus`, `RecutThumbnail` |
|
||||
| 39 | **Crop PER USE, not per photo** (Bryan, 2026-11-17: a photo on two slides can have its own crop on each slide). | Decided, **not built yet**: it is too large and risky for the hero as it is today, because the cut sets, their set hash and the public output all hang on the photo (`HeroImage.SetHash`, `Variants`), so a crop per slide means a set per slide. The smallest safe step is built instead: a photo may be chosen for several slides, the crop is shared and the slide says so ("This photo is in more slides; the crop applies to all of them"). Design of the rest in `inception/application-design/per-use-crop.md`: it comes with phase 2 of the migration, because the library's own use records (`MediaUses.Crops`, `MediaUses.SetHash`) are where a crop per slide lives and the renderer then cuts a set per distinct crop. No public address or set hash changes until then. | An additive nullable focus on the slide (x, y, zoom) that overrides the photo's default focus, with a set per (photo, crop) and the public hero choosing the slide's set: possible without the library tables, but it rebuilds the renderer and the public mapping of the hero first; then phase 2 would have to move it again. | `HeroSlide`, `HeroImageService.RenderNextPendingAsync`, `HeroMapping` |
|
||||
| 40 | **Switching the copy on at the test hosts without access to the Pi** (Bryan, 2026-11-17: the copy may run on test). | The deploy workflow has a new input `media_library_copy` (unchanged, on, off; dispatch input of the CI workflow, passed to the SLS test and ASF test deploys). A step edits ONLY the key `Media__Library__CopyOnStartup` in `<deploy_path>/shared/env` over the deploy account's SSH access (refuses any environment that is not `test`, accepts only on, off or unchanged, never prints the file), before the service restart; after the restart a step shows the journal line `Media library copy verified: N photos and M uses`. `off` removes the key again. | Set the variable by hand in `shared/env` on the Pi (needs a shell there). | `.gitea/workflows/deploy-scp.yaml`, `continuous_integration.yaml` |
|
||||
| 41 | **The picker has a single and a multiple mode** (Bryan, 2026-11-17). | `ImagePicker` takes `mode="single"` (default, radio group, used by the hero slides) or `mode="multiple"` (checkboxes, several photos, several files per upload, ready for the gallery). Both use the same upload checks. | n/a | `ImagePicker.tsx` |
|
||||
|
||||
@@ -107,3 +107,13 @@ After that deploy, check in the log:
|
||||
5. Switch it off again (remove the variable, restart) when done: the copy can be repeated at any time; it is a mirror.
|
||||
|
||||
**Rollback:** remove the variable (the tables stay, unused), or drop the tables with the EF `Down` migration of the Media module; the Hero's own tables are never changed by the copy.
|
||||
|
||||
## Switching the copy on at the test hosts (no shell on the Pi needed)
|
||||
|
||||
The application reads `Media__Library__CopyOnStartup` from the host's `shared/env` (the file the service starts with). The deploy workflow can set exactly this one key, so nobody needs a shell on the Raspberry Pi:
|
||||
|
||||
1. Dispatch the CI workflow (`Continuous Integration`) on the branch with **deploy_sls_test** and/or **deploy_asf_test** checked and **media_library_copy = on**. Each test deploy then sets `Media__Library__CopyOnStartup=true` in its own `shared/env` before restarting the service, and the run log shows the line `Media library copy verified: N photos and M uses from hero` (or the error line that says the copy was rolled back).
|
||||
2. Check N and M against the hero (photos and slides) and the library screen.
|
||||
3. Dispatch once more with **media_library_copy = off** (and the deploy flags again): the key is removed and the next start does not copy. (`unchanged`, the default, never touches the file.)
|
||||
|
||||
The input is refused for any environment other than `test`, and only the three values are accepted; the workflow never prints the file (it holds secrets). Production is not reachable.
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# Crop per use (decision of Bryan, 2026-11-17)
|
||||
|
||||
A photo on two slides can have its own crop on each slide. Decided; **not built yet**. What exists today, why it waits, and the plan.
|
||||
|
||||
## Today
|
||||
|
||||
- The crop (default focus and the `wide` and `tall` overrides) is a property of the **photo** (`HeroImage`). The cut set (`SetHash`, `Variants`) belongs to the photo too, and so does the public output of the hero. A photo chosen for two slides therefore has one crop; the slide says so.
|
||||
- The set hash is `MediaPaths.SetHash(originalSha256, crops)`, so a set is already addressed by photo plus crops; the formula does not have to change.
|
||||
|
||||
## Why not now
|
||||
|
||||
A crop per slide means a set per (photo, crop). The renderer (`HeroRenderService`), the public hero mapping and the admin all assume one set per photo. Changing that on the hero's own tables and then moving it again when the library takes over (`MediaUses` already has `Crops` and `SetHash` per use) would be done twice and puts the public output at risk before the library is accepted.
|
||||
|
||||
## Plan (with phase 2 of the migration)
|
||||
|
||||
1. The library's `MediaUses` (one per slide) carry the crops and the set hash of that use (the copy already fills them from the photo).
|
||||
2. The hero slide gets its own crop (nullable focus overriding the photo's default; empty = the default), edited in the same focus dialog, applied at once like today.
|
||||
3. The renderer cuts one set per distinct (photo, crops); a set that two uses share (same crops) is cut once; a set nobody uses any more is cleaned up like a retired set.
|
||||
4. The public hero maps each slide to the set of its use. With no override the set is exactly today's set hash, so existing addresses and the golden files do not change.
|
||||
5. Tests: two slides with one photo and different crops give two sets and two addresses; with the same crop one set; no override gives today's hash.
|
||||
|
||||
## Smallest safe step built now
|
||||
|
||||
A photo may be chosen for several slides and the slide shows "This photo is in more slides; the crop applies to all of them" (assumption 36 and 39).
|
||||
@@ -1282,6 +1282,17 @@ describe('Choose a photo from the library for a slide', () => {
|
||||
expect(getSavedHeroRequests()[0].slides.map((x) => x.imageId)).toEqual(['10000000-0000-0000-0000-000000000002', '10000000-0000-0000-0000-000000000002']);
|
||||
});
|
||||
|
||||
it('tells that the crop is shared when the same photo is in more than one slide', async () => {
|
||||
const one = slide(1);
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [one, { ...slide(2), imageId: one.imageId, image: one.image }, slide(3)] });
|
||||
|
||||
await openPage();
|
||||
|
||||
expect(screen.getByTestId('hero-slide-0-shared-crop')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('hero-slide-1-shared-crop')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('hero-slide-2-shared-crop')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('uploads a new photo on the spot with the hero upload and puts it in the slide', async () => {
|
||||
setMockHero({ ...emptyHero(), id: 'h1', title: 'T', slides: [slide(1)] });
|
||||
server.use(http.get('*/media-library/photos', () => HttpResponse.json({ photos: [], modules: ['hero'] })));
|
||||
|
||||
@@ -574,6 +574,11 @@ function HeroEditor({ hero }: { hero: HeroAdminDto }) {
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setLibraryFor(index)} data-testid={`hero-slide-${index}-library`}>
|
||||
{t('hero.library.choose')}
|
||||
</Button>
|
||||
{watchedSlides.some((other, otherIndex) => otherIndex !== index && other?.imageId === field.imageId) && (
|
||||
<p className="max-w-28 text-xs text-muted-foreground" data-testid={`hero-slide-${index}-shared-crop`}>
|
||||
{t('hero.library.sharedCrop')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="min-w-[12rem] flex-1 space-y-2" role="group" aria-labelledby={`hero-slide-title-${field.id}`}>
|
||||
<h3 id={`hero-slide-title-${field.id}`} className="text-xs font-medium uppercase tracking-wide text-muted-foreground" data-testid={`hero-slide-${index}-title`}>
|
||||
|
||||
@@ -88,3 +88,57 @@ describe('ImagePicker', () => {
|
||||
expect(screen.getByTestId('picker-empty')).toHaveTextContent('nog geen foto');
|
||||
});
|
||||
});
|
||||
|
||||
function MultiHarness({ onUpload, initial = [] }: { onUpload?: (file: File) => Promise<PhotoItem>; initial?: string[] }) {
|
||||
const [values, setValues] = useState<string[]>(initial);
|
||||
return (
|
||||
<>
|
||||
<ImagePicker mode="multiple" items={items} values={values} onChangeMany={setValues} onUpload={onUpload} maxUploadBytes={10 * MB} label="Foto's van de galerij" />
|
||||
<output data-testid="chosen">{values.join(',')}</output>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
describe('ImagePicker in multiple mode', () => {
|
||||
it('chooses several photos with checkboxes, in the order chosen, and unchooses one', async () => {
|
||||
render(<MultiHarness />);
|
||||
|
||||
expect(screen.getByRole('group', { name: "Foto's van de galerij" })).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByRole('checkbox', { name: 'Foto B' }));
|
||||
await userEvent.click(screen.getByRole('checkbox', { name: 'Foto A' }));
|
||||
expect(screen.getByTestId('chosen')).toHaveTextContent('b,a');
|
||||
|
||||
await userEvent.click(screen.getByRole('checkbox', { name: 'Foto B' }));
|
||||
expect(screen.getByTestId('chosen')).toHaveTextContent('a');
|
||||
expect(screen.getByRole('checkbox', { name: 'Foto B' })).not.toBeChecked();
|
||||
});
|
||||
|
||||
it('uploads several files on the spot and adds them all to the choice', async () => {
|
||||
let n = 0;
|
||||
const upload = vi.fn().mockImplementation(async () => photo(`new${++n}`, `Nieuw ${n}`));
|
||||
render(<MultiHarness onUpload={upload} initial={['a']} />);
|
||||
|
||||
await userEvent.upload(screen.getByTestId('picker-file'), [file('1.jpg'), file('2.jpg')]);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('chosen')).toHaveTextContent('a,new1,new2'));
|
||||
expect(upload).toHaveBeenCalledTimes(2);
|
||||
expect(screen.getByTestId('picker-file')).toHaveAttribute('multiple');
|
||||
});
|
||||
|
||||
it('stops at a file the host would refuse and keeps what was chosen', async () => {
|
||||
const upload = vi.fn().mockResolvedValue(photo('new1', 'Nieuw'));
|
||||
render(<MultiHarness onUpload={upload} />);
|
||||
|
||||
await userEvent.upload(screen.getByTestId('picker-file'), [file('ok.jpg'), file('big.jpg', 'image/jpeg', 10 * MB + 1), file('later.jpg')]);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('picker-problem')).toHaveTextContent('maximaal 10 MB'));
|
||||
expect(upload).toHaveBeenCalledTimes(1);
|
||||
expect(screen.getByTestId('chosen')).toHaveTextContent('new1');
|
||||
});
|
||||
|
||||
it('single mode still takes one file only and has no multiple attribute', () => {
|
||||
render(<Harness onUpload={vi.fn()} />);
|
||||
|
||||
expect(screen.getByTestId('picker-file')).not.toHaveAttribute('multiple');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,12 +6,9 @@ import { cn } from '@/lib/utils';
|
||||
import { validateUpload } from '../lib/validateUpload';
|
||||
import type { PhotoItem } from './PhotoSelectionList';
|
||||
|
||||
interface ImagePickerProps {
|
||||
interface ImagePickerCommon {
|
||||
/** The photos of the library to choose from, newest first. */
|
||||
items: readonly PhotoItem[];
|
||||
/** The id of the chosen photo, or null. */
|
||||
value: string | null;
|
||||
onChange: (id: string) => void;
|
||||
/**
|
||||
* Uploads one file and answers with the photo as the library lists it. The module decides how (the hero uses its own
|
||||
* upload and background processing); the picker only shows the state and chooses the result. Without it there is no
|
||||
@@ -26,30 +23,71 @@ interface ImagePickerProps {
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** One photo: a radio group (the hero slides use this). */
|
||||
export interface ImagePickerSingleProps extends ImagePickerCommon {
|
||||
mode?: 'single';
|
||||
/** The id of the chosen photo, or null. */
|
||||
value: string | null;
|
||||
onChange: (id: string) => void;
|
||||
}
|
||||
|
||||
/** Several photos: checkboxes (ready for the gallery). Uploaded photos are added to the choice. */
|
||||
export interface ImagePickerMultipleProps extends ImagePickerCommon {
|
||||
mode: 'multiple';
|
||||
/** The ids of the chosen photos, in the order they were chosen. */
|
||||
values: readonly string[];
|
||||
onChangeMany: (ids: string[]) => void;
|
||||
}
|
||||
|
||||
export type ImagePickerProps = ImagePickerSingleProps | ImagePickerMultipleProps;
|
||||
|
||||
/**
|
||||
* "Choose an image or upload one": the photos of the library as a group of radio buttons (arrow keys move and choose)
|
||||
* and an upload button that adds the new photo to the library and chooses it at once. One component for every module that
|
||||
* needs an image. It holds no data of its own and calls nothing by itself: the module passes the list and the upload.
|
||||
* "Choose an image or upload one", one component for every module that needs an image. In <c>single</c> mode the library
|
||||
* photos are a radio group (arrow keys move and choose); in <c>multiple</c> mode they are checkboxes and several photos can
|
||||
* be chosen. An upload button adds the new photo to the library and chooses it at once. The picker holds no data of its own
|
||||
* and calls nothing by itself: the module passes the list and the upload.
|
||||
*/
|
||||
export function ImagePicker({ items, value, onChange, onUpload, maxUploadBytes, limitsText, label }: ImagePickerProps) {
|
||||
export function ImagePicker(props: ImagePickerProps) {
|
||||
const { items, onUpload, maxUploadBytes, limitsText, label } = props;
|
||||
const multiple = props.mode === 'multiple';
|
||||
const { t } = useTranslation();
|
||||
const groupName = useId();
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [problem, setProblem] = useState<string | null>(null);
|
||||
|
||||
const upload = async (file: File | undefined) => {
|
||||
if (!file || !onUpload || uploading) return;
|
||||
const refused = validateUpload(file, maxUploadBytes);
|
||||
if (refused) {
|
||||
setProblem(refused === 'tooLarge' ? t('media.picker.tooLarge', { max: Math.round(maxUploadBytes / (1024 * 1024)) }) : t('media.picker.notAnImage'));
|
||||
return;
|
||||
const chosen = (id: string) => (props.mode === 'multiple' ? props.values.includes(id) : props.value === id);
|
||||
|
||||
const toggle = (id: string) => {
|
||||
if (props.mode === 'multiple') {
|
||||
props.onChangeMany(props.values.includes(id) ? props.values.filter((v) => v !== id) : [...props.values, id]);
|
||||
} else {
|
||||
props.onChange(id);
|
||||
}
|
||||
};
|
||||
|
||||
const upload = async (files: FileList | null) => {
|
||||
const list = Array.from(files ?? []);
|
||||
if (list.length === 0 || !onUpload || uploading) return;
|
||||
setProblem(null);
|
||||
setUploading(true);
|
||||
let current = props.mode === 'multiple' ? [...props.values] : [];
|
||||
try {
|
||||
const photo = await onUpload(file);
|
||||
onChange(photo.id);
|
||||
for (const file of multiple ? list : list.slice(0, 1)) {
|
||||
const refused = validateUpload(file, maxUploadBytes);
|
||||
if (refused) {
|
||||
setProblem(refused === 'tooLarge' ? t('media.picker.tooLarge', { max: Math.round(maxUploadBytes / (1024 * 1024)) }) : t('media.picker.notAnImage'));
|
||||
break;
|
||||
}
|
||||
|
||||
const photo = await onUpload(file);
|
||||
if (props.mode === 'multiple') {
|
||||
current = [...current, photo.id];
|
||||
props.onChangeMany(current);
|
||||
} else {
|
||||
props.onChange(photo.id);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
setProblem(t('media.picker.failed'));
|
||||
} finally {
|
||||
@@ -66,10 +104,11 @@ export function ImagePicker({ items, value, onChange, onUpload, maxUploadBytes,
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple={multiple}
|
||||
className="sr-only"
|
||||
aria-label={t('media.picker.upload')}
|
||||
data-testid="picker-file"
|
||||
onChange={(event) => void upload(event.target.files?.[0])}
|
||||
onChange={(event) => void upload(event.target.files)}
|
||||
/>
|
||||
<Button type="button" variant="outline" disabled={uploading} onClick={() => fileInput.current?.click()} data-testid="picker-upload-button">
|
||||
<ImagePlus className="mr-2 size-4" aria-hidden="true" />
|
||||
@@ -88,15 +127,15 @@ export function ImagePicker({ items, value, onChange, onUpload, maxUploadBytes,
|
||||
{t('media.picker.empty')}
|
||||
</p>
|
||||
) : (
|
||||
<div role="radiogroup" aria-label={label} className="grid grid-cols-2 gap-3 sm:grid-cols-4" data-testid="picker-grid">
|
||||
<div role={multiple ? 'group' : 'radiogroup'} aria-label={label} className="grid grid-cols-2 gap-3 sm:grid-cols-4" data-testid="picker-grid">
|
||||
{items.map((item) => (
|
||||
<label key={item.id} className="relative block cursor-pointer" data-testid={`picker-item-${item.id}`}>
|
||||
<input
|
||||
type="radio"
|
||||
type={multiple ? 'checkbox' : 'radio'}
|
||||
name={groupName}
|
||||
value={item.id}
|
||||
checked={value === item.id}
|
||||
onChange={() => onChange(item.id)}
|
||||
checked={chosen(item.id)}
|
||||
onChange={() => toggle(item.id)}
|
||||
aria-label={item.name}
|
||||
className="peer sr-only"
|
||||
/>
|
||||
|
||||
@@ -647,7 +647,8 @@
|
||||
"choose": "Choose from library",
|
||||
"title": "Image for slide {{n}}",
|
||||
"description": "Choose a photo from the media library or upload a new one. A photo that is already in another slide is fine too: it is the same photo, so its crop is shared.",
|
||||
"group": "Image of slide {{n}}"
|
||||
"group": "Image of slide {{n}}",
|
||||
"sharedCrop": "This photo is in more slides; the crop applies to all of them."
|
||||
},
|
||||
"slides": {
|
||||
"title": "Images",
|
||||
|
||||
@@ -647,7 +647,8 @@
|
||||
"choose": "Kies uit bibliotheek",
|
||||
"title": "Afbeelding voor slide {{n}}",
|
||||
"description": "Kies een foto uit de mediabibliotheek of upload een nieuwe foto. Een foto die al in een andere slide staat mag ook: het is dezelfde foto, dus de uitsnede is gedeeld.",
|
||||
"group": "Afbeelding van slide {{n}}"
|
||||
"group": "Afbeelding van slide {{n}}",
|
||||
"sharedCrop": "Deze foto staat in meer slides; de uitsnede geldt voor allemaal."
|
||||
},
|
||||
"slides": {
|
||||
"title": "Afbeeldingen",
|
||||
|
||||
Reference in New Issue
Block a user