Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fd846ac68e | ||
|
|
ff6d28064f | ||
|
|
9ced09803f | ||
|
|
5d6848b712 | ||
|
|
9f9f5715af | ||
|
|
6c17f98ed8 | ||
|
|
1998189109 |
No files matched your search
@@ -757,25 +757,51 @@ export class FaceService {
|
||||
update: { ...(who.club !== undefined && { club: who.club }), ...(who.number !== undefined && { number: who.number }) },
|
||||
});
|
||||
}
|
||||
if (person.model && person.model !== group.model) throw new FaceRejected("model_mismatch");
|
||||
// A group from another embedding model is still named. recomputePerson keeps the centroid on the
|
||||
// person's own model, so the vectors are not mixed and Confirmar is not refused.
|
||||
await db.faceGroup.update({ where: { id: groupId }, data: { personId: person.id, suggestedPersonId: null, suggestionScore: null, ignoredAt: null, confirmedById: userId } });
|
||||
person = await this.recomputePerson(person.id);
|
||||
const photoIds = (await db.face.findMany({ where: { groupId }, select: { photoId: true } })).map((f) => f.photoId);
|
||||
await this.nameConfirmedPhotos([...new Set(photoIds)]);
|
||||
await this.refreshSuggestions(group.eventId);
|
||||
// The same person suggested in other games: their cards are read again with this face included, so confirming
|
||||
// one pulls the rest together instead of leaving a separate guess in every event.
|
||||
// Same-event cards of this person collapse before the answer. Rescoring every other open face (this match
|
||||
// and up to 25 others) used to run inside the request, so Confirmar sat there until the proxy gave up.
|
||||
await this.joinSamePerson(group.eventId);
|
||||
const others = await db.faceGroup.findMany({
|
||||
where: { suggestedPersonId: person.id, personId: null, ignoredAt: null, eventId: { not: group.eventId } },
|
||||
select: { eventId: true },
|
||||
distinct: ["eventId"],
|
||||
take: 25,
|
||||
});
|
||||
for (const other of others) await this.refreshSuggestions(other.eventId);
|
||||
await this.scheduleRefresh([group.eventId, ...others.map((other) => other.eventId)]);
|
||||
this.deps.broadcaster.library(group.organizationId, { type: "faces.updated", eventId: group.eventId });
|
||||
return person;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rescore open faces after the name is saved. The click must not wait on it: a match with hundreds of
|
||||
* unnamed faces was holding the request until the proxy gave up, and the button looked dead.
|
||||
* Tests share one database, so there the refresh finishes before the response (a late write would land in the next test).
|
||||
*/
|
||||
private async scheduleRefresh(eventIds: string[]): Promise<void> {
|
||||
const ids = [...new Set(eventIds)];
|
||||
const inline = process.env.NODE_ENV === "test";
|
||||
const run = async () => {
|
||||
for (const eventId of ids) {
|
||||
try {
|
||||
await this.refreshSuggestions(eventId);
|
||||
} catch (err) {
|
||||
if (inline) throw err;
|
||||
this.deps.log.warn({ eventId, err: err instanceof Error ? err.message : String(err) }, "faces: suggestion refresh failed");
|
||||
}
|
||||
}
|
||||
};
|
||||
if (inline) {
|
||||
await run();
|
||||
return;
|
||||
}
|
||||
void run();
|
||||
}
|
||||
|
||||
/** A name typed as a code (\v7\) becomes the name in the organization's code list. */
|
||||
private async expandName(organizationId: string, typed: string): Promise<string> {
|
||||
if (!typed.includes("\\")) return typed.trim();
|
||||
@@ -788,7 +814,9 @@ export class FaceService {
|
||||
const { db } = this.deps;
|
||||
const person = await db.person.findUniqueOrThrow({ where: { id: personId } });
|
||||
const groups = await db.faceGroup.findMany({ where: { personId } });
|
||||
const model = groups[0]?.model ?? person.model ?? null;
|
||||
// The person's model wins. A group confirmed from another model is named, but must not take over the
|
||||
// centroid: faceGroup.findMany has no order, so the first row is not a stable choice.
|
||||
const model = person.model ?? groups[0]?.model ?? null;
|
||||
if (person.recognitionOffAt) return db.person.update({ where: { id: personId }, data: { centroid: [], faceCount: groups.reduce((n, g) => n + g.size, 0) } });
|
||||
const parts = groups.filter((g) => g.model === model).map((g) => ({ mean: g.centroid, count: g.size }));
|
||||
if (person.referenceEmbedding.length && person.model === model) parts.push({ mean: person.referenceEmbedding, count: 3 });
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { groupBrackets } from "@photoreport/metadata";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { frameClock, groupFrames } from "./clock.js";
|
||||
|
||||
describe("camera clock", () => {
|
||||
it("keeps a wall time with no timezone, and an offset when the file has one", () => {
|
||||
expect(frameClock("2026-10-21T10:00:00")).toBe("2026-10-21T10:00:00");
|
||||
expect(frameClock("2026-10-21T10:00:00.200")).toBe("2026-10-21T10:00:00.200");
|
||||
expect(frameClock("2026-10-21T10:00:00+01:00")).toBe("2026-10-21T10:00:00+01:00");
|
||||
expect(frameClock("2026-10-21T10:00:00Z")).toBe("2026-10-21T10:00:00Z");
|
||||
});
|
||||
|
||||
it("drops a date that is not a time instead of rejecting the folder", () => {
|
||||
const frames = groupFrames({
|
||||
frames: [
|
||||
{ id: "a", capturedAt: "2026-10-21T10:00:00", exposureBias: -2 },
|
||||
{ id: "b", capturedAt: "not a date", exposureBias: 0 },
|
||||
{ id: "c", exposureBias: 2 },
|
||||
],
|
||||
});
|
||||
expect(frames.map((frame) => frame.capturedAt)).toEqual(["2026-10-21T10:00:00", null, null]);
|
||||
});
|
||||
|
||||
it("groups a Canon bracket whose clock has no timezone", () => {
|
||||
const frames = groupFrames({
|
||||
frames: [
|
||||
{ id: "a", fileName: "a.CR3", capturedAt: "2026-10-21T10:00:00", cameraSerial: "body", focalLength: 16, aperture: 8, iso: 100, exposureBias: -2, exposureTime: 0.01 },
|
||||
{ id: "b", fileName: "b.CR3", capturedAt: "2026-10-21T10:00:00.200", cameraSerial: "body", focalLength: 16, aperture: 8, iso: 100, exposureBias: 0, exposureTime: 0.04 },
|
||||
{ id: "c", fileName: "c.CR3", capturedAt: "2026-10-21T10:00:00.400", cameraSerial: "body", focalLength: 16, aperture: 8, iso: 100, exposureBias: 2, exposureTime: 0.1 },
|
||||
],
|
||||
});
|
||||
expect(groupBrackets(frames)).toEqual({ stacks: [{ frameIds: ["a", "b", "c"] }], aside: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { BracketFrame } from "@photoreport/metadata";
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* A camera clock. Canon (and most bodies) store wall time with no timezone, so `2026-10-21T10:00:00`
|
||||
* is a real capture time. The offset is kept when the file recorded one. Anything else is dropped:
|
||||
* one bad sidecar must not reject the whole folder.
|
||||
*/
|
||||
const cameraInstant = z.iso.datetime({ local: true, offset: true });
|
||||
|
||||
export function frameClock(value: string | null | undefined): string | null {
|
||||
if (value == null) return null;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed === "" || trimmed.length > 64) return null;
|
||||
return cameraInstant.safeParse(trimmed).success ? trimmed : null;
|
||||
}
|
||||
|
||||
const optionalText = z.string().trim().max(300).nullable().optional();
|
||||
const optionalNumber = z.number().nullable().optional();
|
||||
|
||||
const FrameBody = z.object({
|
||||
id: z.string().trim().min(1).max(2000),
|
||||
fileName: optionalText,
|
||||
capturedAt: z.string().nullable().optional().transform((value) => frameClock(value)),
|
||||
cameraSerial: optionalText,
|
||||
cameraMake: optionalText,
|
||||
cameraModel: optionalText,
|
||||
focalLength: optionalNumber,
|
||||
aperture: optionalNumber,
|
||||
iso: optionalNumber,
|
||||
width: optionalNumber,
|
||||
height: optionalNumber,
|
||||
exposureBias: optionalNumber,
|
||||
exposureTime: optionalNumber,
|
||||
});
|
||||
|
||||
const GroupBody = z.object({ frames: z.array(FrameBody).max(4000) });
|
||||
|
||||
function finite(value: number | null | undefined): number | null {
|
||||
if (value == null || !Number.isFinite(value)) return null;
|
||||
return value;
|
||||
}
|
||||
|
||||
/** The exposure metadata of one shoot. A date the camera did not write as a time becomes empty. */
|
||||
export function groupFrames(body: unknown): BracketFrame[] {
|
||||
return GroupBody.parse(body).frames.map((frame) => ({
|
||||
id: frame.id,
|
||||
fileName: frame.fileName ?? null,
|
||||
capturedAt: frame.capturedAt ?? null,
|
||||
cameraSerial: frame.cameraSerial ?? null,
|
||||
cameraMake: frame.cameraMake ?? null,
|
||||
cameraModel: frame.cameraModel ?? null,
|
||||
focalLength: finite(frame.focalLength),
|
||||
aperture: finite(frame.aperture),
|
||||
iso: finite(frame.iso),
|
||||
width: finite(frame.width),
|
||||
height: finite(frame.height),
|
||||
exposureBias: finite(frame.exposureBias),
|
||||
exposureTime: finite(frame.exposureTime),
|
||||
}));
|
||||
}
|
||||
@@ -1,35 +1,15 @@
|
||||
import { groupBrackets, type BracketFrame } from "@photoreport/metadata";
|
||||
import { groupBrackets } from "@photoreport/metadata";
|
||||
import type { FastifyInstance } from "fastify";
|
||||
import { z } from "zod";
|
||||
import { requireAuth, requireMembership } from "../auth/guard.js";
|
||||
import type { SessionService } from "../auth/sessions.js";
|
||||
import type { Db } from "../db.js";
|
||||
import { conflict } from "../lib/errors.js";
|
||||
import { groupFrames } from "./clock.js";
|
||||
|
||||
const OrgParams = z.object({ orgId: z.uuid() });
|
||||
const SettingBody = z.object({ enabled: z.boolean() });
|
||||
|
||||
const optionalText = z.string().trim().max(300).nullable().optional();
|
||||
const optionalNumber = z.number().nullable().optional();
|
||||
|
||||
const FrameBody = z.object({
|
||||
id: z.string().trim().min(1).max(400),
|
||||
fileName: optionalText,
|
||||
capturedAt: z.iso.datetime().nullable().optional(),
|
||||
cameraSerial: optionalText,
|
||||
cameraMake: optionalText,
|
||||
cameraModel: optionalText,
|
||||
focalLength: optionalNumber,
|
||||
aperture: optionalNumber,
|
||||
iso: optionalNumber,
|
||||
width: optionalNumber,
|
||||
height: optionalNumber,
|
||||
exposureBias: optionalNumber,
|
||||
exposureTime: optionalNumber,
|
||||
});
|
||||
|
||||
const GroupBody = z.object({ frames: z.array(FrameBody).max(4000) });
|
||||
|
||||
/**
|
||||
* The interior-bracket area. It never touches sports ingest: files stay on the photographer's
|
||||
* computer and only the exposure metadata is sent, to be grouped. Merging the frames is later.
|
||||
@@ -60,30 +40,6 @@ export async function registerRealEstateRoutes(app: FastifyInstance, deps: { db:
|
||||
await requireMembership(db, req, orgId, "PHOTOGRAPHER");
|
||||
const org = await db.organization.findUniqueOrThrow({ where: { id: orgId }, select: { realEstateEnabled: true } });
|
||||
if (!org.realEstateEnabled) throw conflict("real_estate_disabled");
|
||||
const body = GroupBody.parse(req.body);
|
||||
return groupBrackets(body.frames.map(finiteFrame));
|
||||
return groupBrackets(groupFrames(req.body));
|
||||
});
|
||||
}
|
||||
|
||||
function finite(value: number | null | undefined): number | null {
|
||||
if (value == null || !Number.isFinite(value)) return null;
|
||||
return value;
|
||||
}
|
||||
|
||||
function finiteFrame(frame: z.infer<typeof FrameBody>): BracketFrame {
|
||||
return {
|
||||
id: frame.id,
|
||||
fileName: frame.fileName ?? null,
|
||||
capturedAt: frame.capturedAt ?? null,
|
||||
cameraSerial: frame.cameraSerial ?? null,
|
||||
cameraMake: frame.cameraMake ?? null,
|
||||
cameraModel: frame.cameraModel ?? null,
|
||||
focalLength: finite(frame.focalLength),
|
||||
aperture: finite(frame.aperture),
|
||||
iso: finite(frame.iso),
|
||||
width: finite(frame.width),
|
||||
height: finite(frame.height),
|
||||
exposureBias: finite(frame.exposureBias),
|
||||
exposureTime: finite(frame.exposureTime),
|
||||
};
|
||||
}
|
||||
@@ -79,5 +79,21 @@ describe("real estate", () => {
|
||||
});
|
||||
expect(grouped.statusCode).toBe(200);
|
||||
expect(grouped.json()).toEqual({ stacks: [{ frameIds: ["a", "b", "c"] }], aside: ["solo"] });
|
||||
|
||||
const localClock = await ctx.app.inject({
|
||||
method: "POST",
|
||||
url: `${url}/groups`,
|
||||
headers: bearer(photographer.body.accessToken),
|
||||
payload: {
|
||||
frames: [
|
||||
{ ...shot("a", -2, 0), id: "local-a", capturedAt: "2026-10-21T10:00:00" },
|
||||
{ ...shot("b", 0, 200), id: "local-b", capturedAt: "2026-10-21T10:00:00.200" },
|
||||
{ ...shot("c", 2, 400), id: "local-c", capturedAt: "2026-10-21T10:00:00.400" },
|
||||
{ id: "bad", fileName: "nota.XMP", capturedAt: "not a date", cameraSerial: "other", exposureBias: 0 },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(localClock.statusCode).toBe(200);
|
||||
expect(localClock.json()).toEqual({ stacks: [{ frameIds: ["local-a", "local-b", "local-c"] }], aside: ["bad"] });
|
||||
});
|
||||
});
|
||||
@@ -204,6 +204,9 @@ export const t = {
|
||||
enable: "Ligar",
|
||||
disable: "Desligar",
|
||||
enabled: "Ligado",
|
||||
confirm: "Confirmar",
|
||||
confirming: "A confirmar…",
|
||||
confirmFailed: "Não confirmei. Tenta outra vez.",
|
||||
},
|
||||
realEstate: {
|
||||
nav: "Imobiliário",
|
||||
@@ -223,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}`,
|
||||
@@ -239,6 +259,59 @@ export const t = {
|
||||
real_estate_disabled: "O imobiliário está desligado nesta organização.",
|
||||
} as Record<string, string>,
|
||||
},
|
||||
snapshots: {
|
||||
button: "Presets",
|
||||
name: "Nome do preset",
|
||||
save: "Guardar",
|
||||
manage: "Gerir…",
|
||||
empty: "Ainda não há presets.",
|
||||
remove: "Apagar",
|
||||
},
|
||||
card: {
|
||||
title: "Importar cartão",
|
||||
open: "Cartão…",
|
||||
progressButton: (done: number, total: number) => `Cartão ${done}/${total}`,
|
||||
openTitle: "Descarregar um cartão para uma pasta datada (copiar ou mover)",
|
||||
close: "Fechar",
|
||||
closeKeeps: "Fechar não pára a cópia.",
|
||||
intro: "Copia (ou move) as fotos de um cartão para uma pasta datada neste computador. Não envia nada para o servidor.",
|
||||
source: "Origem (cartão/pasta)",
|
||||
sourcePlaceholder: "Escolhe o cartão…",
|
||||
add: "Adicionar cartão",
|
||||
dest: "Destino",
|
||||
template: "Subpastas (template)",
|
||||
templateHelp: "Variáveis: {iptcyear4} {iptcmonth0} {iptcday0} {type} {ext} — data pela hora da fotografia, ou pela hora do ficheiro se não houver.",
|
||||
rawJpeg: "RAW + JPEG",
|
||||
both: "RAW e JPEG",
|
||||
rawOnly: "Só RAW",
|
||||
jpegOnly: "Só JPEG",
|
||||
move: "Mover (apaga do cartão depois de verificar)",
|
||||
moveWarn: "Mover apaga os originais do cartão (só depois de a cópia ser verificada por tamanho e checksum).",
|
||||
overwrite: "Sobrescrever existentes",
|
||||
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}`,
|
||||
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.",
|
||||
remove: "Tirar",
|
||||
stopped: "Parado",
|
||||
copy: "Copiar",
|
||||
moveAction: "Mover",
|
||||
scan: (raw: number, jpeg: number, other: number, size: string) =>
|
||||
other > 0 ? `${raw} RAW · ${jpeg} JPEG · ${other} outras · ${size}` : `${raw} RAW · ${jpeg} JPEG · ${size}`,
|
||||
result: {
|
||||
moved: (n: number) => `${n} movidas`,
|
||||
copied: (n: number) => `${n} copiadas`,
|
||||
skipped: (n: number) => `${n} ignoradas`,
|
||||
failed: (n: number) => `${n} falhadas`,
|
||||
empty: "Nada a fazer.",
|
||||
},
|
||||
running: (n: number) => (n === 1 ? "1 cartão" : `${n} cartões`),
|
||||
},
|
||||
uploading: (done: number, total: number) => `A enviar ${done} de ${total}`,
|
||||
uploaded: (n: number) => (n === 1 ? "1 foto enviada" : `${n} fotos enviadas`),
|
||||
uploadFailed: (n: number) => `${n} com erro`,
|
||||
|
||||
+187
-125
@@ -1,35 +1,17 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useEffect, useState, useSyncExternalStore } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { desktopInvoke } from "../platform.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";
|
||||
|
||||
/**
|
||||
* "Importar cartão": copies (or moves) photos from a memory card into a dated folder on this computer, like Photo
|
||||
* Mechanic's Ingest (Cmd+Y). Desktop only. Pure filesystem — it does not send anything to the server. The last
|
||||
* settings used are remembered. Labels are inline (desktop-only dialog); they can move to i18n later.
|
||||
* Mechanic's Ingest. Desktop only. Nothing is sent to the server. The copy keeps running if this dialog closes;
|
||||
* the job list lives outside the component. The last settings are remembered, and named presets sit beside them.
|
||||
*/
|
||||
|
||||
type RawJpeg = "both" | "raw" | "jpeg";
|
||||
interface CardSettings {
|
||||
destination: string;
|
||||
folderTemplate: string;
|
||||
rawJpeg: RawJpeg;
|
||||
mv: boolean;
|
||||
overwrite: boolean;
|
||||
sidecars: boolean;
|
||||
}
|
||||
interface CardScan {
|
||||
raw: number;
|
||||
jpeg: number;
|
||||
other: number;
|
||||
bytes: number;
|
||||
}
|
||||
interface CardResult {
|
||||
copied: number;
|
||||
moved: number;
|
||||
skipped: number;
|
||||
failed: number;
|
||||
notes: string[];
|
||||
destination: string;
|
||||
}
|
||||
export type { CardResult, CardScan, CardSettings, RawJpeg } from "./cardJobs.js";
|
||||
|
||||
const DEFAULTS: CardSettings = {
|
||||
destination: "~/Pictures",
|
||||
@@ -46,16 +28,26 @@ const human = (bytes: number): string => {
|
||||
return `${Math.max(1, Math.round(bytes / 1e3))} KB`;
|
||||
};
|
||||
|
||||
function useCardJobs(): CardJob[] {
|
||||
return useSyncExternalStore(subscribeCardJobs, cardJobList, cardJobList);
|
||||
}
|
||||
|
||||
export function CardIngestButton() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const jobs = useCardJobs();
|
||||
const running = jobs.filter((job) => job.status === "running");
|
||||
let label: string = t.card.open;
|
||||
if (running.length > 1) label = t.card.running(running.length);
|
||||
else if (running[0]?.progress) label = t.card.progressButton(running[0].progress.done, running[0].progress.total);
|
||||
else if (running.length === 1) label = t.card.running(1);
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
onClick={() => setOpen(true)}
|
||||
title="Descarregar um cartão para uma pasta datada (copiar ou mover)"
|
||||
title={t.card.openTitle}
|
||||
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
|
||||
>
|
||||
Cartão…
|
||||
{label}
|
||||
</button>
|
||||
{open && <CardDialog onClose={() => setOpen(false)} />}
|
||||
</>
|
||||
@@ -63,180 +55,250 @@ export function CardIngestButton() {
|
||||
}
|
||||
|
||||
function CardDialog({ onClose }: { onClose: () => void }) {
|
||||
const jobs = useCardJobs();
|
||||
const [s, setS] = useState<CardSettings>(DEFAULTS);
|
||||
const [source, setSource] = useState("");
|
||||
const [scan, setScan] = useState<CardScan | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [progress, setProgress] = useState<{ done: number; total: number; name: string } | null>(null);
|
||||
const [result, setResult] = useState<CardResult | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [stopNote, setStopNote] = useState<string | null>(null);
|
||||
const canStart = jobs.some((job) => job.status === "queued");
|
||||
|
||||
useEffect(() => {
|
||||
desktopInvoke<CardSettings>("card_settings").then(setS).catch(() => {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
let stop: (() => void) | undefined;
|
||||
void import("@tauri-apps/api/event").then(({ listen }) =>
|
||||
listen<{ done: number; total: number; name: string }>("card-progress", (e) => setProgress(e.payload)).then(
|
||||
(un) => (alive ? (stop = un) : un()),
|
||||
),
|
||||
);
|
||||
return () => {
|
||||
alive = false;
|
||||
stop?.();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const total = scan ? scan.raw + scan.jpeg + scan.other : 0;
|
||||
|
||||
const pickSource = async () => {
|
||||
setError(null);
|
||||
const p = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null);
|
||||
if (!p) return;
|
||||
setSource(p);
|
||||
setScan(null);
|
||||
setResult(null);
|
||||
try {
|
||||
setScan(await desktopInvoke<CardScan>("card_scan", { source: p }));
|
||||
} catch (e) {
|
||||
setError(String(e));
|
||||
}
|
||||
const path = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null);
|
||||
if (!path) return;
|
||||
setSource(path);
|
||||
await enqueueCard(path);
|
||||
};
|
||||
|
||||
const pickDest = async () => {
|
||||
const p = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null);
|
||||
if (p) setS({ ...s, destination: p });
|
||||
const path = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null);
|
||||
if (path) setS({ ...s, destination: path });
|
||||
};
|
||||
|
||||
const run = async () => {
|
||||
if (!source) {
|
||||
setError("Escolhe primeiro o cartão/pasta de origem.");
|
||||
if (!jobs.some((job) => job.status === "queued")) {
|
||||
setError(t.card.needSource);
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setResult(null);
|
||||
setProgress({ done: 0, total, name: "" });
|
||||
setStopNote(null);
|
||||
try {
|
||||
await desktopInvoke("card_save_settings", { settings: s }); // remember the last settings used
|
||||
setResult(await desktopInvoke<CardResult>("card_ingest", { source, settings: s }));
|
||||
} catch (e) {
|
||||
setError(String(e));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
setProgress(null);
|
||||
await desktopInvoke("card_save_settings", { settings: s });
|
||||
} catch {
|
||||
// The copy still uses the settings on screen. Remembering them can wait.
|
||||
}
|
||||
await startQueued(s);
|
||||
};
|
||||
|
||||
const field = "h-7 w-full border border-black bg-[#161617] px-2 text-[12px] text-ink focus:border-accent focus:outline-none";
|
||||
const row = "flex items-center gap-2 text-[12px]";
|
||||
|
||||
return (
|
||||
<div role="dialog" aria-modal="true" aria-label="Importar cartão" className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-4">
|
||||
<div role="dialog" aria-modal="true" aria-label={t.card.title} className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-4">
|
||||
<div className="max-h-full w-full max-w-lg space-y-3 overflow-y-auto border border-line bg-panel p-4 shadow-2xl">
|
||||
<div className="flex items-center justify-between">
|
||||
<h2 className="font-semibold uppercase tracking-wide text-ink">Importar cartão</h2>
|
||||
<button onClick={onClose} className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on">
|
||||
Fechar
|
||||
</button>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h2 className="font-semibold uppercase tracking-wide text-ink">{t.card.title}</h2>
|
||||
<div className="flex items-center gap-2">
|
||||
<SnapshotMenu kind="card" current={s} onApply={setS} />
|
||||
<button onClick={onClose} className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on">
|
||||
{t.card.close}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-[11px] text-faint">Copia (ou move) as fotos de um cartão para uma pasta datada neste computador. Não envia nada para o servidor.</p>
|
||||
<p className="text-[11px] text-faint">{t.card.intro}</p>
|
||||
<p className="text-[11px] text-faint">{t.card.closeKeeps}</p>
|
||||
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">Origem (cartão/pasta)</span>
|
||||
<span className="mb-1 block text-[11px] text-faint">{t.card.source}</span>
|
||||
<div className="flex gap-2">
|
||||
<input readOnly value={source} placeholder="Escolhe o cartão…" className={field} />
|
||||
<button onClick={() => void pickSource()} className="h-7 shrink-0 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
|
||||
<input readOnly value={source} placeholder={t.card.sourcePlaceholder} className={field} />
|
||||
<button type="button" aria-label={t.card.add} onClick={() => void pickSource()} className="h-7 shrink-0 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
|
||||
…
|
||||
</button>
|
||||
</div>
|
||||
{scan && (
|
||||
<span className="mt-1 block text-[11px] text-muted">
|
||||
{scan.raw} RAW · {scan.jpeg} JPEG{scan.other ? ` · ${scan.other} outras` : ""} · {human(scan.bytes)}
|
||||
</span>
|
||||
)}
|
||||
</label>
|
||||
|
||||
{jobs.length > 0 && (
|
||||
<ul className="space-y-2">
|
||||
{jobs.map((job) => (
|
||||
<CardJobRow
|
||||
key={job.id}
|
||||
job={job}
|
||||
onRemove={() => dismissCard(job.id)}
|
||||
onStop={() => {
|
||||
setStopNote(null);
|
||||
void stopCard(job.id).then((note) => {
|
||||
if (note === "old-shell") setStopNote(t.card.oldShellStop);
|
||||
else if (note) setStopNote(note);
|
||||
else setStopNote(t.card.stopping);
|
||||
});
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">Destino</span>
|
||||
<span className="mb-1 block text-[11px] text-faint">{t.card.dest}</span>
|
||||
<div className="flex gap-2">
|
||||
<input value={s.destination} onChange={(e) => setS({ ...s, destination: e.target.value })} className={field} />
|
||||
<button onClick={() => void pickDest()} className="h-7 shrink-0 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
|
||||
<button type="button" onClick={() => void pickDest()} className="h-7 shrink-0 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
|
||||
…
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">Subpastas (template)</span>
|
||||
<span className="mb-1 block text-[11px] text-faint">{t.card.template}</span>
|
||||
<input value={s.folderTemplate} onChange={(e) => setS({ ...s, folderTemplate: e.target.value })} className={`${field} font-mono`} />
|
||||
<span className="mt-1 block text-[11px] text-faint">{"Variáveis: {iptcyear4} {iptcmonth0} {iptcday0} {type} {ext} — data pela hora do ficheiro."}</span>
|
||||
<span className="mt-1 block text-[11px] text-faint">{t.card.templateHelp}</span>
|
||||
</label>
|
||||
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<label className="block">
|
||||
<span className="mb-1 block text-[11px] text-faint">RAW + JPEG</span>
|
||||
<span className="mb-1 block text-[11px] text-faint">{t.card.rawJpeg}</span>
|
||||
<select value={s.rawJpeg} onChange={(e) => setS({ ...s, rawJpeg: e.target.value as RawJpeg })} className={field}>
|
||||
<option value="both">RAW e JPEG</option>
|
||||
<option value="raw">Só RAW</option>
|
||||
<option value="jpeg">Só JPEG</option>
|
||||
<option value="both">{t.card.both}</option>
|
||||
<option value="raw">{t.card.rawOnly}</option>
|
||||
<option value="jpeg">{t.card.jpegOnly}</option>
|
||||
</select>
|
||||
</label>
|
||||
<div className="flex flex-col justify-end gap-1">
|
||||
<label className={row}>
|
||||
<input type="checkbox" checked={s.mv} onChange={(e) => setS({ ...s, mv: e.target.checked })} />
|
||||
Mover (apaga do cartão depois de verificar)
|
||||
{t.card.move}
|
||||
</label>
|
||||
<label className={row}>
|
||||
<input type="checkbox" checked={s.overwrite} onChange={(e) => setS({ ...s, overwrite: e.target.checked })} />
|
||||
Sobrescrever existentes
|
||||
{t.card.overwrite}
|
||||
</label>
|
||||
<label className={row}>
|
||||
<input type="checkbox" checked={s.sidecars} onChange={(e) => setS({ ...s, sidecars: e.target.checked })} />
|
||||
Levar WAV/XMP
|
||||
{t.card.sidecars}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{s.mv && <p className="text-[11px] text-[#f0c27a]">Mover apaga os originais do cartão (só depois de a cópia ser verificada por tamanho e checksum).</p>}
|
||||
{s.mv && <p className="text-[11px] text-[#f0c27a]">{t.card.moveWarn}</p>}
|
||||
{error && <p className="text-[11px] text-danger">{error}</p>}
|
||||
{progress && busy && (
|
||||
<p className="text-[11px] text-muted">
|
||||
A processar {progress.done}/{progress.total}… {progress.name}
|
||||
</p>
|
||||
)}
|
||||
{result && (
|
||||
<div className="border border-line bg-cell p-2 text-[11px] text-ink">
|
||||
<p>
|
||||
{result.moved ? `${result.moved} movidas · ` : ""}
|
||||
{result.copied ? `${result.copied} copiadas · ` : ""}
|
||||
{result.skipped ? `${result.skipped} ignoradas · ` : ""}
|
||||
{result.failed ? `${result.failed} falhadas` : ""}
|
||||
{!result.moved && !result.copied && !result.skipped && !result.failed ? "Nada a fazer." : ""}
|
||||
</p>
|
||||
<p className="mt-1 break-all text-faint">{result.destination}</p>
|
||||
{result.notes.length > 0 && (
|
||||
<ul className="mt-1 list-inside list-disc text-faint">
|
||||
{result.notes.slice(0, 8).map((n, i) => (
|
||||
<li key={i}>{n}</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{stopNote && <p className="text-[11px] text-muted">{stopNote}</p>}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-1">
|
||||
<button
|
||||
onClick={() => void run()}
|
||||
disabled={busy || !source}
|
||||
disabled={!canStart}
|
||||
className="h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong disabled:opacity-40"
|
||||
>
|
||||
{s.mv ? "Mover" : "Copiar"}
|
||||
{s.mv ? t.card.moveAction : t.card.copy}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CardJobRow({ job, onRemove, onStop }: { job: CardJob; onRemove: () => void; onStop: () => void }) {
|
||||
const [, setTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (job.status !== "running") return;
|
||||
const timer = setInterval(() => setTick((n) => n + 1), 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, [job.status]);
|
||||
|
||||
const pace = copyPace(job.progress, job.startedAt, Date.now());
|
||||
const name = job.source.split("/").filter(Boolean).pop() ?? job.source;
|
||||
const scan = job.scan ? t.card.scan(job.scan.raw, job.scan.jpeg, job.scan.other, human(job.scan.bytes)) : null;
|
||||
|
||||
return (
|
||||
<li className="border border-line bg-cell p-2 text-[11px] text-ink">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="min-w-0 truncate">{name}</span>
|
||||
{job.status !== "running" && (
|
||||
<button type="button" onClick={onRemove} className="shrink-0 text-faint hover:text-ink">
|
||||
{t.card.remove}
|
||||
</button>
|
||||
)}
|
||||
{job.status === "running" && (
|
||||
<button type="button" onClick={onStop} className="shrink-0 border border-black bg-panel px-2 py-0.5 text-ink hover:bg-cell-on">
|
||||
{t.card.stop}
|
||||
</button>
|
||||
)}
|
||||
{job.status === "stopped" && <span className="shrink-0 text-faint">{t.card.stopped}</span>}
|
||||
</div>
|
||||
{scan && <p className="mt-1 text-muted">{scan}</p>}
|
||||
{job.status === "running" && job.progress && (
|
||||
<>
|
||||
<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>}
|
||||
{job.result && <JobResult result={job.result} />}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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) : "",
|
||||
result.copied ? t.card.result.copied(result.copied) : "",
|
||||
result.skipped ? t.card.result.skipped(result.skipped) : "",
|
||||
result.failed ? t.card.result.failed(result.failed) : "",
|
||||
].filter(Boolean);
|
||||
return (
|
||||
<div className="mt-1">
|
||||
<p>{parts.length > 0 ? parts.join(" · ") : t.card.result.empty}</p>
|
||||
<p className="mt-1 break-all text-faint">{result.destination}</p>
|
||||
{result.notes.length > 0 && (
|
||||
<ul className="mt-1 list-inside list-disc text-faint">
|
||||
{result.notes.slice(0, 8).map((note) => (
|
||||
<li key={note}>{note}</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { exifDateTime, lisbonInstant, localPhoto, localPhotos, routeLocally } fr
|
||||
import { localId, offlineQueue } from "../offline/queue.js";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { SnapshotMenu } from "./SnapshotMenu.js";
|
||||
import { asArrayBuffer, prefs } from "../platform.js";
|
||||
import type { DesktopOrigin, PreviewOf, UploadStatus } from "./uploads.js";
|
||||
|
||||
@@ -349,6 +350,9 @@ function SettingsForm({ ftp, initial, onDone }: { ftp: LocalFtpState; initial: F
|
||||
void ftp.save(s).then((ok) => ok && onDone());
|
||||
}}
|
||||
>
|
||||
<div className="flex justify-end">
|
||||
<SnapshotMenu kind="ftp" current={s} onApply={setS} />
|
||||
</div>
|
||||
<label className="block">
|
||||
<span className="text-[11px] uppercase tracking-wide text-faint">{L.port}</span>
|
||||
<input className={field} type="number" min={1024} max={65535} value={s.port} onChange={(e) => setS({ ...s, port: Number(e.target.value) })} />
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useState } from "react";
|
||||
import { t } from "../i18n.js";
|
||||
import { deleteSnapshot, loadSnapshots, saveSnapshot } from "./snapshots.js";
|
||||
|
||||
/**
|
||||
* Photo Mechanic's snapshot menu: the dialog remembers the last settings on its own, and a named preset
|
||||
* brings a whole setup back (destination and template, or an FTP login set).
|
||||
*/
|
||||
export function SnapshotMenu<T>({ kind, current, onApply }: { kind: string; current: T; onApply: (settings: T) => void }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [manage, setManage] = useState(false);
|
||||
const [name, setName] = useState("");
|
||||
const [items, setItems] = useState(() => loadSnapshots<T>(kind));
|
||||
|
||||
const refresh = () => setItems(loadSnapshots<T>(kind));
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={open}
|
||||
aria-label={t.snapshots.button}
|
||||
onClick={() => {
|
||||
refresh();
|
||||
setOpen((value) => !value);
|
||||
}}
|
||||
className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on"
|
||||
>
|
||||
{t.snapshots.button}
|
||||
</button>
|
||||
{open && (
|
||||
<div className="absolute right-0 z-10 mt-1 w-56 border border-black bg-panel p-2 text-[12px] shadow-xl">
|
||||
<div className="flex gap-1">
|
||||
<input
|
||||
aria-label={t.snapshots.name}
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter") return;
|
||||
event.preventDefault();
|
||||
setItems(saveSnapshot(kind, name, current));
|
||||
setName("");
|
||||
}}
|
||||
placeholder={t.snapshots.name}
|
||||
className="h-7 min-w-0 flex-1 border border-black bg-[#161617] px-2 text-ink focus:border-accent focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setItems(saveSnapshot(kind, name, current));
|
||||
setName("");
|
||||
}}
|
||||
className="h-7 shrink-0 border border-black bg-cell px-2 text-ink hover:bg-cell-on"
|
||||
>
|
||||
{t.snapshots.save}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setManage((value) => !value)}
|
||||
className="mt-2 block text-left text-accent underline"
|
||||
>
|
||||
{t.snapshots.manage}
|
||||
</button>
|
||||
{items.length === 0 ? (
|
||||
<p className="mt-2 text-faint">{t.snapshots.empty}</p>
|
||||
) : (
|
||||
<ul className="mt-1 max-h-48 overflow-y-auto">
|
||||
{items.map((item) => (
|
||||
<li key={item.name} className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onApply(item.settings);
|
||||
setOpen(false);
|
||||
setManage(false);
|
||||
}}
|
||||
className="min-w-0 flex-1 truncate py-1 text-left text-ink hover:bg-cell"
|
||||
>
|
||||
{item.name}
|
||||
</button>
|
||||
{manage && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`${t.snapshots.remove} ${item.name}`}
|
||||
onClick={() => setItems(deleteSnapshot(kind, item.name))}
|
||||
className="px-1 text-faint hover:text-ink"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const invoke = vi.fn();
|
||||
|
||||
vi.mock("../platform.js", () => ({
|
||||
desktopInvoke: (...args: unknown[]) => invoke(...args),
|
||||
}));
|
||||
|
||||
import { cardJobList, enqueueCard, resetCardJobsForTests, startQueued } from "./cardJobs.js";
|
||||
|
||||
const settings = {
|
||||
destination: "/tmp/out",
|
||||
folderTemplate: "{type}",
|
||||
rawJpeg: "both" as const,
|
||||
mv: false,
|
||||
overwrite: false,
|
||||
sidecars: true,
|
||||
};
|
||||
|
||||
describe("card jobs", () => {
|
||||
beforeEach(() => {
|
||||
resetCardJobsForTests();
|
||||
invoke.mockReset();
|
||||
});
|
||||
|
||||
it("runs several cards together when the shell can stop one", async () => {
|
||||
invoke.mockImplementation(async (cmd: string, args: { source?: string; jobId?: string }) => {
|
||||
if (cmd === "card_cancel") return null;
|
||||
if (cmd === "card_scan") return { raw: 1, jpeg: 2, other: 0, bytes: 30 };
|
||||
if (cmd === "card_ingest") return { copied: 3, moved: 0, skipped: 0, failed: 0, notes: [], destination: "/tmp/out", stopped: false, source: args.source, jobId: args.jobId };
|
||||
throw new Error(cmd);
|
||||
});
|
||||
await enqueueCard("/Volumes/ONE");
|
||||
await enqueueCard("/Volumes/TWO");
|
||||
await startQueued(settings);
|
||||
const copies = invoke.mock.calls.filter((call) => call[0] === "card_ingest");
|
||||
expect(copies).toHaveLength(2);
|
||||
expect(copies.every((call) => typeof call[1].jobId === "string" && call[1].jobId !== "")).toBe(true);
|
||||
expect(cardJobList().every((job) => job.status === "done")).toBe(true);
|
||||
});
|
||||
|
||||
it("queues cards one after another on a shell that cannot stop", async () => {
|
||||
invoke.mockImplementation(async (cmd: string) => {
|
||||
if (cmd === "card_cancel") throw new Error("Command card_cancel not found");
|
||||
if (cmd === "card_scan") return { raw: 0, jpeg: 1, other: 0, bytes: 10 };
|
||||
if (cmd === "card_ingest") return { copied: 1, moved: 0, skipped: 0, failed: 0, notes: [], destination: "/tmp/out", stopped: false };
|
||||
throw new Error(cmd);
|
||||
});
|
||||
await enqueueCard("/Volumes/ONE");
|
||||
await enqueueCard("/Volumes/TWO");
|
||||
await startQueued(settings);
|
||||
const copies = invoke.mock.calls.filter((call) => call[0] === "card_ingest");
|
||||
expect(copies).toHaveLength(2);
|
||||
expect(copies.every((call) => call[1].jobId === undefined)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,175 @@
|
||||
import { desktopInvoke } from "../platform.js";
|
||||
|
||||
export type RawJpeg = "both" | "raw" | "jpeg";
|
||||
|
||||
export interface CardSettings {
|
||||
destination: string;
|
||||
folderTemplate: string;
|
||||
rawJpeg: RawJpeg;
|
||||
mv: boolean;
|
||||
overwrite: boolean;
|
||||
sidecars: boolean;
|
||||
}
|
||||
|
||||
export interface CardScan {
|
||||
raw: number;
|
||||
jpeg: number;
|
||||
other: number;
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
export interface CardResult {
|
||||
copied: number;
|
||||
moved: number;
|
||||
skipped: number;
|
||||
failed: number;
|
||||
notes: string[];
|
||||
destination: string;
|
||||
stopped?: boolean;
|
||||
}
|
||||
|
||||
export interface CardProgress {
|
||||
done: number;
|
||||
total: number;
|
||||
name: string;
|
||||
jobId?: string;
|
||||
bytesDone?: number;
|
||||
bytesTotal?: number;
|
||||
}
|
||||
|
||||
export type CardJobStatus = "queued" | "running" | "done" | "stopped" | "error";
|
||||
|
||||
export interface CardJob {
|
||||
id: string;
|
||||
source: string;
|
||||
settings: CardSettings | null;
|
||||
scan: CardScan | null;
|
||||
status: CardJobStatus;
|
||||
progress: CardProgress | null;
|
||||
startedAt: number | null;
|
||||
result: CardResult | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
type Listener = () => void;
|
||||
|
||||
let jobs: CardJob[] = [];
|
||||
let canStop: boolean | null = null;
|
||||
const listeners = new Set<Listener>();
|
||||
let listening = false;
|
||||
|
||||
function emit() {
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
function patch(id: string, next: Partial<CardJob>) {
|
||||
jobs = jobs.map((job) => (job.id === id ? { ...job, ...next } : job));
|
||||
emit();
|
||||
}
|
||||
|
||||
export function cardJobList(): CardJob[] {
|
||||
return jobs;
|
||||
}
|
||||
|
||||
/** Clears the in-memory queue. Tests only. */
|
||||
export function resetCardJobsForTests() {
|
||||
jobs = [];
|
||||
canStop = null;
|
||||
listeners.clear();
|
||||
}
|
||||
|
||||
export function subscribeCardJobs(listener: Listener): () => void {
|
||||
listeners.add(listener);
|
||||
ensureProgress();
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/** The installed shell can stop a card when `card_cancel` exists. An older shell throws. */
|
||||
export async function shellCanStop(): Promise<boolean> {
|
||||
if (canStop !== null) return canStop;
|
||||
try {
|
||||
await desktopInvoke("card_cancel", { jobId: "" });
|
||||
canStop = true;
|
||||
} catch {
|
||||
canStop = false;
|
||||
}
|
||||
return canStop;
|
||||
}
|
||||
|
||||
function ensureProgress() {
|
||||
if (listening || typeof window === "undefined") return;
|
||||
listening = true;
|
||||
void import("@tauri-apps/api/event")
|
||||
.then(({ listen }) =>
|
||||
listen<CardProgress>("card-progress", (event) => {
|
||||
const progress = event.payload;
|
||||
const named = progress.jobId ? jobs.find((job) => job.id === progress.jobId) : undefined;
|
||||
const job = named ?? jobs.find((item) => item.status === "running");
|
||||
if (!job) return;
|
||||
patch(job.id, { progress, startedAt: job.startedAt ?? Date.now() });
|
||||
}),
|
||||
)
|
||||
.catch(() => {
|
||||
listening = false;
|
||||
});
|
||||
}
|
||||
|
||||
export async function enqueueCard(source: string): Promise<void> {
|
||||
const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
jobs = [...jobs, { id, source, settings: null, scan: null, status: "queued", progress: null, startedAt: null, result: null, error: null }];
|
||||
emit();
|
||||
try {
|
||||
const scan = await desktopInvoke<CardScan>("card_scan", { source });
|
||||
patch(id, { scan });
|
||||
} catch (err) {
|
||||
const job = jobs.find((item) => item.id === id);
|
||||
if (job?.status === "queued") patch(id, { status: "error", error: String(err) });
|
||||
}
|
||||
}
|
||||
|
||||
/** Drops a card that is not copying. A running copy stays until it finishes or is stopped. */
|
||||
export function dismissCard(id: string) {
|
||||
jobs = jobs.filter((job) => job.id !== id || job.status === "running");
|
||||
emit();
|
||||
}
|
||||
|
||||
async function runJob(id: string, settings: CardSettings, withId: boolean) {
|
||||
const job = jobs.find((item) => item.id === id);
|
||||
if (!job || job.status !== "queued") return;
|
||||
patch(id, { settings, status: "running", startedAt: Date.now(), error: null, result: null });
|
||||
const args: Record<string, unknown> = { source: job.source, settings };
|
||||
if (withId) args.jobId = id;
|
||||
try {
|
||||
const result = await desktopInvoke<CardResult>("card_ingest", args);
|
||||
patch(id, { status: result.stopped ? "stopped" : "done", result });
|
||||
} catch (err) {
|
||||
patch(id, { status: "error", error: String(err) });
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts every card still waiting. A shell that can stop runs them together; an older one, one after another. */
|
||||
export async function startQueued(settings: CardSettings): Promise<void> {
|
||||
ensureProgress();
|
||||
const parallel = await shellCanStop();
|
||||
const ids = jobs.filter((job) => job.status === "queued").map((job) => job.id);
|
||||
if (parallel) {
|
||||
await Promise.all(ids.map((id) => runJob(id, settings, true)));
|
||||
return;
|
||||
}
|
||||
for (const id of ids) {
|
||||
await runJob(id, settings, false);
|
||||
}
|
||||
}
|
||||
|
||||
export async function stopCard(id: string): Promise<string | null> {
|
||||
const ok = await shellCanStop();
|
||||
if (!ok) return "old-shell";
|
||||
try {
|
||||
await desktopInvoke("card_cancel", { jobId: id });
|
||||
return null;
|
||||
} catch (err) {
|
||||
return String(err);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { copyPace, formatRemaining, overallPace, remainingMs } from "./cardPace.js";
|
||||
|
||||
describe("card copy pace", () => {
|
||||
it("estimates the rest from the bytes already written", () => {
|
||||
const started = 1_000;
|
||||
expect(remainingMs(10, 40, started, started + 10_000)).toBe(30_000);
|
||||
expect(formatRemaining(30_000)).toBe("1 min");
|
||||
expect(formatRemaining(90 * 60_000)).toBe("1 h 30 min");
|
||||
const pace = copyPace({ done: 1, total: 4, bytesDone: 10, bytesTotal: 40 }, started, started + 10_000);
|
||||
expect(pace.fraction).toBeCloseTo(0.25);
|
||||
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();
|
||||
expect(copyPace(null, 0, 1_000)).toEqual({ fraction: 0, left: null });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
/** How far a card copy has got, and how long the rest should take at the pace so far. */
|
||||
export function remainingMs(done: number, total: number, startedAt: number, now: number): number | null {
|
||||
if (done <= 0 || total <= 0 || done >= total) return null;
|
||||
const elapsed = now - startedAt;
|
||||
if (elapsed < 500) return null;
|
||||
return Math.round((elapsed / done) * (total - done));
|
||||
}
|
||||
|
||||
export function formatRemaining(ms: number): string {
|
||||
const minutes = Math.round(ms / 60_000);
|
||||
if (minutes < 1) return "menos de 1 min";
|
||||
if (minutes < 60) return minutes === 1 ? "1 min" : `${minutes} min`;
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const rest = minutes % 60;
|
||||
if (rest === 0) return hours === 1 ? "1 h" : `${hours} h`;
|
||||
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,
|
||||
now: number,
|
||||
): { fraction: number; left: string | null } {
|
||||
if (!progress || startedAt === null || progress.total <= 0) return { fraction: 0, left: null };
|
||||
const byBytes = (progress.bytesTotal ?? 0) > 0;
|
||||
const done = byBytes ? (progress.bytesDone ?? 0) : progress.done;
|
||||
const total = byBytes ? (progress.bytesTotal as number) : progress.total;
|
||||
if (total <= 0) return { fraction: 0, left: null };
|
||||
const fraction = Math.max(0, Math.min(1, done / total));
|
||||
const left = remainingMs(done, total, startedAt, now);
|
||||
return { fraction, left: left === null ? null : formatRemaining(left) };
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { deleteSnapshot, loadSnapshots, saveSnapshot } from "./snapshots.js";
|
||||
|
||||
describe("dialog presets", () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
it("remembers a named preset and replaces one with the same name", () => {
|
||||
saveSnapshot("card", "Estúdio", { destination: "/a" });
|
||||
saveSnapshot("card", "Arquivo", { destination: "/b" });
|
||||
saveSnapshot("card", "Estúdio", { destination: "/c" });
|
||||
expect(loadSnapshots<{ destination: string }>("card").map((item) => [item.name, item.settings.destination])).toEqual([
|
||||
["Arquivo", "/b"],
|
||||
["Estúdio", "/c"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("drops a preset without touching another dialog", () => {
|
||||
saveSnapshot("card", "Estúdio", { destination: "/a" });
|
||||
saveSnapshot("ftp", "Campo", { port: 2121 });
|
||||
deleteSnapshot("card", "Estúdio");
|
||||
expect(loadSnapshots("card")).toEqual([]);
|
||||
expect(loadSnapshots<{ port: number }>("ftp")[0]?.settings.port).toBe(2121);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { prefs } from "../platform.js";
|
||||
|
||||
/** A named set of dialog settings, the same idea as a Photo Mechanic snapshot. */
|
||||
export interface Snapshot<T> {
|
||||
name: string;
|
||||
settings: T;
|
||||
}
|
||||
|
||||
function storageKey(kind: string): string {
|
||||
return `snapshot.${kind}`;
|
||||
}
|
||||
|
||||
export function loadSnapshots<T>(kind: string): Snapshot<T>[] {
|
||||
const raw = prefs.get(storageKey(kind));
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.filter((item): item is Snapshot<T> => {
|
||||
if (!item || typeof item !== "object") return false;
|
||||
const row = item as { name?: unknown; settings?: unknown };
|
||||
return typeof row.name === "string" && row.name.trim() !== "" && row.settings !== undefined;
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves under `name`, replacing a preset with the same name. Names sort in Portuguese. */
|
||||
export function saveSnapshot<T>(kind: string, name: string, settings: T): Snapshot<T>[] {
|
||||
const trimmed = name.trim();
|
||||
if (trimmed === "") return loadSnapshots(kind);
|
||||
const next = loadSnapshots<T>(kind).filter((item) => item.name !== trimmed);
|
||||
next.push({ name: trimmed, settings });
|
||||
next.sort((a, b) => a.name.localeCompare(b.name, "pt"));
|
||||
prefs.set(storageKey(kind), JSON.stringify(next));
|
||||
return next;
|
||||
}
|
||||
|
||||
export function deleteSnapshot<T>(kind: string, name: string): Snapshot<T>[] {
|
||||
const next = loadSnapshots<T>(kind).filter((item) => item.name !== name);
|
||||
prefs.set(storageKey(kind), JSON.stringify(next));
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { render, screen, waitFor } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { FacesQueuePage } from "./FacesQueuePage.js";
|
||||
|
||||
const staged = vi.hoisted(() => ({
|
||||
request: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("../auth.js", () => ({
|
||||
useAuth: () => ({
|
||||
organization: { id: "org-1" },
|
||||
api: {
|
||||
request: staged.request,
|
||||
absolute: (path: string) => path,
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
const ricardo = {
|
||||
id: "g1",
|
||||
eventId: "e1",
|
||||
size: 4,
|
||||
suggestion: { id: "p1", name: "Ricardo Candeias", club: "SPORTING CP", number: "C", score: 0.9 },
|
||||
event: { title: "SPORTING CP x SL BENFICA", startsAt: "2026-10-01T20:00:00.000Z" },
|
||||
samples: [],
|
||||
};
|
||||
|
||||
describe("faces queue", () => {
|
||||
beforeEach(() => {
|
||||
staged.request.mockReset();
|
||||
});
|
||||
|
||||
it("shows that Confirmar is working, then takes the card away", async () => {
|
||||
let release: () => void = () => undefined;
|
||||
const pending = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
staged.request.mockImplementation((method: string) => {
|
||||
if (method === "GET") return Promise.resolve({ groups: [ricardo] });
|
||||
return pending.then(() => ({ person: { id: "p1", name: "Ricardo Candeias" } }));
|
||||
});
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<FacesQueuePage />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
const button = await screen.findByRole("button", { name: "Confirmar" });
|
||||
await userEvent.click(button);
|
||||
expect((await screen.findByRole("button", { name: "A confirmar…" })).hasAttribute("disabled")).toBe(true);
|
||||
release();
|
||||
await waitFor(() => expect(screen.queryByText("Ricardo Candeias")).toBeNull());
|
||||
expect(staged.request).toHaveBeenCalledWith("POST", "/v1/face-groups/g1/confirm", { personId: "p1" });
|
||||
});
|
||||
|
||||
it("says so when Confirmar fails, and leaves the card", async () => {
|
||||
staged.request.mockImplementation((method: string) => {
|
||||
if (method === "GET") return Promise.resolve({ groups: [ricardo] });
|
||||
return Promise.reject(new Error("conflict"));
|
||||
});
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<FacesQueuePage />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Confirmar" }));
|
||||
expect(await screen.findByText("Não confirmei. Tenta outra vez.")).toBeTruthy();
|
||||
expect(screen.getByText("Ricardo Candeias")).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: "Confirmar" }).hasAttribute("disabled")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -32,6 +32,7 @@ export function FacesQueuePage() {
|
||||
const orgId = organization?.id ?? "";
|
||||
const [rows, setRows] = useState<Row[] | null>(null);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [failed, setFailed] = useState<string | null>(null);
|
||||
const [open, setOpen] = useState<Sample[] | null>(null);
|
||||
const [at, setAt] = useState(0);
|
||||
|
||||
@@ -54,29 +55,33 @@ export function FacesQueuePage() {
|
||||
const personId = pile[0]?.suggestion?.id;
|
||||
if (!personId) return;
|
||||
setBusy(personId);
|
||||
setFailed(null);
|
||||
try {
|
||||
for (const row of pile) await api.request("POST", `/v1/face-groups/${row.id}/confirm`, { personId });
|
||||
setRows((cur) => cur?.filter((r) => !pile.some((p) => p.id === r.id)) ?? null);
|
||||
} catch {
|
||||
setFailed(personId);
|
||||
await load().catch(() => undefined);
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="flex h-full min-h-0 w-full min-w-0 flex-col overflow-hidden">
|
||||
<PageHeader title={t.faces.title} />
|
||||
<p className="px-4 pt-3 text-[13px] text-muted">
|
||||
As caras por confirmar, juntas por pessoa. As camisolas ensinam-se em <Link to="/numbers" className="underline">{t.numbersNav}</Link>.
|
||||
</p>
|
||||
<div className="grid flex-1 content-start gap-3 overflow-auto p-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
<div className="grid min-h-0 min-w-0 flex-1 content-start gap-3 overflow-x-hidden overflow-y-auto p-4 pb-6 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{rows === null && <p className="text-sm text-muted">A carregar…</p>}
|
||||
{rows?.length === 0 && <p className="text-sm text-muted">Nada por confirmar.</p>}
|
||||
{[...piles.values()].map((pile) => {
|
||||
const who = pile[0]!.suggestion;
|
||||
const faces = pile.flatMap((r) => r.samples);
|
||||
return (
|
||||
<article key={who?.id ?? pile[0]!.id} className="flex flex-col gap-2 border border-[#151516] bg-cell p-2">
|
||||
<button type="button" className="flex flex-wrap gap-1 text-left" onClick={() => (setOpen(faces), setAt(0))}>
|
||||
<article key={who?.id ?? pile[0]!.id} className="flex min-w-0 flex-col gap-2 border border-[#151516] bg-cell p-2">
|
||||
<button type="button" className="flex min-w-0 flex-wrap gap-1 text-left" onClick={() => (setOpen(faces), setAt(0))}>
|
||||
{faces.slice(0, 6).map((s) => (
|
||||
<FaceCrop key={s.faceId} src={api.absolute(s.preview)} box={s} aspect={s.aspect} size={faces.length > 3 ? 52 : 72} />
|
||||
))}
|
||||
@@ -89,9 +94,10 @@ export function FacesQueuePage() {
|
||||
.join(" · ")}
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" className="h-8 border border-black bg-accent text-[12px] text-ink" disabled={busy === who?.id} onClick={() => void confirm(pile)}>
|
||||
Confirmar
|
||||
<button type="button" className="h-8 w-full shrink-0 border border-black bg-accent text-[12px] text-ink disabled:opacity-70" disabled={busy === who?.id || !who?.id} onClick={() => void confirm(pile)}>
|
||||
{busy === who?.id ? t.faces.confirming : t.faces.confirm}
|
||||
</button>
|
||||
{failed === who?.id && <p className="text-[11px] text-danger">{t.faces.confirmFailed}</p>}
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -54,22 +54,15 @@ export function PreferencesPage() {
|
||||
</label>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
{role === "OWNER" && organization && (
|
||||
<section className="max-w-2xl px-6 pb-6">
|
||||
<div className="border border-line bg-panel">
|
||||
<div className="panel-head">
|
||||
<span>{t.realEstate.setting}</span>
|
||||
<span className={realEstateOn ? "text-ok" : "text-faint"}>{realEstateOn ? t.realEstate.enabled : t.realEstate.off}</span>
|
||||
</div>
|
||||
<div className="space-y-3 p-4">
|
||||
<p className="text-[13px] text-muted">{t.realEstate.settingHelp}</p>
|
||||
{realEstateError && <p className="text-[12px] text-danger">{realEstateError}</p>}
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
{role === "OWNER" && organization && (
|
||||
<li>
|
||||
<label className="flex h-11 cursor-pointer items-center gap-3 rounded-md border border-line bg-panel px-3 text-sm hover:border-faint">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-4 w-4 accent-[var(--color-accent)]"
|
||||
checked={realEstateOn}
|
||||
disabled={realEstateBusy}
|
||||
onClick={() => {
|
||||
onChange={() => {
|
||||
setRealEstateBusy(true);
|
||||
setRealEstateError(null);
|
||||
void (async () => {
|
||||
@@ -84,15 +77,15 @@ export function PreferencesPage() {
|
||||
}
|
||||
})();
|
||||
}}
|
||||
className="h-8 border border-black bg-cell px-4 text-[13px] hover:bg-cell-on disabled:opacity-50"
|
||||
>
|
||||
{realEstateOn ? t.realEstate.disable : t.realEstate.enable}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
/>
|
||||
{t.realEstate.setting}
|
||||
</label>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
{role === "OWNER" && organization && <p className="mt-3 text-sm text-muted">{t.realEstate.settingHelp}</p>}
|
||||
{realEstateError && <Alert>{realEstateError}</Alert>}
|
||||
</section>
|
||||
{isDesktop() && <LocalCatalog />}
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -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();
|
||||
@@ -103,7 +107,7 @@ describe("real estate area", () => {
|
||||
window.history.pushState({}, "", "/preferences");
|
||||
const api = fakeApi(me("OWNER", false));
|
||||
render(<App api={api} />);
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Ligar" }));
|
||||
await userEvent.click(await screen.findByRole("checkbox", { name: "Imobiliário" }));
|
||||
expect(api.setRealEstate).toHaveBeenCalledWith("o1", true);
|
||||
});
|
||||
});
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@photoreport/desktop",
|
||||
"version": "0.3.20",
|
||||
"version": "0.3.21",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "photoreport-desktop"
|
||||
version = "0.3.20"
|
||||
version = "0.3.21"
|
||||
edition = "2024"
|
||||
publish = false
|
||||
description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine."
|
||||
|
||||
@@ -28,6 +28,7 @@ fn main() {
|
||||
"catalog_cancel",
|
||||
"card_scan",
|
||||
"card_ingest",
|
||||
"card_cancel",
|
||||
"card_settings",
|
||||
"card_save_settings",
|
||||
"faces_local",
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
"allow-catalog-cancel",
|
||||
"allow-card-scan",
|
||||
"allow-card-ingest",
|
||||
"allow-card-cancel",
|
||||
"allow-card-settings",
|
||||
"allow-card-save-settings",
|
||||
"allow-faces-local",
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Automatically generated - DO NOT EDIT!
|
||||
|
||||
[[permission]]
|
||||
identifier = "allow-card-cancel"
|
||||
description = "Enables the card_cancel command without any pre-configured scope."
|
||||
commands.allow = ["card_cancel"]
|
||||
|
||||
[[permission]]
|
||||
identifier = "deny-card-cancel"
|
||||
description = "Denies the card_cancel command without any pre-configured scope."
|
||||
commands.deny = ["card_cancel"]
|
||||
@@ -5,11 +5,15 @@
|
||||
//! then deletes the original; on any mismatch or error it never deletes, so a card is never emptied of a file
|
||||
//! that did not arrive whole. The last settings used are remembered (like Photo Mechanic's dialog).
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use chrono::{Datelike, Local, TimeZone};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use tauri::{AppHandle, Emitter};
|
||||
|
||||
use crate::local::sha256_file;
|
||||
@@ -92,6 +96,8 @@ impl Default for CardSettings {
|
||||
pub struct CardState {
|
||||
settings: Mutex<Option<CardSettings>>,
|
||||
config_path: Option<PathBuf>,
|
||||
/// One flag per running card. A second card is another command, so the cards run side by side.
|
||||
cancel: Mutex<HashMap<String, Arc<AtomicBool>>>,
|
||||
}
|
||||
|
||||
fn config_file() -> PathBuf {
|
||||
@@ -126,6 +132,22 @@ impl CardState {
|
||||
*self.settings.lock().unwrap() = Some(s);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn begin(&self, job_id: &str) -> Arc<AtomicBool> {
|
||||
let flag = Arc::new(AtomicBool::new(false));
|
||||
self.cancel.lock().unwrap().insert(job_id.to_string(), flag.clone());
|
||||
flag
|
||||
}
|
||||
|
||||
fn end(&self, job_id: &str) {
|
||||
self.cancel.lock().unwrap().remove(job_id);
|
||||
}
|
||||
|
||||
fn stop(&self, job_id: &str) {
|
||||
if let Some(flag) = self.cancel.lock().unwrap().get(job_id) {
|
||||
flag.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The type folder for a file: "RAW", "JPEG", or the extension upper-cased for anything else.
|
||||
@@ -178,15 +200,28 @@ fn ymd_from_capture(bytes: &[u8]) -> Option<(i32, u32, u32)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The capture day of a photo. LightCraft reads EXIF, then IPTC, then XMP, including a CR3 with no JPEG
|
||||
/// beside it. A JPEG whose header the engine cannot read still tries the short EXIF scan. Otherwise the
|
||||
/// file's modification time — on a card straight from the camera that is when the frame was shot.
|
||||
/// Capture day from the bytes already in memory. The header is enough for a JPEG; a CR3 sometimes
|
||||
/// keeps the metadata at the end, so the caller reads the rest only when the head had no clock.
|
||||
fn ymd_of(bytes: &[u8]) -> Option<(i32, u32, u32)> {
|
||||
ymd_from_capture(bytes).or_else(|| crate::preview::exif_date(bytes))
|
||||
}
|
||||
|
||||
/// The capture day of a photo. LightCraft reads EXIF, then IPTC, then XMP. A JPEG is not read whole:
|
||||
/// the clock is in the header. A raw whose header has no clock is read whole (a CR3 can park it at the
|
||||
/// end). Otherwise the file's modification time — on a card straight from the camera that is the shot.
|
||||
fn capture_day(path: &Path, ext: &str) -> chrono::DateTime<Local> {
|
||||
let from_engine = || std::fs::read(path).ok().and_then(|bytes| ymd_from_capture(&bytes));
|
||||
let ymd = if is_jpeg(ext) {
|
||||
from_engine().or_else(|| crate::preview::exif_date(&read_head(path)))
|
||||
} else if is_image(ext) {
|
||||
from_engine().or_else(|| sibling_jpeg(path).and_then(|j| crate::preview::exif_date(&read_head(&j))))
|
||||
let from_file = |path: &Path| {
|
||||
let head = read_head(path);
|
||||
if let Some(day) = ymd_of(&head) {
|
||||
return Some(day);
|
||||
}
|
||||
if head.len() < 256 * 1024 {
|
||||
return None;
|
||||
}
|
||||
std::fs::read(path).ok().and_then(|bytes| ymd_of(&bytes))
|
||||
};
|
||||
let ymd = if is_image(ext) {
|
||||
from_file(path).or_else(|| sibling_jpeg(path).and_then(|j| from_file(&j)))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -289,6 +324,8 @@ pub struct CardResult {
|
||||
/// A few lines describing what failed or was skipped, for the person to see.
|
||||
pub notes: Vec<String>,
|
||||
pub destination: String,
|
||||
/// The photographer asked to stop. Files already verified stay; the rest were not touched.
|
||||
pub stopped: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone)]
|
||||
@@ -297,6 +334,9 @@ struct Progress {
|
||||
done: usize,
|
||||
total: usize,
|
||||
name: String,
|
||||
job_id: String,
|
||||
bytes_done: u64,
|
||||
bytes_total: u64,
|
||||
}
|
||||
|
||||
fn wanted(ext: &str, mode: RawJpeg) -> bool {
|
||||
@@ -307,112 +347,177 @@ fn wanted(ext: &str, mode: RawJpeg) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies one file and checks the copy is whole (same size, same SHA-256). Returns Ok only when it is.
|
||||
/// Copies one file, hashing the card as the bytes are read, then checks the copy on disk.
|
||||
/// The card is read once. A second read of the same card, only to hash it, is what made a full
|
||||
/// offload take about twice as long. Returns Ok only when the copy matches.
|
||||
fn copy_verified(src: &Path, dst: &Path) -> Result<(), String> {
|
||||
std::fs::copy(src, dst).map_err(|e| format!("copy: {e}"))?;
|
||||
let src_len = std::fs::metadata(src).map_err(|e| e.to_string())?.len();
|
||||
let dst_len = std::fs::metadata(dst).map_err(|e| e.to_string())?.len();
|
||||
if src_len != dst_len {
|
||||
let _ = std::fs::remove_file(dst);
|
||||
return Err("size mismatch after copy".into());
|
||||
let mut input = std::fs::File::open(src).map_err(|e| format!("copy: {e}"))?;
|
||||
let mut output = std::fs::File::create(dst).map_err(|e| format!("copy: {e}"))?;
|
||||
let mut hasher = Sha256::new();
|
||||
let mut buf = vec![0u8; 1 << 20];
|
||||
loop {
|
||||
let n = input.read(&mut buf).map_err(|e| format!("copy: {e}"))?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
hasher.update(&buf[..n]);
|
||||
if let Err(e) = output.write_all(&buf[..n]) {
|
||||
let _ = std::fs::remove_file(dst);
|
||||
return Err(format!("copy: {e}"));
|
||||
}
|
||||
}
|
||||
if sha256_file(src).map_err(|e| e.to_string())? != sha256_file(dst).map_err(|e| e.to_string())? {
|
||||
let _ = output.sync_all();
|
||||
drop(output);
|
||||
let src_hex = hex_of(&hasher.finalize());
|
||||
let dst_hex = match sha256_file(dst) {
|
||||
Ok(hex) => hex,
|
||||
Err(e) => {
|
||||
let _ = std::fs::remove_file(dst);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
};
|
||||
if src_hex != dst_hex {
|
||||
let _ = std::fs::remove_file(dst);
|
||||
return Err("checksum mismatch after copy".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn hex_of(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
fn note(notes: &mut Vec<String>, line: &str) {
|
||||
if notes.len() < 20 {
|
||||
notes.push(line.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies (or moves) the chosen photos from `source` into the dated folders under the destination. Emits
|
||||
/// `card-progress` events as it goes.
|
||||
#[tauri::command]
|
||||
pub async fn card_ingest(app: AppHandle, source: String, settings: CardSettings) -> Result<CardResult, String> {
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let root = expand(&source);
|
||||
if !root.is_dir() {
|
||||
return Err("not_a_folder".to_string());
|
||||
fn report(app: Option<&AppHandle>, progress: &Progress) {
|
||||
if let Some(app) = app {
|
||||
let _ = app.emit("card-progress", progress);
|
||||
}
|
||||
}
|
||||
|
||||
/// One card, one stream. A memory card has a single reader: several threads on it seek back and forth and
|
||||
/// usually finish later, not sooner. A second card is a second call, so the two readers work at once.
|
||||
fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job_id: &str, cancel: &AtomicBool) -> Result<CardResult, String> {
|
||||
if !root.is_dir() {
|
||||
return Err("not_a_folder".to_string());
|
||||
}
|
||||
let base = expand(&settings.destination);
|
||||
let mut files = Vec::new();
|
||||
collect(root, &mut files);
|
||||
let photos: Vec<PathBuf> = files.into_iter().filter(|f| wanted(&ext_of(f), settings.raw_jpeg)).collect();
|
||||
let total = photos.len();
|
||||
let bytes_total: u64 = photos.iter().map(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0)).sum();
|
||||
let mut bytes_done = 0u64;
|
||||
let mut r = CardResult {
|
||||
copied: 0,
|
||||
moved: 0,
|
||||
skipped: 0,
|
||||
failed: 0,
|
||||
notes: Vec::new(),
|
||||
destination: base.to_string_lossy().to_string(),
|
||||
stopped: false,
|
||||
};
|
||||
for (i, src) in photos.iter().enumerate() {
|
||||
if cancel.load(Ordering::Relaxed) {
|
||||
r.stopped = true;
|
||||
break;
|
||||
}
|
||||
let base = expand(&settings.destination);
|
||||
let mut files = Vec::new();
|
||||
collect(&root, &mut files);
|
||||
let photos: Vec<PathBuf> = files.iter().filter(|f| wanted(&ext_of(f), settings.raw_jpeg)).cloned().collect();
|
||||
let total = photos.len();
|
||||
let mut r = CardResult {
|
||||
copied: 0,
|
||||
moved: 0,
|
||||
skipped: 0,
|
||||
failed: 0,
|
||||
notes: Vec::new(),
|
||||
destination: base.to_string_lossy().to_string(),
|
||||
};
|
||||
for (i, src) in photos.iter().enumerate() {
|
||||
let name = src.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||
let _ = app.emit("card-progress", Progress { done: i, total, name: name.clone() });
|
||||
let name = src.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
|
||||
let len = std::fs::metadata(src).map(|m| m.len()).unwrap_or(0);
|
||||
report(app, &Progress { done: i + 1, total, name: name.clone(), job_id: job_id.to_string(), bytes_done, bytes_total });
|
||||
|
||||
let ext = ext_of(src);
|
||||
let folder = render_folder(&settings.folder_template, &capture_day(src, &ext), &ext);
|
||||
let dir = base.join(folder.trim_start_matches('/'));
|
||||
if let Err(e) = std::fs::create_dir_all(&dir) {
|
||||
r.failed += 1;
|
||||
note(&mut r.notes, &format!("{name}: pasta — {e}"));
|
||||
continue;
|
||||
}
|
||||
let ext = ext_of(src);
|
||||
let folder = render_folder(&settings.folder_template, &capture_day(src, &ext), &ext);
|
||||
let dir = base.join(folder.trim_start_matches('/'));
|
||||
if let Err(e) = std::fs::create_dir_all(&dir) {
|
||||
r.failed += 1;
|
||||
bytes_done += len;
|
||||
note(&mut r.notes, &format!("{name}: pasta — {e}"));
|
||||
continue;
|
||||
}
|
||||
|
||||
// The photo itself first. A file already there is skipped (unless "overwrite"); nothing is deleted then.
|
||||
let target = dir.join(&name);
|
||||
if target.exists() && !settings.overwrite {
|
||||
r.skipped += 1;
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = copy_verified(src, &target) {
|
||||
r.failed += 1;
|
||||
note(&mut r.notes, &format!("{name}: {e}"));
|
||||
continue;
|
||||
}
|
||||
// The photo itself first. A file already there is skipped (unless "overwrite"); nothing is deleted then.
|
||||
let target = dir.join(&name);
|
||||
if target.exists() && !settings.overwrite {
|
||||
r.skipped += 1;
|
||||
bytes_done += len;
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = copy_verified(src, &target) {
|
||||
r.failed += 1;
|
||||
bytes_done += len;
|
||||
note(&mut r.notes, &format!("{name}: {e}"));
|
||||
continue;
|
||||
}
|
||||
|
||||
// Its sidecars (same stem): best effort — a sidecar that fails is noted but does not fail the photo.
|
||||
let mut sidecars_done: Vec<PathBuf> = Vec::new();
|
||||
if settings.sidecars {
|
||||
if let (Some(stem), Some(parent)) = (src.file_stem().and_then(|s| s.to_str()), src.parent()) {
|
||||
for s in SIDECAR_EXTS {
|
||||
let side = parent.join(format!("{stem}.{s}"));
|
||||
if !side.exists() {
|
||||
continue;
|
||||
}
|
||||
let side_target = dir.join(format!("{stem}.{s}"));
|
||||
if side_target.exists() && !settings.overwrite {
|
||||
continue;
|
||||
}
|
||||
match copy_verified(&side, &side_target) {
|
||||
Ok(()) => sidecars_done.push(side),
|
||||
Err(e) => note(&mut r.notes, &format!("{stem}.{s}: {e}")),
|
||||
}
|
||||
// Its sidecars (same stem): best effort — a sidecar that fails is noted but does not fail the photo.
|
||||
let mut sidecars_done: Vec<PathBuf> = Vec::new();
|
||||
if settings.sidecars {
|
||||
if let (Some(stem), Some(parent)) = (src.file_stem().and_then(|s| s.to_str()), src.parent()) {
|
||||
for s in SIDECAR_EXTS {
|
||||
let side = parent.join(format!("{stem}.{s}"));
|
||||
if !side.exists() {
|
||||
continue;
|
||||
}
|
||||
let side_target = dir.join(format!("{stem}.{s}"));
|
||||
if side_target.exists() && !settings.overwrite {
|
||||
continue;
|
||||
}
|
||||
match copy_verified(&side, &side_target) {
|
||||
Ok(()) => sidecars_done.push(side),
|
||||
Err(e) => note(&mut r.notes, &format!("{stem}.{s}: {e}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Move: the copy is verified, so the originals can go. Only what arrived whole is deleted.
|
||||
if settings.mv {
|
||||
let _ = std::fs::remove_file(src);
|
||||
for side in &sidecars_done {
|
||||
let _ = std::fs::remove_file(side);
|
||||
}
|
||||
r.moved += 1;
|
||||
} else {
|
||||
r.copied += 1;
|
||||
}
|
||||
}
|
||||
let _ = app.emit("card-progress", Progress { done: total, total, name: String::new() });
|
||||
Ok(r)
|
||||
|
||||
// Move: the copy is verified, so the originals can go. Only what arrived whole is deleted.
|
||||
if settings.mv {
|
||||
let _ = std::fs::remove_file(src);
|
||||
for side in &sidecars_done {
|
||||
let _ = std::fs::remove_file(side);
|
||||
}
|
||||
r.moved += 1;
|
||||
} else {
|
||||
r.copied += 1;
|
||||
}
|
||||
bytes_done += len;
|
||||
}
|
||||
let finished = r.copied + r.moved + r.skipped + r.failed;
|
||||
report(
|
||||
app,
|
||||
&Progress { done: finished, total, name: String::new(), job_id: job_id.to_string(), bytes_done, bytes_total },
|
||||
);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Copies (or moves) the chosen photos from `source` into the dated folders under the destination. Emits
|
||||
/// `card-progress` events as it goes. `job_id` lets several cards report progress without mixing, and lets
|
||||
/// [`card_cancel`] stop one of them. Omitted, the job is named `default` (one card at a time).
|
||||
#[tauri::command]
|
||||
pub async fn card_ingest(app: AppHandle, source: String, settings: CardSettings, job_id: Option<String>, state: tauri::State<'_, CardState>) -> Result<CardResult, String> {
|
||||
let job_id = job_id.unwrap_or_else(|| "default".to_string());
|
||||
let cancel = state.begin(&job_id);
|
||||
let end_id = job_id.clone();
|
||||
let result = tauri::async_runtime::spawn_blocking(move || {
|
||||
let root = expand(&source);
|
||||
ingest_dir(Some(&app), &root, &settings, &job_id, &cancel)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())?
|
||||
.map_err(|e| e.to_string());
|
||||
state.end(&end_id);
|
||||
result?
|
||||
}
|
||||
|
||||
/// Stops one card after the file it is copying now. An unknown id does nothing, so a probe can ask
|
||||
/// whether this shell knows how to stop.
|
||||
#[tauri::command]
|
||||
pub fn card_cancel(job_id: String, state: tauri::State<'_, CardState>) {
|
||||
state.stop(&job_id);
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -425,3 +530,35 @@ pub fn card_save_settings(state: tauri::State<'_, CardState>, settings: CardSett
|
||||
state.save(settings.clone())?;
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_stop_copies_nothing_and_a_clear_flag_copies_the_card() {
|
||||
let dir = std::env::temp_dir().join(format!("pr-card-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let src = dir.join("src");
|
||||
let dst = dir.join("dst");
|
||||
std::fs::create_dir_all(&src).unwrap();
|
||||
std::fs::write(src.join("a.jpg"), b"hello card").unwrap();
|
||||
std::fs::write(src.join("b.jpg"), b"second").unwrap();
|
||||
let settings = CardSettings {
|
||||
destination: dst.to_string_lossy().to_string(),
|
||||
folder_template: String::new(),
|
||||
..CardSettings::default()
|
||||
};
|
||||
|
||||
let stopped = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(true)).unwrap();
|
||||
assert!(stopped.stopped);
|
||||
assert_eq!(stopped.copied, 0);
|
||||
assert!(!dst.join("a.jpg").exists());
|
||||
|
||||
let done = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(false)).unwrap();
|
||||
assert!(!done.stopped);
|
||||
assert_eq!(done.copied, 2);
|
||||
assert_eq!(std::fs::read(dst.join("a.jpg")).unwrap(), b"hello card");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -135,6 +135,7 @@ pub fn run() {
|
||||
catalog::catalog_cancel,
|
||||
card::card_scan,
|
||||
card::card_ingest,
|
||||
card::card_cancel,
|
||||
card::card_settings,
|
||||
card::card_save_settings,
|
||||
faces::faces_local,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "PhotoReport",
|
||||
"version": "0.3.20",
|
||||
"version": "0.3.21",
|
||||
"identifier": "pt.photoreport.desktop",
|
||||
"build": {
|
||||
"devUrl": "http://localhost:5173",
|
||||
|
||||
@@ -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"]);
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
Reference in new issue
Block a user