Compare commits

..
Author SHA1 Message Date
spark fd846ac68e Show the whole card copy, finish a fused angle, and open a tournament under its tile.
ci / rust (pull_request) Successful in 9m43s
ci / typescript (pull_request) Failing after 11m37s
The progress bar is the copy as a whole. A fused property angle can take a finish and be saved. A tournament's galleries open on the next row instead of below the list.
2026-10-21 05:12:53 +01:00
spark ff6d28064f Merge pull request 'Confirm a face without rescoring every other group first.' (#83) from task/faces-confirm into main
ci / rust (push) Successful in 12m7s
ci / typescript (push) Failing after 13m45s
Confirm a face without rescoring every other group first.
2026-10-21 04:56:43 +01:00
16 changed files with 563 additions and 62 deletions

No files matched your search

+20 -1
View File
@@ -226,6 +226,23 @@ export const t = {
chooseFolder: "Escolher pasta",
dropHint: "ou larga uma pasta aqui",
reading: (done: number, total: number) => `A ler ${done} de ${total}…`,
fusingAll: (done: number, total: number) => `A fundir ${done} de ${total} ângulos`,
savingAll: (done: number, total: number) => `A guardar ${done} de ${total}`,
resultHelp: "Cada imagem é o ângulo já fundido. Escolhe um acabamento e guarda o JPEG neste computador.",
save: "Guardar",
saveAll: "Guardar todos",
edit: "Editar",
exposure: "Exposição",
highlights: "Altas luzes",
shadows: "Sombras",
lookFailed: "Não apliquei o acabamento.",
savedFolder: "Os JPEG ficaram na pasta que escolheste.",
savedDownload: "Os JPEG foram descarregados.",
looks: {
natural: "Natural",
interior: "Interior claro",
brighter: "Mais luz",
},
noPhotos: "Não há fotografias nesta seleção. Um ficheiro XMP só acompanha o raw.",
support: (n: number) => (n === 1 ? "1 ficheiro de apoio (XMP e semelhantes) não é uma fotografia." : `${n} ficheiros de apoio (XMP e semelhantes) não são fotografias.`),
asideMore: (n: number) => `e mais ${n}`,
@@ -274,7 +291,9 @@ export const t = {
sidecars: "Levar WAV/XMP",
needSource: "Escolhe primeiro o cartão/pasta de origem.",
progress: (done: number, total: number, name: string) => `A processar ${done}/${total}… ${name}`,
remaining: (label: string) => `faltam cerca de ${label}`,
overall: (done: number, total: number, percent: number) => `${done} de ${total} · ${percent}%`,
general: "Geral",
remaining: (label: string) => (label.startsWith("menos") ? `falta ${label}` : `faltam cerca de ${label}`),
stop: "Parar",
stopping: "Pára depois do ficheiro que está a copiar.",
oldShellStop: "Esta versão da app de secretária ainda não consegue parar a meio. Atualiza-a; a cópia que já vai continua.",
+40 -6
View File
@@ -1,7 +1,7 @@
import { useEffect, useState, useSyncExternalStore } from "react";
import { t } from "../i18n.js";
import { desktopInvoke } from "../platform.js";
import { copyPace } from "./cardPace.js";
import { copyPace, overallPace } from "./cardPace.js";
import { cardJobList, dismissCard, enqueueCard, startQueued, stopCard, subscribeCardJobs, type CardJob, type CardResult, type CardSettings, type RawJpeg } from "./cardJobs.js";
import { SnapshotMenu } from "./SnapshotMenu.js";
@@ -232,13 +232,12 @@ function CardJobRow({ job, onRemove, onStop }: { job: CardJob; onRemove: () => v
{scan && <p className="mt-1 text-muted">{scan}</p>}
{job.status === "running" && job.progress && (
<>
<div className="mt-2 h-1.5 overflow-hidden bg-black">
<div className="h-full bg-accent" style={{ width: `${Math.round(pace.fraction * 100)}%` }} />
</div>
<p className="mt-1 text-muted">
{t.card.progress(job.progress.done, job.progress.total, job.progress.name)}
<p className="mt-2 text-ink">
{t.card.overall(job.progress.done, job.progress.total, Math.round(pace.fraction * 100))}
{pace.left ? ` · ${t.card.remaining(pace.left)}` : ""}
</p>
<Track fraction={pace.fraction} />
{job.progress.name && <p className="mt-1 truncate text-muted">{job.progress.name}</p>}
</>
)}
{job.error && <p className="mt-1 text-danger">{job.error}</p>}
@@ -247,6 +246,41 @@ function CardJobRow({ job, onRemove, onStop }: { job: CardJob; onRemove: () => v
);
}
/** The copy as a whole, under the library, including when the card window is closed. */
export function CardOverallStatus() {
const jobs = useCardJobs();
const [, setTick] = useState(0);
const running = jobs.some((job) => job.status === "running");
useEffect(() => {
if (!running) return;
const timer = setInterval(() => setTick((n) => n + 1), 1000);
return () => clearInterval(timer);
}, [running]);
const overall = overallPace(jobs, Date.now());
if (!overall) return null;
const name = jobs.find((job) => job.status === "running" && job.progress?.name)?.progress?.name;
return (
<div className="border-t border-line bg-panel px-3 py-2" role="status" aria-label={t.card.general}>
<p className="mb-1 flex flex-wrap items-baseline gap-x-2 text-[12px] text-ink">
<span className="font-semibold">{t.card.general}</span>
<span>{t.card.overall(overall.done, overall.total, Math.round(overall.fraction * 100))}</span>
{overall.left && <span className="text-muted">{t.card.remaining(overall.left)}</span>}
{name && <span className="min-w-0 truncate text-muted">{name}</span>}
</p>
<Track fraction={overall.fraction} />
</div>
);
}
function Track({ fraction }: { fraction: number }) {
const percent = Math.round(Math.max(0, Math.min(1, fraction)) * 100);
return (
<div className="mt-1 h-3 overflow-hidden bg-black" role="progressbar" aria-valuenow={percent} aria-valuemin={0} aria-valuemax={100}>
<div className="h-full bg-accent" style={{ width: `${percent}%` }} />
</div>
);
}
function JobResult({ result }: { result: CardResult }) {
const parts = [
result.moved ? t.card.result.moved(result.moved) : "",
+28 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { copyPace, formatRemaining, remainingMs } from "./cardPace.js";
import { copyPace, formatRemaining, overallPace, remainingMs } from "./cardPace.js";
describe("card copy pace", () => {
it("estimates the rest from the bytes already written", () => {
@@ -12,6 +12,33 @@ describe("card copy pace", () => {
expect(pace.left).toBe("1 min");
});
it("adds every card into one bar", () => {
const started = 1_000;
const now = started + 10_000;
const pace = overallPace(
[
{ status: "running", startedAt: started, progress: { done: 1, total: 4, bytesDone: 10, bytesTotal: 40 } },
{ status: "running", startedAt: started, progress: { done: 1, total: 4, bytesDone: 30, bytesTotal: 60 } },
{ status: "queued", startedAt: null, progress: null },
],
now,
);
expect(pace).toMatchObject({ done: 2, total: 8 });
expect(pace?.fraction).toBeCloseTo(0.4);
});
it("counts files when a card has no byte total", () => {
const started = 1_000;
const pace = overallPace(
[
{ status: "running", startedAt: started, progress: { done: 1, total: 4, bytesDone: 10, bytesTotal: 40 } },
{ status: "running", startedAt: started, progress: { done: 2, total: 4 } },
],
started + 10_000,
);
expect(pace?.fraction).toBeCloseTo(3 / 8);
});
it("waits for a little progress before guessing", () => {
expect(remainingMs(0, 10, 0, 5_000)).toBeNull();
expect(remainingMs(1, 10, 0, 100)).toBeNull();
+28
View File
@@ -16,6 +16,34 @@ export function formatRemaining(ms: number): string {
return `${hours} h ${rest} min`;
}
export interface PaceJob {
status: string;
startedAt: number | null;
progress: { done: number; total: number; bytesDone?: number; bytesTotal?: number } | null;
}
/** One bar for every card still copying: bytes when each job reports them, otherwise file counts. */
export function overallPace(jobs: readonly PaceJob[], now: number): { done: number; total: number; fraction: number; left: string | null } | null {
const running = jobs.filter((job) => job.status === "running" && job.progress && job.progress.total > 0 && job.startedAt !== null);
if (running.length === 0) return null;
const startedAt = Math.min(...running.map((job) => job.startedAt as number));
const done = running.reduce((sum, job) => sum + (job.progress?.done ?? 0), 0);
const total = running.reduce((sum, job) => sum + (job.progress?.total ?? 0), 0);
const byBytes = running.every((job) => (job.progress?.bytesTotal ?? 0) > 0);
const progress = {
done,
total,
...(byBytes
? {
bytesDone: running.reduce((sum, job) => sum + (job.progress?.bytesDone ?? 0), 0),
bytesTotal: running.reduce((sum, job) => sum + (job.progress?.bytesTotal ?? 0), 0),
}
: {}),
};
const pace = copyPace(progress, startedAt, now);
return { done, total, fraction: pace.fraction, left: pace.left };
}
export function copyPace(
progress: { done: number; total: number; bytesDone?: number; bytesTotal?: number } | null,
startedAt: number | null,
+2 -1
View File
@@ -18,7 +18,7 @@ import { IptcInfo } from "../library/IptcInfo.js";
import { useLibraryLive } from "../library/realtime.js";
import { useIngest } from "../library/ingest.js";
import { LocalFtpButton } from "../library/LocalFtp.js";
import { CardIngestButton } from "../library/CardIngest.js";
import { CardIngestButton, CardOverallStatus } from "../library/CardIngest.js";
import { AutopilotButton } from "../library/Autopilot.js";
import { SquadsButton } from "../library/Squads.js";
import { type PlayerPick, photoIdsOf, samePicks } from "../library/squadFilter.js";
@@ -672,6 +672,7 @@ export function LibraryPage() {
)}
</div>
)}
{desktop && <CardOverallStatus />}
<div className="border-t border-line bg-raised px-3 py-1.5 text-[11px] text-faint">{t.shortcuts}</div>
</div>
+5 -1
View File
@@ -1,7 +1,7 @@
import type { BracketFrame } from "@photoreport/metadata";
import { groupBrackets } from "@photoreport/metadata";
import type { ApiClient, Me, Organization } from "@photoreport/sdk";
import { render, screen } from "@testing-library/react";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { App } from "../App.js";
@@ -94,6 +94,10 @@ describe("real estate area", () => {
expect(await screen.findByText("1 ângulo")).toBeTruthy();
expect(screen.getByText("Ângulo 1 · 3 exposições")).toBeTruthy();
expect(await screen.findByRole("img", { name: "Ângulo 1 fundido" })).toBeTruthy();
await waitFor(() => expect(screen.getByRole("button", { name: "Guardar todos" }).hasAttribute("disabled")).toBe(false));
expect(screen.getByRole("button", { name: /^Guardar$/ })).toBeTruthy();
expect(screen.getByRole("button", { name: "Interior claro" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Editar" })).toBeTruthy();
expect(screen.getByText("1 fotografia fica de fora")).toBeTruthy();
expect(screen.getByText("solo.cr3 · 0 EV")).toBeTruthy();
expect(api.groupRealEstate).toHaveBeenCalledOnce();
+212 -9
View File
@@ -3,8 +3,11 @@ import { ApiError, hasRole, type RealEstateGrouping } from "@photoreport/sdk";
import { useEffect, useRef, useState } from "react";
import { useAuth } from "../auth.js";
import { t } from "../i18n.js";
import { applyFinish } from "../realestate/finish.js";
import { fuseBracket } from "../realestate/fuse.js";
import { LOOKS, finishValues, needsFinish, type LookId } from "../realestate/looks.js";
import { fillFromSidecar, pairKey, partitionBracketFiles, readBracketFile } from "../realestate/readFrame.js";
import { downloadBlob, jpegName, saveBlobs } from "../realestate/save.js";
import { PageHeader } from "./Shell.js";
const READ_AT_ONCE = 4;
@@ -131,7 +134,12 @@ export function RealEstatePage() {
</div>
<p className="mt-3 text-[13px] text-faint">{t.realEstate.dropHint}</p>
</div>
{busy && progress && <p className="mt-4 text-sm text-muted">{t.realEstate.reading(progress.done, progress.total)}</p>}
{busy && progress && (
<div className="mt-4">
<Track done={progress.done} total={progress.total} />
<p className="mt-1 text-sm text-muted">{t.realEstate.reading(progress.done, progress.total)}</p>
</div>
)}
{error && <p className="mt-4 text-sm text-danger">{error}</p>}
{support > 0 && <p className="mt-4 text-sm text-muted">{t.realEstate.support(support)}</p>}
{result && <Grouping frames={frames} files={files} result={result} />}
@@ -144,15 +152,89 @@ export function RealEstatePage() {
function Grouping({ frames, files, result }: { frames: BracketFrame[]; files: Map<string, File>; result: RealEstateGrouping }) {
const byId = new Map(frames.map((frame) => [frame.id, frame]));
const ready = useRef(new Set<number>());
const [fused, setFused] = useState(0);
const [blobs, setBlobs] = useState<Map<number, Blob>>(new Map());
const [saving, setSaving] = useState<{ done: number; total: number } | null>(null);
const [note, setNote] = useState<string | null>(null);
useEffect(() => {
ready.current = new Set();
setFused(0);
setBlobs(new Map());
setNote(null);
}, [result]);
const saveAll = async () => {
const chosen = result.stacks.flatMap((stack, index) => {
const blob = blobs.get(index);
if (!blob) return [];
const frame = byId.get(stack.frameIds[0] ?? "");
return [{ name: jpegName(frame?.fileName || `angulo-${index + 1}`), blob }];
});
if (chosen.length === 0) return;
setSaving({ done: 0, total: chosen.length });
setNote(null);
try {
const where = await saveBlobs(chosen, (done, total) => setSaving({ done, total }));
if (where === "folder") setNote(t.realEstate.savedFolder);
else if (where === "download") setNote(t.realEstate.savedDownload);
} catch {
setNote(t.unexpectedError);
} finally {
setSaving(null);
}
};
return (
<div className="mt-6 space-y-4">
<p className="text-sm text-ink">{t.realEstate.stacks(result.stacks.length)}</p>
{result.stacks.length > 0 && <p className="text-sm text-muted">{t.realEstate.resultHelp}</p>}
{result.stacks.length > 0 && fused < result.stacks.length && (
<div>
<Track done={fused} total={result.stacks.length} />
<p className="mt-1 text-sm text-muted">{t.realEstate.fusingAll(fused, result.stacks.length)}</p>
</div>
)}
{result.stacks.length > 0 && (
<button
type="button"
disabled={blobs.size < result.stacks.length || saving !== null}
onClick={() => void saveAll()}
className="h-8 border border-black bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong disabled:opacity-40"
>
{t.realEstate.saveAll}
</button>
)}
{saving && (
<div>
<Track done={saving.done} total={saving.total} />
<p className="mt-1 text-sm text-muted">{t.realEstate.savingAll(saving.done, saving.total)}</p>
</div>
)}
{note && <p className="text-sm text-muted">{note}</p>}
{result.stacks.length === 0 && <p className="text-sm text-muted">{t.realEstate.none}</p>}
<ul className="space-y-3">
{result.stacks.map((stack, index) => (
<li key={`${index}-${stack.frameIds[0] ?? ""}`} className="border border-line bg-panel">
<p className="border-b border-line px-3 py-2 text-[13px] font-semibold">{t.realEstate.angle(index + 1, stack.frameIds.length)}</p>
<AnglePreview index={index} ids={stack.frameIds} files={files} />
<AnglePreview
index={index}
ids={stack.frameIds}
files={files}
fileName={byId.get(stack.frameIds[0] ?? "")?.fileName || `angulo-${index + 1}`}
onReady={() => {
if (ready.current.has(index)) return;
ready.current.add(index);
setFused(ready.current.size);
}}
onBlob={(blob) =>
setBlobs((current) => {
const next = new Map(current);
next.set(index, blob);
return next;
})
}
/>
<ul className="px-3 py-2 text-[13px] text-muted">
{stack.frameIds.map((id) => (
<li key={id}>{line(byId.get(id), id)}</li>
@@ -177,9 +259,34 @@ function Grouping({ frames, files, result }: { frames: BracketFrame[]; files: Ma
);
}
function AnglePreview({ index, ids, files }: { index: number; ids: string[]; files: Map<string, File> }) {
function AnglePreview({
index,
ids,
files,
fileName,
onReady,
onBlob,
}: {
index: number;
ids: string[];
files: Map<string, File>;
fileName: string;
onReady: () => void;
onBlob: (blob: Blob) => void;
}) {
const [base, setBase] = useState<Blob | null>(null);
const [shown, setShown] = useState<Blob | null>(null);
const [url, setUrl] = useState<string | null>(null);
const [failed, setFailed] = useState(false);
const [look, setLook] = useState<LookId>("natural");
const [tweaks, setTweaks] = useState<Record<string, number> | null>(null);
const [editing, setEditing] = useState(false);
const [applying, setApplying] = useState(false);
const [lookError, setLookError] = useState(false);
const ready = useRef(onReady);
const report = useRef(onBlob);
ready.current = onReady;
report.current = onBlob;
const key = ids.join("\n");
useEffect(() => {
const stack = ids.map((id) => files.get(id)).filter((file): file is File => file instanceof File);
@@ -188,28 +295,124 @@ function AnglePreview({ index, ids, files }: { index: number; ids: string[]; fil
return;
}
let cancelled = false;
let objectUrl = "";
setUrl(null);
setBase(null);
setShown(null);
setFailed(false);
setLook("natural");
setTweaks(null);
fuseBracket(stack)
.then((blob) => {
if (cancelled) return;
objectUrl = URL.createObjectURL(blob);
setUrl(objectUrl);
setBase(blob);
setShown(blob);
})
.catch(() => {
if (!cancelled) setFailed(true);
});
return () => {
cancelled = true;
if (objectUrl) URL.revokeObjectURL(objectUrl);
};
// `key` is the stack. `files` is replaced as a whole when a new folder is read.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key, files]);
useEffect(() => {
if (!base && !failed) return;
ready.current();
}, [base, failed]);
useEffect(() => {
if (!base) return;
const values = finishValues(look, tweaks ?? {});
if (!needsFinish(values)) {
setShown(base);
setLookError(false);
setApplying(false);
return;
}
let cancelled = false;
setApplying(true);
applyFinish(base, look, tweaks ?? {})
.then((blob) => {
if (cancelled) return;
setShown(blob);
setLookError(false);
})
.catch(() => {
if (!cancelled) setLookError(true);
})
.finally(() => {
if (!cancelled) setApplying(false);
});
return () => {
cancelled = true;
};
}, [base, look, tweaks]);
useEffect(() => {
if (!shown) return;
report.current(shown);
const objectUrl = URL.createObjectURL(shown);
setUrl(objectUrl);
return () => URL.revokeObjectURL(objectUrl);
}, [shown]);
if (failed) return <p className="px-3 py-2 text-[13px] text-danger">{t.realEstate.fuseFailed}</p>;
if (!url) return <p className="px-3 py-2 text-[13px] text-muted">{t.realEstate.fusing}</p>;
return <img alt={t.realEstate.previewAlt(index + 1)} className="block w-full" src={url} />;
const controls = finishValues(look, tweaks ?? {});
const setControl = (id: string, value: number) => setTweaks({ ...finishValues(look, tweaks ?? {}), [id]: value });
return (
<>
<img alt={t.realEstate.previewAlt(index + 1)} className="block w-full" src={url} />
<div className="flex flex-wrap items-center gap-2 border-t border-line px-3 py-2">
{LOOKS.map((item) => (
<button
key={item.id}
type="button"
aria-pressed={look === item.id && tweaks === null}
disabled={applying}
onClick={() => {
setTweaks(null);
setLook(item.id);
}}
className={`h-7 border border-black px-2 text-[12px] ${look === item.id && tweaks === null ? "bg-accent text-white" : "bg-panel text-ink hover:bg-cell"}`}
>
{t.realEstate.looks[item.id]}
</button>
))}
<button type="button" aria-pressed={editing} onClick={() => setEditing((open) => !open)} className="h-7 border border-black bg-panel px-2 text-[12px] text-ink hover:bg-cell">
{t.realEstate.edit}
</button>
<button type="button" onClick={() => downloadBlob(jpegName(fileName), shown ?? base!)} className="h-7 border border-black bg-panel px-2 text-[12px] text-ink hover:bg-cell">
{t.realEstate.save}
</button>
{applying && <span className="text-[12px] text-muted">{t.realEstate.fusing}</span>}
{lookError && <span className="text-[12px] text-danger">{t.realEstate.lookFailed}</span>}
</div>
{editing && (
<div className="grid gap-2 border-t border-line px-3 py-2 text-[12px] text-muted">
<Slider label={t.realEstate.exposure} min={-2} max={2} step={0.05} value={controls["light.exposure"] ?? 0} onChange={(value) => setControl("light.exposure", value)} />
<Slider label={t.realEstate.highlights} min={-100} max={100} step={1} value={controls["light.highlights"] ?? 0} onChange={(value) => setControl("light.highlights", value)} />
<Slider label={t.realEstate.shadows} min={-100} max={100} step={1} value={controls["light.shadows"] ?? 0} onChange={(value) => setControl("light.shadows", value)} />
</div>
)}
</>
);
}
function Slider({ label, min, max, step, value, onChange }: { label: string; min: number; max: number; step: number; value: number; onChange: (value: number) => void }) {
return (
<label className="grid grid-cols-[7rem_1fr_3rem] items-center gap-2">
<span>{label}</span>
<input className="pr-range" type="range" min={min} max={max} step={step} value={value} aria-label={label} onChange={(event) => onChange(Number(event.target.value))} />
<span className="text-right font-mono text-ink">{Number.isInteger(value) ? value : value.toFixed(2)}</span>
</label>
);
}
function Track({ done, total }: { done: number; total: number }) {
const percent = total > 0 ? Math.round((done / total) * 100) : 0;
return (
<div className="h-3 overflow-hidden bg-black" role="progressbar" aria-valuenow={done} aria-valuemin={0} aria-valuemax={total}>
<div className="h-full bg-accent" style={{ width: `${percent}%` }} />
</div>
);
}
function line(frame: BracketFrame | undefined, id: string): string {
+31
View File
@@ -0,0 +1,31 @@
import { loadEngine } from "../develop/engine.js";
import { finishValues, needsFinish, type LookId } from "./looks.js";
/** The fused JPEG, then one develop pass when a finish or a slider asks for it. */
export async function applyFinish(jpeg: Blob, look: LookId, tweaks: Record<string, number>): Promise<Blob> {
const values = finishValues(look, tweaks);
if (!needsFinish(values)) return jpeg;
const engine = await loadEngine();
const photo = new engine.Photo(new Uint8Array(await jpeg.arrayBuffer()), 2048);
try {
const settings = engine.apply(engine.defaultSettings(), JSON.stringify({ command: "develop.set", params: { values } }));
photo.render(settings, photo.sourceWidth, photo.sourceHeight, false, false);
return rgbaToJpeg(photo.pixels(), photo.width, photo.height);
} finally {
photo.free();
}
}
function rgbaToJpeg(rgba: Uint8Array, width: number, height: number): Promise<Blob> {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
if (!context || width <= 0 || height <= 0) return Promise.reject(new Error("canvas"));
const pixels = new Uint8ClampedArray(rgba.byteLength);
pixels.set(rgba);
context.putImageData(new ImageData(pixels, width, height), 0, 0);
return new Promise((resolve, reject) => {
canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error("jpeg"))), "image/jpeg", 0.92);
});
}
+15
View File
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vitest";
import { finishValues, needsFinish } from "./looks.js";
describe("real estate finishes", () => {
it("keeps the merge when nothing was chosen", () => {
expect(needsFinish(finishValues("natural", {}))).toBe(false);
});
it("lets a slider replace one control of a preset", () => {
const values = finishValues("interior", { "light.shadows": 10 });
expect(values["light.shadows"]).toBe(10);
expect(values["light.highlights"]).toBe(-40);
expect(needsFinish(values)).toBe(true);
});
});
+20
View File
@@ -0,0 +1,20 @@
/** Finishes on top of the fused JPEG. Empty values keep the merge as the engine made it. */
export const LOOKS = [
{ id: "natural", values: {} },
{ id: "interior", values: { "light.exposure": 0.35, "light.highlights": -40, "light.shadows": 45, "light.whites": -15 } },
{ id: "brighter", values: { "light.exposure": 0.65, "light.highlights": -25, "light.shadows": 30 } },
] as const;
export type LookId = (typeof LOOKS)[number]["id"];
/** Preset first. A slider that moved replaces that one control. */
export function finishValues(look: LookId, tweaks: Record<string, number>): Record<string, number> {
const preset = LOOKS.find((item) => item.id === look)?.values ?? {};
const values: Record<string, number> = { ...preset };
for (const [id, value] of Object.entries(tweaks)) values[id] = value;
return values;
}
export function needsFinish(values: Record<string, number>): boolean {
return Object.values(values).some((value) => value !== 0);
}
+10
View File
@@ -0,0 +1,10 @@
import { describe, expect, it } from "vitest";
import { jpegName } from "./save.js";
describe("fused file names", () => {
it("names the jpeg from the raw", () => {
expect(jpegName("PSR10099.CR3")).toBe("PSR10099-fundido.jpg");
expect(jpegName("sala 1.cr3")).toBe("sala-1-fundido.jpg");
expect(jpegName("")).toBe("angulo-fundido.jpg");
});
});
+54
View File
@@ -0,0 +1,54 @@
/** A download name for one fused angle. */
export function jpegName(fileName: string): string {
const stem = fileName.replace(/\.[^.]+$/, "").replace(/[^\w.-]+/g, "-").replace(/^-+|-+$/g, "");
return `${stem || "angulo"}-fundido.jpg`;
}
export function downloadBlob(name: string, blob: Blob): void {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = name;
link.click();
URL.revokeObjectURL(url);
}
interface Writable {
write(data: Blob): Promise<void>;
close(): Promise<void>;
}
interface DirectoryPicker {
showDirectoryPicker?: () => Promise<{
getFileHandle(name: string, opts: { create: boolean }): Promise<{ createWritable(): Promise<Writable> }>;
}>;
}
/** All the angles into one folder when the browser allows it, otherwise one download each. */
export async function saveBlobs(
files: readonly { name: string; blob: Blob }[],
onStep?: (done: number, total: number) => void,
): Promise<"folder" | "download" | "cancel"> {
const picker = (window as DirectoryPicker).showDirectoryPicker;
if (!picker) {
for (const file of files) downloadBlob(file.name, file.blob);
onStep?.(files.length, files.length);
return "download";
}
try {
const dir = await picker();
for (let index = 0; index < files.length; index += 1) {
const file = files[index];
if (!file) continue;
const handle = await dir.getFileHandle(file.name, { create: true });
const writable = await handle.createWritable();
await writable.write(file.blob);
await writable.close();
onStep?.(index + 1, files.length);
}
return "folder";
} catch (err) {
if (err instanceof DOMException && err.name === "AbortError") return "cancel";
throw err;
}
}
+42 -43
View File
@@ -1,7 +1,8 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { cached, call, contents, fold, forget, initials, KIND_LABEL, prefetch, shortDay, Unauthorised, type Directory, type GalleryCard, type GalleryKind, type GallerySort, type PeopleList } from "./api";
import { eventLayout } from "./events";
import { Icon, Loading, PersonFace } from "./parts";
export type Tab = "galleries" | "people" | "teams" | "review";
@@ -60,6 +61,11 @@ export function Browse({
const [filtersOpen, setFiltersOpen] = useState(false);
/** A tournament's day or group opened from its tile. */
const [openGroup, setOpenGroup] = useState<string | null>(null);
const openPanel = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!openGroup) return;
openPanel.current?.scrollIntoView({ block: "nearest" });
}, [openGroup]);
/** "Juntar nomes": the clubs ticked to count as one (null: not joining). */
const [joining, setJoining] = useState<string[] | null>(null);
const [joinInto, setJoinInto] = useState("");
@@ -281,59 +287,52 @@ export function Browse({
</button>
);
/** A tournament's galleries by day or group (the folder above them): one tile each, opened in place. */
/** A tournament's galleries by day or group (the folder above them): one tile each, opened under that tile. */
const events = (items: GalleryCard[]) => {
const groups = new Map<string, GalleryCard[]>();
const loose: GalleryCard[] = [];
for (const g of items) {
if (!g.group) loose.push(g);
else groups.set(g.group, [...(groups.get(g.group) ?? []), g]);
}
for (const [name, gs] of groups)
if (gs.length < 2) {
loose.push(...gs);
groups.delete(name);
}
const open = openGroup ? groups.get(openGroup) : undefined;
const { groups, loose } = eventLayout(items);
return (
<>
{(groups.size > 0 || loose.length > 0) && (
{(groups.length > 0 || loose.length > 0) && (
<div className="arq-cards">
{[...groups].map(([name, gs]) => {
const cover = gs.find((g) => g.cover)?.cover;
const dates = gs.map((g) => g.startsAt).filter((d): d is string => !!d).sort();
{groups.map((group) => {
const cover = group.galleries.find((g) => g.cover)?.cover;
const dates = group.galleries.map((g) => g.startsAt).filter((d): d is string => !!d).sort();
const expanded = openGroup === group.name;
const photos = group.galleries.reduce((n, g) => n + g.photoCount, 0);
return (
<button key={name} type="button" className="arq-card arq-groupcard" aria-expanded={openGroup === name} onClick={() => setOpenGroup(openGroup === name ? null : name)}>
<span className="arq-date">{dates[0] ? shortDay.format(new Date(dates[0])) : "Sem data"}</span>
<span className="arq-thumb">
{cover && <img src={cover} alt="" loading="lazy" decoding="async" />}
<span className="arq-badge dark">{gs.length} galerias</span>
</span>
<span className="arq-event">
<strong>{name}</strong>
<span>
{gs.length} galerias · {gs.reduce((n, g) => n + g.photoCount, 0)} fotos
<Fragment key={group.name}>
<button type="button" className="arq-card arq-groupcard" aria-expanded={expanded} onClick={() => setOpenGroup(expanded ? null : group.name)}>
<span className="arq-date">{dates[0] ? shortDay.format(new Date(dates[0])) : "Sem data"}</span>
<span className="arq-thumb">
{cover && <img src={cover} alt="" loading="lazy" decoding="async" />}
<span className="arq-badge dark">{group.galleries.length} galerias</span>
</span>
</span>
</button>
<span className="arq-event">
<strong>{group.name}</strong>
<span>
{group.galleries.length} galerias · {photos} fotos
</span>
</span>
</button>
{expanded && (
<div className="arq-group-open" ref={openPanel}>
<div className="arq-kind-head">
<h3>{group.name}</h3>
<span className="arq-muted">{group.galleries.length} galerias</span>
<span className="arq-grow" />
<button type="button" className="arq-link" onClick={() => setOpenGroup(null)}>
Fechar
</button>
</div>
<div className="arq-cards">{group.galleries.map(card)}</div>
</div>
)}
</Fragment>
);
})}
{loose.map(card)}
</div>
)}
{open && (
<div className="arq-group-open">
<div className="arq-kind-head">
<h3>{openGroup}</h3>
<span className="arq-muted">{open.length} galerias</span>
<span className="arq-grow" />
<button type="button" className="arq-link" onClick={() => setOpenGroup(null)}>
Fechar
</button>
</div>
<div className="arq-cards">{open.map(card)}</div>
</div>
)}
</>
);
};
@@ -2292,6 +2292,7 @@
box-shadow: 0 0 0 2px var(--ink), 5px 5px 0 0 var(--card), 5px 5px 0 2px var(--ink);
}
.arq-group-open {
grid-column: 1 / -1;
display: flex;
flex-direction: column;
gap: 12px;
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import type { GalleryCard } from "./api";
import { eventLayout } from "./events";
function card(id: string, group: string | null): GalleryCard {
return { id, title: id, group, home: null, away: null, competition: null, startsAt: null, photoCount: 10, cover: null };
}
describe("tournament tiles", () => {
it("keeps a tournament's galleries on that tile", () => {
const { groups, loose } = eventLayout([
card("a", "JORNADA 8"),
card("b", "JORNADA 8"),
card("c", "PG COMUNICAÇÃO"),
card("d", "PG COMUNICAÇÃO"),
card("e", "PG COMUNICAÇÃO"),
card("solo", null),
card("one", "Só um dia"),
]);
expect(groups.map((group) => [group.name, group.galleries.map((gallery) => gallery.id)])).toEqual([
["JORNADA 8", ["a", "b"]],
["PG COMUNICAÇÃO", ["c", "d", "e"]],
]);
expect(loose.map((gallery) => gallery.id)).toEqual(["solo", "one"]);
});
});
+29
View File
@@ -0,0 +1,29 @@
import type { GalleryCard } from "./api";
export interface EventGroup {
name: string;
galleries: GalleryCard[];
}
/**
* Tournaments are one tile per folder. A folder with a single gallery is just that gallery: clicking it opens
* the gallery. A folder with several galleries opens under its own tile, not after the whole list.
*/
export function eventLayout(items: readonly GalleryCard[]): { groups: EventGroup[]; loose: GalleryCard[] } {
const byName = new Map<string, GalleryCard[]>();
const loose: GalleryCard[] = [];
for (const item of items) {
const name = item.group?.trim() ?? "";
if (!name) {
loose.push(item);
continue;
}
byName.set(name, [...(byName.get(name) ?? []), item]);
}
const groups: EventGroup[] = [];
for (const [name, galleries] of byName) {
if (galleries.length < 2) loose.push(...galleries);
else groups.push({ name, galleries });
}
return { groups, loose };
}