Compare commits

...
Author SHA1 Message Date
spark 010ef22f62 feat(library): put colour and selection where the cull happens
ci / typescript (pull_request) Failing after 4m26s
ci / rust (pull_request) Successful in 13m42s
The chips and the right-click menu did not show how to mark or filter, and a short drag list was uploaded as if it were the whole drop.
2026-11-06 21:48:45 +00:00
spark ea6ae03ad1 feat(library): filter photos with no colour and add selection menus
ci / typescript (push) Failing after 4m24s
ci / rust (push) Successful in 13m50s
The colour bar had no unmarked-only filter, and the system menu cannot select photos.
2026-11-06 21:43:03 +00:00
spark ba1142c73f feat(library): filter photos with no colour and add selection menus
ci / typescript (pull_request) Failing after 4m31s
ci / rust (pull_request) Successful in 14m18s
The colour bar had no way to show only unmarked photos, and the system menu cannot select or mark them.
2026-11-06 21:42:59 +00:00
spark ea8308d703 chore(app): republish the library interface
ci / typescript (push) Failing after 4m12s
ci / rust (push) Successful in 14m36s
The running app was still the previous build.
2026-11-06 21:40:46 +00:00
spark 3813fe90ae chore(app): republish the library interface
ci / typescript (pull_request) Failing after 4m18s
ci / rust (pull_request) Successful in 14m40s
The colour filter and drag-select were on main, and the running app was still the previous build.
2026-11-06 21:40:43 +00:00
spark 2241d54dab fix(library): drag a rectangle to select several photos
ci / typescript (push) Failing after 4m3s
ci / rust (push) Successful in 15m4s
One colour paints the whole selection.
2026-11-06 21:29:45 +00:00
spark 68603f25e3 fix(library): drag a rectangle to select several photos
ci / typescript (pull_request) Failing after 3m57s
ci / rust (pull_request) Successful in 13m57s
A colour is painted on the whole selection. Shift or Cmd while dragging adds to what was already selected.
2026-11-06 21:29:41 +00:00
spark 29230c09e4 fix(library): mark a colour and hide the photos that have it
ci / typescript (push) Failing after 4m21s
ci / rust (push) Successful in 13m9s
Second click hides that colour.
2026-11-06 21:28:30 +00:00
spark a9065856df fix(library): mark a colour and hide the photos that have it
ci / typescript (pull_request) Failing after 3m54s
ci / rust (pull_request) Successful in 12m10s
The chips only kept photos of that colour, and painting a selection had no button. A second click hides that colour so the rest of the set stays on screen.
2026-11-06 21:28:27 +00:00
spark 2f3c12be28 fix(upload): file a photo when the named event is gone
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Failing after 21s
ci / typescript (push) Failing after 14m0s
ci / rust (push) Successful in 10m40s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 59m53s
A missing event no longer refuses the photo.
2026-11-06 21:25:12 +00:00
spark d195860d56 fix(upload): file a photo when the named event is gone
ci / rust (pull_request) Successful in 9m14s
ci / typescript (pull_request) Failing after 13m54s
A drop was refused with event_not_in_organization, so most of the files never appeared. The photo is filed by its capture time instead. The desktop reads every file in the drop, not only the few the page list kept.
2026-11-06 21:25:10 +00:00
spark 557d7351ce fix(library): take the colour Photo Mechanic paints
ci / rust (push) Successful in 10m25s
ci / typescript (push) Failing after 14m39s
Colour class comes back into the library.
2026-11-06 21:18:46 +00:00
spark e5d7ca324f fix(library): take the colour Photo Mechanic paints
ci / rust (pull_request) Successful in 10m40s
ci / typescript (pull_request) Failing after 14m31s
The desktop re-read the file for a crop and a reject, and left the colour behind. Colour class 1, 3, 4, 5 and 7 become red, yellow, green, blue and purple on the photo.
2026-11-06 21:18:42 +00:00
spark 6721df6432 fix(sports): fill the handball city from the home club
ci / rust (push) Successful in 9m58s
ci / typescript (push) Failing after 13m14s
City from the home club locality.
2026-11-06 21:12:43 +00:00
spark 96539a1f60 fix(sports): fill the handball city from the home club
ci / rust (pull_request) Successful in 9m10s
ci / typescript (pull_request) Failing after 12m50s
The sheet names the hall. The town is the home club's locality, so Oriental is Lisboa and Albicastrense is Castelo Branco. The federation's own card is not used for a national team.
2026-11-06 21:12:40 +00:00
spark c628dcf288 fix(sports): keep the stadium and the home club town apart
ci / rust (push) Successful in 8m47s
ci / typescript (push) Failing after 12m54s
Stadium and home town on every federation import.
2026-11-06 21:06:27 +00:00
spark 82d64ad225 fix(sports): keep the stadium and the home club town apart
ci / rust (pull_request) Successful in 8m7s
ci / typescript (pull_request) Failing after 12m18s
The match calendar left Local and Cidade empty. The ground comes from each federation (Liga team/info, UEFA, EHF, FPA) and is stored separately from the town, then copied onto the event when the match is chosen.
2026-11-06 21:06:25 +00:00
spark 25a661ae22 fix(faces): compile the sure-face path and compare kit colour by hue
ci / rust (push) Successful in 6m53s
ci / typescript (push) Failing after 12m9s
Unblock the API deploy and compare kits by hue.
2026-11-06 20:58:44 +00:00
42 changed files with 1009 additions and 112 deletions

No files matched your search

@@ -0,0 +1,3 @@
-- Stadium name and the home club's town are stored apart, so a caption can say both.
ALTER TABLE "sports_teams" ADD COLUMN "city" TEXT;
ALTER TABLE "sports_fixtures" ADD COLUMN "city" TEXT;
+6
View File
@@ -1314,7 +1314,10 @@ model SportsTeam {
/// Lower-case, accent-free name with dashes; codes are derived from it (sl-benfica: b / slb).
slug String
logoUrl String? @map("logo_url")
/// The hall or stadium the club plays at.
venue String?
/// The club's town, kept apart from the stadium name.
city String?
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@ -1380,7 +1383,10 @@ model SportsFixture {
timeKnown Boolean @default(true) @map("time_known")
round String?
matchNumber String? @map("match_number")
/// Stadium or hall, without the town.
venue String?
/// Town of the home club.
city String?
homeScore Int? @map("home_score")
awayScore Int? @map("away_score")
/// FPF and UEFA: when the line-ups were read from the match sheet.
+7
View File
@@ -11,6 +11,7 @@ import { badRequest, conflict, forbidden, notFound } from "../lib/errors.js";
import type { Broadcaster } from "../realtime.js";
import type { SportsService } from "../sports/service.js";
import { officialSigla } from "../sports/fpa-siglas.js";
import { splitStoredPlace } from "../sports/providers.js";
import { claimInbox } from "./adopt.js";
const HOUR = 3600_000;
@@ -173,6 +174,12 @@ export async function registerEventRoutes(app: FastifyInstance, deps: { db: Db;
if (body.photographerIds?.length) await assertMembers(orgId, body.photographerIds);
const { photographerIds, iptcTemplate, ingestFrom, ingestUntil, autopilot, fixtureId, homeTeamId, awayTeamId, ...fields } = body;
const match = await resolveMatch({ fixtureId, homeTeamId, awayTeamId });
if (match.fixtureId && (!fields.venue || !fields.city)) {
const fixture = await db.sportsFixture.findUnique({ where: { id: match.fixtureId }, include: { homeTeam: { select: { venue: true, city: true } } } });
const place = splitStoredPlace(fixture?.venue ?? fixture?.homeTeam.venue ?? null, fixture?.city ?? fixture?.homeTeam.city ?? null);
if (!fields.venue && place.venue) fields.venue = place.venue;
if (!fields.city && place.city) fields.city = place.city;
}
// A second click (the first answer never arrived) must not create the game twice.
if (match.fixtureId) {
const existing = await db.event.findFirst({ where: { organizationId: orgId, fixtureId: match.fixtureId, archivedAt: null }, include, orderBy: { createdAt: "asc" } });
+3 -5
View File
@@ -47,11 +47,10 @@ export async function registerUploadRoutes(
app.post("/v1/orgs/:orgId/uploads", { preHandler: authenticate }, async (req, reply) => {
const { orgId } = OrgParams.parse(req.params);
const query = UploadQuery.parse(req.query);
const { eventId } = query;
// A computer can still name an event that was removed or belongs to somewhere else. Refusing the file
// drops the photo. Ingest keeps the event only when it is this organization's, and otherwise uses the clock.
const eventId = query.eventId;
const membership = await requireMembership(db, req, orgId, "PHOTOGRAPHER");
if (eventId && !(await db.event.findFirst({ where: { id: eventId, organizationId: orgId }, select: { id: true } }))) {
throw badRequest("event_not_in_organization");
}
let uploaderId = currentUserId(req);
if (query.uploaderUserId && query.uploaderUserId !== uploaderId) {
if (ROLE_RANK[membership.role] < ROLE_RANK.INGESTER) throw badRequest("uploader_forbidden");
@@ -191,7 +190,6 @@ export async function registerUploadRoutes(
const membership = await requireMembership(db, req, orgId, "PHOTOGRAPHER");
const name = path.basename(body.name);
if (!ACCEPTED_EXTENSIONS.has(path.extname(name).toLowerCase())) throw new AppError(415, "unsupported_type", "JPEG only for now");
if (body.eventId && !(await db.event.findFirst({ where: { id: body.eventId, organizationId: orgId }, select: { id: true } }))) throw badRequest("event_not_in_organization");
const userId = currentUserId(req);
let uploaderUserId: string | null = null;
if (body.uploaderUserId && body.uploaderUserId !== userId) {
+2 -1
View File
@@ -28,7 +28,8 @@ describe("EHF matches", () => {
away: { name: "FC Porto" },
startsAt: new Date("2026-10-21T16:45:00Z"),
round: "Group Phase A",
venue: "Hala Aleksandar Nikolic, Belgrade",
venue: "Hala Aleksandar Nikolic",
city: "Belgrade",
homeScore: null,
awayScore: 28,
});
+34
View File
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { clubCity, fpaClubPlace, splitStoredPlace } from "./providers.js";
describe("home club place", () => {
it("reads the town from the club's own name or from a stadium that names the town", () => {
expect(clubCity({ fullName: "Associação Académica de Coimbra/OAF, SDUQ, Lda", stadium: "Estádio Cidade de Coimbra" })).toBe("Coimbra");
expect(clubCity({ fullName: "Amarante Futebol Clube SDUQ, Lda", stadium: "Estádio Municipal de Amarante" })).toBe("Amarante");
expect(clubCity({ fullName: "Futebol Clube de Vizela – Futebol, SAD", stadium: "Estádio Futebol Clube de Vizela" })).toBe("Vizela");
expect(clubCity({ fullName: "Futebol Clube do Porto - Futebol, SAD", stadium: "Estádio do Dragão" })).toBe("Porto");
expect(clubCity({ fullName: "Sport Lisboa e Benfica - Futebol, SAD", stadium: "Estádio do Sport Lisboa e Benfica" })).toBe("Lisboa");
expect(clubCity({ fullName: "UDL - União de Leiria - Futebol, SAD", stadium: "Estádio Dr. Magalhães Pessoa" })).toBe("Leiria");
expect(clubCity({ fullName: "Portimonense - Futebol, SAD", stadium: "Portimão Estádio" })).toBe("Portimão");
});
it("does not turn a person's name or the word Portugal into a town", () => {
expect(clubCity({ fullName: "Futebol Clube de Felgueiras - Futebol SAD", stadium: "Estádio Municipal Dr. Machado de Matos" })).toBe("Felgueiras");
expect(clubCity({ fullName: "Sporting Clube de Portugal - Futebol, SAD", stadium: "Estádio José Alvalade" })).toBeNull();
expect(clubCity({ fullName: "Leixões Sport Clube - Futebol, SAD", stadium: "Estádio do Mar" })).toBeNull();
expect(clubCity({ fullName: "Clube Desportivo Feirense - Futebol, SAD", stadium: "Estádio Marcolino Castro" })).toBeNull();
});
it("takes the handball club's town, and not the federation's address", () => {
expect(fpaClubPlace({ CLU_NOME: "Clube Oriental Lisboa", CLU_ABREV: "CLUBE ORIENTAL LISBOA", REC_NOME: "PAV. LOIOS", CLUBE_LOCALIDADE: "Lisboa" })).toEqual({ venue: "PAV. LOIOS", city: "Lisboa" });
expect(fpaClubPlace({ CLU_NOME: "Associacao Desportiva Albicastrense", CLU_ABREV: "AD ALBICASTRENSE", REC_NOME: "MUN. CASTELO BRANCO", CLUBE_LOCALIDADE: "Castelo Branco" })).toEqual({ venue: "MUN. CASTELO BRANCO", city: "Castelo Branco" });
expect(fpaClubPlace({ CLU_NOME: "Federacao Andebol Portugal", CLU_ABREV: "F.A.P.", CLUBE_LOCALIDADE: "Lisboa" })).toBeNull();
expect(fpaClubPlace({ CLU_NOME: "Vitória Sport Clube", CLU_ABREV: "VITÓRIA SC", REC_NOME: "DESP. UNIDADE VIMARANENSE", CLUBE_LOCALIDADE: null })).toEqual({ venue: "DESP. UNIDADE VIMARANENSE", city: null });
});
it("splits a venue that was stored with the town after a comma", () => {
expect(splitStoredPlace("Estádio Dr. Magalhães Pessoa, Leiria", null)).toEqual({ venue: "Estádio Dr. Magalhães Pessoa", city: "Leiria" });
expect(splitStoredPlace("Estádio Cidade de Coimbra", null)).toEqual({ venue: "Estádio Cidade de Coimbra", city: null });
expect(splitStoredPlace("Estádio do Dragão", "Porto")).toEqual({ venue: "Estádio do Dragão", city: "Porto" });
});
});
+137 -8
View File
@@ -19,7 +19,10 @@ export interface TeamData {
name: string;
abbreviation?: string | null;
logoUrl?: string | null;
/** The hall or stadium this club plays at. */
venue?: string | null;
/** The home club's town. Separate from the stadium name: captions use both. */
city?: string | null;
/** FPA: the club the team belongs to (its games and levels are listed per club). Not stored. */
clubId?: string | null;
}
@@ -50,7 +53,10 @@ export interface FixtureData {
timeKnown: boolean;
round?: string | null;
matchNumber?: string | null;
/** Stadium or hall, without the town. */
venue?: string | null;
/** Town of the home club, when the source names it. */
city?: string | null;
homeScore?: number | null;
awayScore?: number | null;
/** The referee team (UEFA publishes it before the match). */
@@ -111,6 +117,55 @@ export function lisbonTime(day: string, time?: string | null): { at: Date; timeK
}
const str = (v: unknown): string | null => (typeof v === "string" && v.trim() ? v.trim() : typeof v === "number" ? String(v) : null);
/** A city named by the club itself: "de Vizela", "Municipal de Amarante", "Sport Lisboa". Not a person's name. */
const PLACE_STOP = new Set(["portugal", "futebol", "sad", "sduq", "lda", "clube", "sport", "sporting", "mar", "campo"]);
function tidyPlace(value: string): string | null {
const place = value.replace(/[/,].*$/, "").replace(/\s+(futebol|sad|sduq|lda)\b.*$/i, "").trim();
if (!place || place.length > 40) return null;
const key = place.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase();
if (PLACE_STOP.has(key)) return null;
return place;
}
export function clubCity(input: { fullName?: string | null; stadium?: string | null }): string | null {
const stadium = (input.stadium ?? "").replace(/\s+/g, " ").trim();
const municipal = /^estádio municipal de\s+(.+)$/i.exec(stadium);
if (municipal && !/^(dr\.?|eng\.?º?|engenheiro|25 de )\b/i.test(municipal[1]!)) {
const city = tidyPlace(municipal[1]!);
if (city) return city;
}
const cidadeDe = /^estádio cidade de\s+(.+)$/i.exec(stadium);
if (cidadeDe) {
const city = tidyPlace(cidadeDe[1]!);
if (city) return city;
}
const leading = /^(.+?)\s+estádio$/i.exec(stadium);
if (leading) {
const city = tidyPlace(leading[1]!);
if (city) return city;
}
const full = input.fullName ?? "";
if (/\bsport lisboa\b/i.test(full) || /\bsport lisboa\b/i.test(stadium)) return "Lisboa";
const matches = [...full.matchAll(/\b(?:de|do|das|dos)\s+([A-ZÁÉÍÓÚÂÊÔÃÕÇÀ][\p{L}'’.-]+)/gu)];
for (let i = matches.length - 1; i >= 0; i--) {
const city = tidyPlace(matches[i]![1]!);
if (city) return city;
}
return null;
}
/** Older rows stored "Estádio, Leiria" in the venue. The comma splits them back into stadium and city. */
export function splitStoredPlace(venue: string | null, city: string | null): { venue: string | null; city: string | null } {
if (city || !venue) return { venue, city };
const cut = venue.lastIndexOf(",");
if (cut < 0) return { venue, city: null };
const left = venue.slice(0, cut).trim();
const right = venue.slice(cut + 1).trim();
if (!left || !right || right.length > 40 || right.split(/\s+/).length > 4) return { venue, city: null };
return { venue: left, city: right };
}
const url = (...vs: unknown[]): string | null => {
for (const v of vs) {
if (typeof v === "string" && /^https:\/\//.test(v.trim())) return v.trim();
@@ -176,9 +231,30 @@ export function clubSeasons(payload: unknown): LigaClubSeason[] {
export class LigaProvider {
static readonly BASE = "https://www.ligaportugal.pt/api/v1";
private static readonly HEADERS = { accept: "application/json", "accept-language": "pt-PT,pt;q=0.9", locale: "pt-PT", "x-client-platform": "web" };
/** Stadium and town, once per club. The calendar and the teams list leave both empty; team/info has the stadium. */
private readonly places = new Map<string, Promise<{ venue: string | null; city: string | null } | null>>();
constructor(private readonly fetcher: Fetch) {}
/** The club's stadium and town. Null when Liga has not published the page. Never throws. */
place(externalId: string, season: string): Promise<{ venue: string | null; city: string | null } | null> {
const cached = this.places.get(externalId);
if (cached) return cached;
const pending = this.readPlace(externalId, season).catch(() => null);
this.places.set(externalId, pending);
return pending;
}
private async readPlace(externalId: string, season: string): Promise<{ venue: string | null; city: string | null } | null> {
const data = (await this.api("team/info", { id: externalId, season })) as Record<string, unknown>;
const stadium = data.stadium && typeof data.stadium === "object" ? (data.stadium as { name?: unknown }) : null;
const venue = str(stadium?.name);
const named = str(data.city);
const city = named || clubCity({ fullName: str(data.fullName), stadium: venue });
if (!venue && !city) return null;
return { venue, city };
}
/** Every season the federation still publishes, with that year's club competitions. */
async seasons(): Promise<LigaClubSeason[]> {
return clubSeasons(await this.api("seasons", {}));
@@ -194,7 +270,15 @@ export class LigaProvider {
async teams(competition: string, season: string): Promise<TeamData[]> {
const list = await this.api("competition/teams", { season, competition });
if (!Array.isArray(list)) throw new Error("liga: unexpected competition/teams");
return list.map(ligaTeam).filter((t): t is TeamData => !!t);
const teams = list.map(ligaTeam).filter((t): t is TeamData => !!t);
for (const team of teams) {
if (team.venue && team.city) continue;
const place = await this.place(team.externalId, season);
if (!place) continue;
team.venue = team.venue ?? place.venue;
team.city = team.city ?? place.city;
}
return teams;
}
/** The players, then the first team's coaching staff (head coach, assistants; the B team's staff is left out). */
@@ -306,6 +390,7 @@ export class LigaProvider {
round: str(f.round) ?? str(f.matchweekNumber),
matchNumber: str(f.fixtureNumber),
venue: str((f.stadium as { name?: unknown } | undefined)?.name) ?? home.venue ?? null,
city: str((f.stadium as { city?: unknown } | undefined)?.city) ?? home.city ?? null,
homeScore: finished && typeof f.homeTeamGoals === "number" ? f.homeTeamGoals : null,
awayScore: finished && typeof f.awayTeamGoals === "number" ? f.awayTeamGoals : null,
});
@@ -326,7 +411,8 @@ function ligaTeam(t: unknown): TeamData | null {
name,
abbreviation: str(o.abbreviation),
logoUrl: url(o.logo, o.image),
venue: str(o.venue) ?? str(o.venueName) ?? str(o.stadium),
venue: (typeof o.stadium === "object" && o.stadium ? str((o.stadium as { name?: unknown }).name) : null) ?? str(o.venue) ?? str(o.venueName) ?? (typeof o.stadium === "string" ? str(o.stadium) : null),
city: str(o.city) || null,
};
}
@@ -364,6 +450,23 @@ export class FpaProvider {
if (this.delayMs) await new Promise((r) => setTimeout(r, this.delayMs));
}
/** The club's hall and town (CLUBE_LOCALIDADE is often empty; the hall is REC_NOME). Never throws. */
async club(clubId: string): Promise<{ venue: string | null; city: string | null } | null> {
const cached = this.clubs.get(clubId);
if (cached) return cached;
const pending = this.readClub(clubId).catch(() => null);
this.clubs.set(clubId, pending);
return pending;
}
private readonly clubs = new Map<string, Promise<{ venue: string | null; city: string | null } | null>>();
private async readClub(clubId: string): Promise<{ venue: string | null; city: string | null } | null> {
const data = await get(this.fetcher, `${FpaProvider.WS}/getClube/${encodeURIComponent(clubId)}`, { accept: "application/json" }, "json");
const row = (Array.isArray(data) ? data[0] : data) as Record<string, unknown> | undefined;
return fpaClubPlace(row);
}
/** An HTML page in whatever charset it declares (the match report is windows-1252). */
private async html(u: string): Promise<string> {
const res = await this.fetcher(u, { headers: FpaProvider.HTML, signal: AbortSignal.timeout(TIMEOUT_MS) });
@@ -744,6 +847,21 @@ export function fpaProva(prova: string): { code: string; name: string } | null {
return m ? { code: m[1]!, name: m[2]!.replace(/\s{2,}/g, " ") } : null;
}
/**
* The club card (`getClube`): the hall is REC_NOME, the town is CLUBE_LOCALIDADE.
* The federation's own card (F.A.P., Lisboa) is not a home club, so a seleção does not inherit that town.
*/
export function fpaClubPlace(row: Record<string, unknown> | null | undefined): { venue: string | null; city: string | null } | null {
if (!row) return null;
const abbrev = str(row.CLU_ABREV) ?? "";
const name = str(row.CLU_NOME) ?? "";
const federation = /^f\.?a\.?p\.?$/i.test(abbrev) || /federa[cç][aã]o/i.test(name);
const venue = str(row.REC_NOME);
const city = federation ? null : str(row.CLUBE_LOCALIDADE);
if (!venue && !city) return null;
return { venue, city };
}
function fpaFixture(r: Record<string, unknown>): FixtureData | null {
const prova = fpaProva(str(r.PROVA) ?? "");
const day = str(r.JOG_DATA);
@@ -768,6 +886,7 @@ function fpaFixture(r: Record<string, unknown>): FixtureData | null {
round: str(r.FASE),
matchNumber: str(r.JOG_NUM_JOGO),
venue: str(r.LOCAL),
city: str(r.CLUBE_LOCALIDADE),
homeScore: goals(r.GOLOS_CASA ?? r.JOG_GOLOS_CASA),
awayScore: goals(r.GOLOS_FORA ?? r.JOG_GOLOS_FORA),
};
@@ -790,6 +909,13 @@ export function fpfDate(text: string, now: Date): { at: Date; timeKnown: boolean
return candidates[0]!;
}
/** FPF prints the stadium, sometimes "Estádio, Cidade". */
function fpfPlace(text: string): { venue: string | null; city: string | null } {
const raw = text.replace(/\s+/g, " ").trim();
if (!raw) return { venue: null, city: null };
return splitStoredPlace(raw, null);
}
export class FpfProvider {
static readonly BASE = "https://resultados.fpf.pt";
private static readonly HEADERS = { accept: "text/html", "accept-language": "pt-PT,pt;q=0.9", "user-agent": "PhotoReport/2 (sports data)" };
@@ -850,7 +976,7 @@ export class FpfProvider {
startsAt: when.at,
timeKnown: when.timeKnown,
round: roundLabel,
venue: r(link).next(".game-list-stadium").find("small").text().trim() || null,
...fpfPlace(r(link).next(".game-list-stadium").find("small").text().trim()),
homeScore: score ? Number(score[1]) : null,
awayScore: score ? Number(score[2]) : null,
});
@@ -964,7 +1090,8 @@ export function uefaFixture(m: Json, competitionId: string, season: string): Fix
startsAt: at,
timeKnown: true,
round: str(obj(m.matchday).longName) ?? str(obj(m.matchday).name) ?? str(obj(obj(m.round).metaData).name),
venue: stadium ? (city ? `${stadium}, ${city}` : stadium) : null,
venue: stadium,
city,
homeScore: goals(total.home),
awayScore: goals(total.away),
officials,
@@ -1131,7 +1258,8 @@ export function ehfFixture(row: unknown, competition: string, season: string): F
startsAt: at,
timeKnown: when.hasTime !== false,
round: round && group ? `${round} ${group}` : round,
venue: hall && city ? `${hall}, ${city}` : (hall ?? city),
venue: hall,
city,
homeScore: goals(obj(m.homeTeam)),
awayScore: goals(obj(m.guestTeam)),
};
@@ -1240,7 +1368,7 @@ export class EhfProvider {
async euroCupMenMatches(
competitionId: string,
contentId: string,
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null }[]> {
): Promise<{ matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[]> {
const data = await get(
this.fetcher,
`https://www.eurohandball.com/umbraco/api/competitionapi/GetStandingMatches?contentId=${encodeURIComponent(contentId)}&competitionId=${encodeURIComponent(competitionId)}`,
@@ -1248,7 +1376,7 @@ export class EhfProvider {
"json",
);
const rows = Array.isArray(obj(data).matches) ? (obj(data).matches as unknown[]) : [];
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null }[] = [];
const out: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[] = [];
for (const row of rows) {
const m = obj(row);
const matchId = str(m.matchID);
@@ -1264,7 +1392,8 @@ export class EhfProvider {
startsAt: at,
homeNation: str(obj(obj(m.homeTeam).team).nationAbbreviation) ?? str(obj(obj(m.homeTeam).team).countryAbbreviation),
awayNation: str(obj(obj(m.guestTeam).team).nationAbbreviation) ?? str(obj(obj(m.guestTeam).team).countryAbbreviation),
venue: hall && city ? `${hall}, ${city}` : (hall ?? city),
venue: hall,
city,
});
}
return out;
+10 -4
View File
@@ -7,6 +7,7 @@ import type { Db } from "../db.js";
import { forbidden, notFound } from "../lib/errors.js";
import { toCsv, toTsv } from "./codegen.js";
import { fixtureTextFilter } from "./fixture-search.js";
import { splitStoredPlace } from "./providers.js";
import type { SportsService } from "./service.js";
const OrgParams = z.object({ orgId: z.uuid() });
@@ -81,6 +82,7 @@ export async function registerSportsRoutes(app: FastifyInstance, deps: { db: Db;
slug: t.slug,
logoUrl: t.logoUrl,
venue: t.venue,
city: t.city,
players: t._count.players,
})),
};
@@ -120,20 +122,24 @@ export async function registerSportsRoutes(app: FastifyInstance, deps: { db: Db;
include: { homeTeam: true, awayTeam: true, competition: true },
});
return {
fixtures: fixtures.map((f) => ({
fixtures: fixtures.map((f) => {
const place = splitStoredPlace(f.venue ?? f.homeTeam.venue, f.city ?? f.homeTeam.city);
return {
id: f.id,
startsAt: f.startsAt,
timeKnown: f.timeKnown,
round: f.round,
matchNumber: f.matchNumber,
venue: f.venue,
venue: place.venue,
city: place.city,
homeScore: f.homeScore,
awayScore: f.awayScore,
sport: f.competition.sport,
competition: { id: f.competition.id, name: f.competition.name, provider: f.competition.provider, code: f.competition.externalId, gender: f.competition.gender },
home: { id: f.homeTeam.id, name: f.homeTeam.name, abbreviation: f.homeTeam.abbreviation, venue: f.homeTeam.venue },
home: { id: f.homeTeam.id, name: f.homeTeam.name, abbreviation: f.homeTeam.abbreviation, venue: f.homeTeam.venue, city: f.homeTeam.city },
away: { id: f.awayTeam.id, name: f.awayTeam.name, abbreviation: f.awayTeam.abbreviation },
})),
};
}),
};
});
+25 -6
View File
@@ -42,6 +42,7 @@ import {
type OfficialData,
type PlayerData,
ProviderHttpError,
splitStoredPlace,
type TeamData,
EHF_COMPETITIONS,
EhfProvider,
@@ -595,7 +596,8 @@ export class SportsService {
startsAt: lisbonTime("2026-11-05", "20:00").at,
timeKnown: true,
round: "Particular",
venue: "Pavilhão Municipal Fernando Lima, Caminha",
venue: "Pavilhão Municipal Fernando Lima",
city: "Caminha",
},
{
externalId: "m19-esp-por-20261107",
@@ -606,7 +608,8 @@ export class SportsService {
startsAt: lisbonTime("2026-11-07", "17:30").at,
timeKnown: true,
round: "Particular",
venue: "Pavilhão Municipal, Salceda de Caselas",
venue: "Pavilhão Municipal",
city: "Salceda de Caselas",
},
];
let n = 0;
@@ -685,7 +688,7 @@ export class SportsService {
*/
private async applyEuroCupSheets(now: Date, season: string, result: RefreshResult): Promise<void> {
const { db, log } = this.deps;
let matches: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null }[];
let matches: { matchId: string; startsAt: Date; homeNation: string | null; awayNation: string | null; venue: string | null; city: string | null }[];
try {
matches = await this.ehf.euroCupMenMatches(EHF_EURO_CUP_MEN.competitionId, EHF_EURO_CUP_MEN.contentId);
} catch (err) {
@@ -717,6 +720,7 @@ export class SportsService {
timeKnown: true,
round: "EHF Euro Cup",
venue: m.venue,
city: m.city,
});
}
const due = matches.filter((m) => Math.abs(m.startsAt.getTime() - now.getTime()) <= EHF_EURO_CUP_MEN.sheetWindowMs);
@@ -1244,6 +1248,7 @@ export class SportsService {
...(t.abbreviation ? { abbreviation: t.abbreviation } : {}),
...(t.logoUrl ? { logoUrl: t.logoUrl } : {}),
...(t.venue ? { venue: t.venue } : {}),
...(t.city ? { city: t.city } : {}),
};
const team = await this.deps.db.sportsTeam.upsert({
where,
@@ -1304,6 +1309,21 @@ export class SportsService {
private async saveFixture(c: SportsCompetition, provider: SportsProvider, f: FixtureData, sport?: string): Promise<number> {
const homeTeamId = await this.upsertTeam(provider, f.home, sport);
const awayTeamId = await this.upsertTeam(provider, f.away, sport);
let place = splitStoredPlace(f.venue ?? null, f.city ?? null);
if (provider === "FPA" && f.home.clubId && !place.city) {
const club = await this.fpa.club(f.home.clubId);
if (club?.city) {
place = { ...place, city: club.city };
await this.deps.db.sportsTeam.updateMany({ where: { id: homeTeamId, OR: [{ city: null }, { city: "" }] }, data: { city: club.city } });
}
if (club?.venue) {
await this.deps.db.sportsTeam.updateMany({ where: { id: homeTeamId, venue: null }, data: { venue: club.venue } });
}
}
if (!place.venue || !place.city) {
const home = await this.deps.db.sportsTeam.findUnique({ where: { id: homeTeamId }, select: { venue: true, city: true } });
place = { venue: place.venue ?? home?.venue ?? null, city: place.city ?? home?.city ?? null };
}
const data = {
season: f.season,
homeTeamId,
@@ -1317,11 +1337,10 @@ export class SportsService {
...(f.officials?.length ? { officials: f.officials as unknown as object } : {}),
};
// A sheet that does not name a hall must not wipe a venue we already stored (the youth article has none).
const venue = f.venue ?? null;
await this.deps.db.sportsFixture.upsert({
where: { competitionId_externalId: { competitionId: c.id, externalId: f.externalId } },
create: { competitionId: c.id, externalId: f.externalId, ...data, venue },
update: { ...data, ...(venue ? { venue } : {}) },
create: { competitionId: c.id, externalId: f.externalId, ...data, venue: place.venue, city: place.city },
update: { ...data, ...(place.venue ? { venue: place.venue } : {}), ...(place.city ? { city: place.city } : {}) },
});
return 1;
}
+3 -2
View File
@@ -693,7 +693,7 @@ describe("sports data service", () => {
]);
// The next match's sheet is not out yet: read again around kick-off.
const next = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "2050091" } });
expect(next).toMatchObject({ round: "Matchday 2", venue: "Estádio Dr. Magalhães Pessoa, Leiria", lineupAt: null });
expect(next).toMatchObject({ round: "Matchday 2", venue: "Estádio Dr. Magalhães Pessoa", city: "Leiria", lineupAt: null });
expect((next.officials as { role: string }[]).map((o) => o.role)).toContain("REFEREE");
const token = (await login(ctx.app, user.email)).body.accessToken;
@@ -839,7 +839,8 @@ describe("sports data service", () => {
expect(friendly?.homeTeam.externalId).toBe("M19");
expect(friendly?.awayTeam.externalId).toBe("ESP-M19");
expect(friendly?.startsAt.toISOString()).toBe("2026-11-05T20:00:00.000Z");
expect(friendly?.venue).toBe("Pavilhão Municipal Fernando Lima, Caminha");
expect(friendly?.venue).toBe("Pavilhão Municipal Fernando Lima");
expect(friendly?.city).toBe("Caminha");
});
});
+6 -3
View File
@@ -8,9 +8,10 @@ const EVERY_MS = 4_000;
/**
* Desktop only: while signed in, notice Lightroom / Photo Mechanic soft-crop writes on local originals
* and apply them as develop crops (same path as cropping in Revelar — including autopilot learning).
* A colour class Photo Mechanic paints on the same file is copied onto the library photo.
*/
export function SoftCropWatch({ enabled = isDesktop(), everyMs = EVERY_MS }: { enabled?: boolean; everyMs?: number }) {
const { organization } = useAuth();
const { api, organization } = useAuth();
const orgId = organization?.id;
useEffect(() => {
if (!enabled || !orgId) return;
@@ -18,7 +19,9 @@ export function SoftCropWatch({ enabled = isDesktop(), everyMs = EVERY_MS }: { e
let timer: ReturnType<typeof setTimeout> | undefined;
const tick = async () => {
try {
await reconcileSoftCrops();
await reconcileSoftCrops(async (id, photoId, color) => {
await api.updatePhotos(id, [photoId], { colorLabel: color });
});
} catch {
/* older desktop without local_stat, or offline index miss */
}
@@ -29,6 +32,6 @@ export function SoftCropWatch({ enabled = isDesktop(), everyMs = EVERY_MS }: { e
alive = false;
clearTimeout(timer);
};
}, [orgId, enabled, everyMs]);
}, [api, orgId, enabled, everyMs]);
return null;
}
+14 -2
View File
@@ -1,4 +1,4 @@
import { libraryMarksFromXmp, xmpPacketFromJpeg } from "@photoreport/metadata";
import { colorClassFromXmp, libraryMarksFromXmp, xmpPacketFromJpeg } from "@photoreport/metadata";
import type { ApiClient } from "@photoreport/sdk";
import { desktopInvoke, isDesktop } from "../platform.js";
@@ -15,6 +15,8 @@ export interface WatchedDelivery {
orgId: string;
/** Last mtime we already reconciled (ms). */
seenAt: number;
/** Colour last copied from this file. */
color?: string | undefined;
}
function load(): WatchedDelivery[] {
@@ -96,6 +98,16 @@ export async function reconcileLightroomMarks(api: ApiClient): Promise<number> {
continue;
}
const marks = libraryMarksFromXmp(xmp);
const color = colorClassFromXmp(xmp);
if (color && color !== row.color) {
try {
await api.updatePhotos(row.orgId, [row.photoId], { colorLabel: color });
row.color = color;
} catch {
next.push(row);
continue;
}
}
if (marks.flag === "REJECT") {
try {
await deleteDeliveredFile(row.path);
@@ -107,7 +119,7 @@ export async function reconcileLightroomMarks(api: ApiClient): Promise<number> {
continue;
}
}
next.push({ ...row, seenAt: Date.now() });
next.push({ ...row, seenAt: Date.now(), color: row.color });
}
save(next);
return rejected;
+16 -8
View File
@@ -12,6 +12,21 @@ function asBytes(data: unknown): Uint8Array | null {
return null;
}
/** The XMP text of a local original (sidecar, else the packet in the JPEG). Null when this computer has no file. */
export async function localXmpText(sha256: string): Promise<string | null> {
if (!isDesktop() || !sha256) return null;
try {
const raw = await desktopInvoke<unknown>("local_xmp", { sha256 });
const bytes = asBytes(raw);
if (!bytes?.length) return null;
const text = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
if (text.includes("<x:xmpmeta") || text.includes("crs:Crop") || text.includes("ColorClass") || text.includes("xmp:Label")) return text;
return xmpPacketFromJpeg(bytes);
} catch {
return null;
}
}
/**
* Soft crop embedded in the original on this computer (crs:Crop*), the same block Photo Mechanic reads.
* Cached per SHA-256. Null in the browser, when the file is missing, or when there is no crop.
@@ -23,14 +38,7 @@ export async function softCropFor(sha256: string): Promise<SoftCrop | null> {
if (pending) return pending;
const work = (async () => {
try {
const raw = await desktopInvoke<unknown>("local_xmp", { sha256 });
const bytes = asBytes(raw);
if (!bytes?.length) {
cache.set(sha256, null);
return null;
}
const text = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
const xmp = text.includes("<x:xmpmeta") || text.includes("crs:Crop") ? text : xmpPacketFromJpeg(bytes);
const xmp = await localXmpText(sha256);
const crop = xmp ? cropFromXmp(xmp) : null;
cache.set(sha256, crop);
return crop;
+28 -7
View File
@@ -1,7 +1,7 @@
import type { SoftCrop } from "@photoreport/metadata";
import { colorClassFromXmp, cropFromXmp, type SoftCrop, type XmpColor } from "@photoreport/metadata";
import { desktopInvoke, isDesktop } from "../platform.js";
import { offlineQueue } from "../offline/queue.js";
import { forgetSoftCrop, softCropFor } from "./softCrop.js";
import { forgetSoftCrop, localXmpText } from "./softCrop.js";
/**
* Watch local originals for soft-crop changes written outside this app (Lightroom / Photo Mechanic).
@@ -22,6 +22,8 @@ export interface WatchedSoftCrop {
fingerprint: string;
/** Ignore file changes until this instant (our own sidecar write). */
ownWriteUntil: number;
/** Colour last copied from this file, so a repaint in Photo Mechanic is applied once. "" means the file named none. */
color?: string | undefined;
}
/** Return true when the crop was applied into an open develop session (skip a second queue write). */
@@ -97,11 +99,15 @@ function cropsEqual(a: SoftCrop, b: SoftCrop): boolean {
return softCropFingerprint(a) === softCropFingerprint(b);
}
/** Apply a colour Photo Mechanic wrote into the original. */
export type ApplyExternalColor = (orgId: string, photoId: string, color: XmpColor) => Promise<void>;
/**
* One pass: re-read soft crops whose file (or sidecar) mtime moved, apply as develop crop when the
* rectangle changed. Returns how many photos received a new crop.
* rectangle changed, and copy a colour class Photo Mechanic wrote onto the library photo.
* Returns how many photos received a new crop.
*/
export async function reconcileSoftCrops(): Promise<number> {
export async function reconcileSoftCrops(applyColor?: ApplyExternalColor): Promise<number> {
if (!isDesktop()) return 0;
const rows = load();
if (!rows.length) return 0;
@@ -114,7 +120,9 @@ export async function reconcileSoftCrops(): Promise<number> {
next.push(row);
continue;
}
if (stat.mtimeMs && stat.mtimeMs === row.mtimeMs) {
// A row saved before colours were copied has no `color`. Read it once even if the mtime is already known,
// so a colour painted earlier still arrives. "" means we looked and the file names no colour.
if (stat.mtimeMs && stat.mtimeMs === row.mtimeMs && row.color !== undefined) {
next.push(row);
continue;
}
@@ -123,10 +131,22 @@ export async function reconcileSoftCrops(): Promise<number> {
continue;
}
forgetSoftCrop(row.sha256);
const crop = await softCropFor(row.sha256);
const xmp = await localXmpText(row.sha256);
const crop = xmp ? cropFromXmp(xmp) : null;
const color = xmp ? colorClassFromXmp(xmp) : null;
let colorApplied = color ? row.color : (row.color ?? "");
if (color && color !== row.color && applyColor) {
try {
await applyColor(row.orgId, row.photoId, color);
colorApplied = color;
} catch {
next.push(row);
continue;
}
}
const fingerprint = softCropFingerprint(crop);
if (!crop || fingerprint === row.fingerprint) {
next.push({ ...row, mtimeMs: stat.mtimeMs || row.mtimeMs, fingerprint });
next.push({ ...row, mtimeMs: stat.mtimeMs || row.mtimeMs, fingerprint, color: colorApplied });
continue;
}
const command = {
@@ -147,6 +167,7 @@ export async function reconcileSoftCrops(): Promise<number> {
...row,
mtimeMs: stat.mtimeMs || row.mtimeMs,
fingerprint,
color: colorApplied,
ownWriteUntil: now + OWN_WRITE_GRACE_MS,
});
}
+16 -1
View File
@@ -100,6 +100,21 @@ export const t = {
starsAtLeast: "Estrelas (pelo menos)",
starsOrMore: (n: number) => (n === 1 ? "1 estrela ou mais" : `${n} estrelas ou mais`),
colorLabel: "Cor",
markColor: "Marcar",
colorOnly: (name: string) => `Só ${name.toLowerCase()}`,
colorWithout: (name: string) => `Sem ${name.toLowerCase()}`,
colorUncolored: "Só sem cor",
colorNone: "Sem cor",
menuSelectColor: (name: string) => `Selecionar ${name.toLowerCase()}`,
dropPartial: "O arrasto não trouxe o lote todo. Escolhe as fotografias aqui.",
dropChoose: "Escolher fotografias",
menuSelection: "Seleção",
menuSelectAll: "Selecionar todas",
menuSelectNone: "Limpar seleção",
menuSelectUncolored: "Selecionar sem cor",
menuImage: "Imagem",
menuSetColor: "Definir cor",
menuSetRating: "Definir estrelas",
colors: { RED: "Vermelho", YELLOW: "Amarelo", GREEN: "Verde", BLUE: "Azul", PURPLE: "Roxo" },
deliveryFilter: "Envio:",
deliveryStates: { any: "Todas", unsent: "Por enviar", queued: "A enviar", sent: "Enviadas", failed: "Com erro" },
@@ -129,7 +144,7 @@ export const t = {
setUpDelivery: "Configurar envio",
noTargetsHelp: "Ainda não há destinos de envio (FTP da agência, pasta, etc.). Cria um em Entregar.",
deliveryBadge: { QUEUED: "A enviar", DONE: "Enviada", FAILED: "Envio falhou" },
shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · Delete tirar do evento · I informação · E/Enter lupa · G/Esc grelha · D revelar · R recortar · W conta-gotas · Ctrl+Alt+2 revelar · Photo Mechanic: T marcar · Cmd+1–5 cor · Ctrl+1–5 estrelas (Windows: Ctrl cor, Alt estrelas)",
shortcuts: "P escolher · X rejeitar · U limpar · 0–5 estrelas · 6–9 cor · arrastar seleciona várias · Delete tirar do evento · I informação · E/Enter lupa · G/Esc grelha · D revelar · R recortar · W conta-gotas · Ctrl+Alt+2 revelar · Photo Mechanic: T marcar · Cmd+1–5 cor · Ctrl+1–5 estrelas (Windows: Ctrl cor, Alt estrelas)",
selected: (n: number) => (n === 1 ? "1 selecionada" : `${n} selecionadas`),
ofTotal: (n: number, total: number) => `${n} de ${total}`,
players: "Jogadores",
+1
View File
@@ -89,6 +89,7 @@ export function EventForm({ api, orgId, onClose, onCreated }: { api: ApiClient;
home: teamDisplayName(f.home.name),
away: teamDisplayName(f.away.name),
venue: f.venue ?? f.home.venue ?? values.venue ?? "",
city: f.city ?? f.home.city ?? values.city ?? "",
sport: f.sport,
competition: f.competition.name,
competitionCode: f.competition.provider === "FPA" ? f.competition.code : (values.competitionCode ?? ""),
+33 -12
View File
@@ -1,7 +1,7 @@
import type { ColorLabel } from "@photoreport/contracts";
import { t } from "../i18n.js";
import { LABEL_COLOR } from "./Grid.js";
import { ALL_PHOTOS, isAll, type LibraryFilter } from "./store.js";
import { ALL_PHOTOS, cycleColor, isAll, onlyUncolored, type LibraryFilter } from "./store.js";
const FLAGS: LibraryFilter["flag"][] = ["all", "PICK", "UNFLAGGED", "UNREJECTED", "REJECT"];
const DELIVERY: LibraryFilter["delivery"][] = ["any", "unsent", "queued", "sent", "failed"];
@@ -40,17 +40,38 @@ export function FilterBar(props: { filter: LibraryFilter; onChange: (f: LibraryF
))}
</span>
<span className="flex items-center gap-1" role="group" aria-label={t.colorLabel}>
{COLORS.map((c) => (
<button
key={c}
onClick={() => set({ color: f.color === c ? null : c })}
aria-pressed={f.color === c}
aria-label={t.colors[c]}
title={t.colors[c]}
className={`h-3 w-3 rounded-[2px] ${f.color === c ? "outline outline-1 outline-offset-1 outline-white" : "opacity-60 hover:opacity-100"}`}
style={{ background: LABEL_COLOR[c] ?? undefined }}
/>
))}
{COLORS.map((c) => {
const on = f.color === c;
const hiding = on && f.withoutColor;
return (
<button
key={c}
onClick={() => set(cycleColor(f, c))}
aria-pressed={on}
aria-label={hiding ? t.colorWithout(t.colors[c]) : on ? t.colorOnly(t.colors[c]) : t.colors[c]}
title={hiding ? t.colorWithout(t.colors[c]) : on ? t.colorOnly(t.colors[c]) : t.colors[c]}
className={`relative h-5 w-6 rounded-[2px] ${on ? "outline outline-2 outline-offset-1 outline-white" : "opacity-80 hover:opacity-100"}`}
style={{ background: LABEL_COLOR[c] ?? undefined }}
>
{hiding && <span aria-hidden="true" className="absolute left-1/2 top-[-3px] h-[18px] w-px -translate-x-1/2 rotate-45 bg-white" />}
</button>
);
})}
<button
type="button"
onClick={() => set(onlyUncolored(f))}
aria-pressed={f.uncolored}
aria-label={t.colorUncolored}
title={t.colorUncolored}
className={`flex h-5 items-center gap-1 rounded-[2px] border border-dotted px-1.5 text-[11px] ${f.uncolored ? "border-white bg-[#1a1a1a] text-ink outline outline-2 outline-offset-1 outline-white" : "border-faint bg-[#2a2a2a] text-muted hover:text-ink"}`}
>
<span aria-hidden="true" className="h-3 w-3 rounded-[1px] border border-dotted border-current" />
{t.colorNone}
</button>
{f.uncolored && <span className="text-ink">{t.colorUncolored}</span>}
{f.color && !f.uncolored && (
<span className="text-ink">{f.withoutColor ? t.colorWithout(t.colors[f.color]) : t.colorOnly(t.colors[f.color])}</span>
)}
</span>
{!compact && <span aria-hidden="true" className="text-line">|</span>}
{!compact && (
+80 -2
View File
@@ -70,7 +70,7 @@ const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, o
aria-pressed={selected}
aria-label={`${photo.name}${photo.flag === "PICK" ? ", escolhida" : photo.flag === "REJECT" ? ", rejeitada" : ""}${photo.rating ? `, ${photo.rating} estrelas` : ""}`}
className={`relative flex aspect-square flex-col items-center justify-between gap-1 border px-2 pb-1 pt-4 ${
selected ? "border-[#9a9a9a] bg-cell-on" : "border-[#151516] bg-cell hover:bg-[#444445]"
selected ? "border-white bg-cell-on shadow-[inset_0_0_0_2px_#fff]" : "border-[#151516] bg-cell hover:bg-[#444445]"
} ${focused ? "outline outline-1 outline-offset-[-3px] outline-white/60" : ""} ${photo.flag === "REJECT" ? "opacity-40" : ""}`}
>
<span aria-hidden="true" className="absolute left-2 top-0.5 font-mono text-xl font-bold text-white/[0.08]">
@@ -125,6 +125,27 @@ const Cell = memo(function Cell({ photo, index, src, orgId, selected, focused, o
);
});
const DRAG_PX = 5;
interface DragSelect {
x: number;
y: number;
additive: boolean;
base: string[];
moved: boolean;
}
function idsInside(root: HTMLElement, rect: DOMRect): string[] {
const ids: string[] = [];
root.querySelectorAll<HTMLElement>("[data-photo-id]").forEach((node) => {
const box = node.getBoundingClientRect();
const hit = box.left < rect.right && box.right > rect.left && box.top < rect.bottom && box.bottom > rect.top;
const id = node.dataset.photoId;
if (hit && id) ids.push(id);
});
return ids;
}
export function Grid(props: {
photos: PhotoSummary[];
selected: ReadonlySet<string>;
@@ -134,14 +155,71 @@ export function Grid(props: {
onPick: (id: string, e: React.MouseEvent) => void;
onOpen: (id: string) => void;
onMenu?: (id: string, e: React.MouseEvent) => void;
/** Drag a rectangle across the sheet, as in Photo Mechanic. Replaces the selection, or adds to it with Shift/Cmd. */
onSelectMany?: (ids: string[], focus: string | null) => void;
}) {
const root = useRef<HTMLElement>(null);
const drag = useRef<DragSelect | null>(null);
const swallowClick = useRef(false);
const [band, setBand] = useState<{ left: number; top: number; width: number; height: number } | null>(null);
const moveBand = (e: React.PointerEvent) => {
const current = drag.current;
const section = root.current;
if (!current || !section || !props.onSelectMany) return;
const dx = e.clientX - current.x;
const dy = e.clientY - current.y;
if (!current.moved && Math.hypot(dx, dy) < DRAG_PX) return;
current.moved = true;
const left = Math.min(current.x, e.clientX);
const top = Math.min(current.y, e.clientY);
const width = Math.abs(e.clientX - current.x);
const height = Math.abs(e.clientY - current.y);
setBand({ left, top, width, height });
const hit = idsInside(section, new DOMRect(left, top, width, height));
const ids = current.additive ? [...current.base, ...hit] : hit;
props.onSelectMany(ids, hit[hit.length - 1] ?? ids[ids.length - 1] ?? null);
};
return (
<section
ref={root}
aria-label="Grelha"
className="grid content-start gap-1 p-1.5"
className="relative grid content-start gap-1 p-1.5"
style={{ gridTemplateColumns: "repeat(auto-fill, minmax(168px, 1fr))" }}
onContextMenu={(e) => e.preventDefault()}
onPointerDown={(e) => {
if (e.button !== 0 || !props.onSelectMany) return;
drag.current = {
x: e.clientX,
y: e.clientY,
additive: e.shiftKey || e.metaKey || e.ctrlKey,
base: [...props.selected],
moved: false,
};
e.currentTarget.setPointerCapture(e.pointerId);
}}
onPointerMove={moveBand}
onPointerUp={(e) => {
if (drag.current?.moved) swallowClick.current = true;
drag.current = null;
setBand(null);
if (e.currentTarget.hasPointerCapture(e.pointerId)) e.currentTarget.releasePointerCapture(e.pointerId);
}}
onClickCapture={(e) => {
if (!swallowClick.current) return;
swallowClick.current = false;
e.preventDefault();
e.stopPropagation();
}}
>
{band && (
<span
aria-hidden="true"
className="pointer-events-none fixed z-40 border border-white/80 bg-white/10"
style={{ left: band.left, top: band.top, width: band.width, height: band.height }}
/>
)}
{props.photos.map((photo, index) => (
<Cell
key={photo.id}
+150
View File
@@ -0,0 +1,150 @@
import type { ColorLabel } from "@photoreport/contracts";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { t } from "../i18n.js";
import { LABEL_COLOR } from "./Grid.js";
const COLORS = ["NONE", "RED", "YELLOW", "GREEN", "BLUE", "PURPLE"] as const satisfies readonly ColorLabel[];
type OpenMenu = "selection" | "image" | null;
/**
* Selection and colour commands that the macOS menu bar does not offer (that bar is the webview's
* Cut / Copy / Paste). Acts on the photos in the grid, the same way Photo Mechanic's Image menu does.
*/
export function LibraryMenus(props: {
canEdit: boolean;
hasSelection: boolean;
canRemove: boolean;
onSelectAll: () => void;
onSelectNone: () => void;
onSelectUncolored: () => void;
onSelectColor: (color: ColorLabel) => void;
onColor: (color: ColorLabel) => void;
onRating: (rating: number) => void;
onFlag: (flag: "PICK" | "REJECT" | "NONE") => void;
onInfo: () => void;
onRemove: () => void;
}) {
const [open, setOpen] = useState<OpenMenu>(null);
const root = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const onDown = (e: MouseEvent) => {
if (root.current && !root.current.contains(e.target as Node)) setOpen(null);
};
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setOpen(null);
};
window.addEventListener("mousedown", onDown);
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("mousedown", onDown);
window.removeEventListener("keydown", onKey);
};
}, [open]);
const run = (fn: () => void) => {
setOpen(null);
fn();
};
return (
<div ref={root} className="flex items-center gap-1">
<MenuButton label={t.menuSelection} pressed={open === "selection"} onClick={() => setOpen(open === "selection" ? null : "selection")}>
{open === "selection" && (
<MenuPanel>
<Item label={t.menuSelectAll} onSelect={() => run(props.onSelectAll)} />
<Item label={t.menuSelectNone} onSelect={() => run(props.onSelectNone)} />
<Item label={t.menuSelectUncolored} onSelect={() => run(props.onSelectUncolored)} />
{COLORS.filter((c) => c !== "NONE").map((c) => (
<Item key={c} label={t.menuSelectColor(t.colors[c])} swatch={LABEL_COLOR[c] ?? undefined} onSelect={() => run(() => props.onSelectColor(c))} />
))}
</MenuPanel>
)}
</MenuButton>
<MenuButton label={t.menuImage} pressed={open === "image"} onClick={() => setOpen(open === "image" ? null : "image")}>
{open === "image" && (
<MenuPanel>
<p className="px-3 pb-1 pt-1 text-[11px] text-faint">{t.menuSetColor}</p>
{COLORS.map((c) => (
<Item
key={c}
label={c === "NONE" ? t.colorNone : t.colors[c]}
disabled={!props.canEdit || !props.hasSelection}
swatch={c === "NONE" ? "none" : (LABEL_COLOR[c] ?? undefined)}
onSelect={() => run(() => props.onColor(c))}
/>
))}
<p className="px-3 pb-1 pt-2 text-[11px] text-faint">{t.menuSetRating}</p>
<div className="flex gap-1 px-3 pb-1">
{[0, 1, 2, 3, 4, 5].map((n) => (
<button
key={n}
type="button"
disabled={!props.canEdit || !props.hasSelection}
className="text-[13px] text-star disabled:opacity-40"
onClick={() => run(() => props.onRating(n))}
>
{n === 0 ? "0" : "★"}
</button>
))}
</div>
<Item label={t.photoMenuPick} disabled={!props.canEdit || !props.hasSelection} onSelect={() => run(() => props.onFlag("PICK"))} />
<Item label={t.photoMenuReject} disabled={!props.canEdit || !props.hasSelection} onSelect={() => run(() => props.onFlag("REJECT"))} />
<Item label={t.photoMenuClear} disabled={!props.canEdit || !props.hasSelection} onSelect={() => run(() => props.onFlag("NONE"))} />
<Item label={t.photoMenuInfo} disabled={!props.canEdit || !props.hasSelection} onSelect={() => run(props.onInfo)} />
{props.canRemove && (
<Item label={t.photoMenuRemove} danger disabled={!props.canEdit || !props.hasSelection} onSelect={() => run(props.onRemove)} />
)}
</MenuPanel>
)}
</MenuButton>
</div>
);
}
function MenuButton(props: { label: string; pressed: boolean; onClick: () => void; children: ReactNode }) {
return (
<div className="relative">
<button
type="button"
aria-expanded={props.pressed}
aria-haspopup="menu"
onClick={props.onClick}
className={`h-6 border border-black px-2 text-[12px] ${props.pressed ? "bg-cell-on text-ink" : "bg-cell text-ink hover:bg-cell-on"}`}
>
{props.label}
</button>
{props.children}
</div>
);
}
function MenuPanel(props: { children: ReactNode }) {
return (
<div role="menu" className="absolute left-0 top-7 z-40 min-w-[200px] border border-line bg-panel py-1 shadow-xl">
{props.children}
</div>
);
}
function Item(props: { label: string; disabled?: boolean; danger?: boolean; swatch?: string; onSelect: () => void }) {
return (
<button
type="button"
role="menuitem"
disabled={props.disabled}
className={`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[13px] disabled:opacity-40 ${
props.danger ? "text-danger hover:bg-[#3a2020]" : "text-ink hover:bg-cell-on"
}`}
onClick={() => {
if (props.disabled) return;
props.onSelect();
}}
>
{props.swatch === "none" && <span className="h-2.5 w-2.5 rounded-[2px] border border-dotted border-faint" />}
{props.swatch && props.swatch !== "none" && <span className="h-2.5 w-2.5 rounded-[2px]" style={{ background: props.swatch }} />}
{props.label}
</button>
);
}
+47 -1
View File
@@ -1,5 +1,9 @@
import type { ColorLabel } from "@photoreport/contracts";
import { useEffect, useRef } from "react";
import { t } from "../i18n.js";
import { LABEL_COLOR } from "./Grid.js";
const COLORS = ["NONE", "RED", "YELLOW", "GREEN", "BLUE", "PURPLE"] as const satisfies readonly ColorLabel[];
export interface PhotoMenuAction {
id: string;
@@ -15,6 +19,8 @@ export function PhotoContextMenu(props: {
y: number;
actions: PhotoMenuAction[];
onClose: () => void;
onColor?: (color: ColorLabel) => void;
onRating?: (rating: number) => void;
}) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
@@ -37,7 +43,7 @@ export function PhotoContextMenu(props: {
}, [props.onClose]);
// Keep the menu on screen.
const left = Math.min(props.x, typeof window !== "undefined" ? window.innerWidth - 220 : props.x);
const top = Math.min(props.y, typeof window !== "undefined" ? window.innerHeight - props.actions.length * 32 - 16 : props.y);
const top = Math.min(props.y, typeof window !== "undefined" ? window.innerHeight - props.actions.length * 32 - 88 : props.y);
return (
<div
ref={ref}
@@ -46,6 +52,46 @@ export function PhotoContextMenu(props: {
className="fixed z-[60] min-w-[200px] border border-line bg-panel py-1 shadow-xl"
style={{ left, top }}
>
{(props.onColor || props.onRating) && (
<div className="border-b border-line px-3 py-2">
{props.onColor && (
<div className="flex items-center gap-1" role="group" aria-label={t.menuSetColor}>
{COLORS.map((c) => (
<button
key={c}
type="button"
title={c === "NONE" ? t.colorNone : t.colors[c]}
aria-label={c === "NONE" ? t.colorNone : t.colors[c]}
className={c === "NONE" ? "h-5 w-5 rounded-[2px] border border-dotted border-faint" : "h-5 w-5 rounded-[2px]"}
style={c === "NONE" ? undefined : { background: LABEL_COLOR[c] ?? undefined }}
onClick={() => {
props.onColor?.(c);
props.onClose();
}}
/>
))}
</div>
)}
{props.onRating && (
<div className="mt-1.5 flex items-center gap-1" role="group" aria-label={t.menuSetRating}>
{[0, 1, 2, 3, 4, 5].map((n) => (
<button
key={n}
type="button"
className="px-0.5 text-[14px] text-star"
aria-label={String(n)}
onClick={() => {
props.onRating?.(n);
props.onClose();
}}
>
{n === 0 ? "0" : "★"}
</button>
))}
</div>
)}
</div>
)}
{props.actions.map((a) => (
<button
key={a.id}
+54
View File
@@ -0,0 +1,54 @@
import type { ColorLabel } from "@photoreport/contracts";
import { t } from "../i18n.js";
import { LABEL_COLOR } from "./Grid.js";
const COLORS = ["NONE", "RED", "YELLOW", "GREEN", "BLUE", "PURPLE"] as const satisfies readonly ColorLabel[];
/** The row that appears as soon as photos are selected: colour, stars and flag, on the whole selection. */
export function SelectionBar(props: {
count: number;
onColor: (color: ColorLabel) => void;
onRating: (rating: number) => void;
onFlag: (flag: "PICK" | "REJECT" | "NONE") => void;
}) {
return (
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 border-b border-line bg-panel px-3 py-1.5 text-[12px]">
<span className="font-semibold text-ink">{t.selected(props.count)}</span>
<span className="flex items-center gap-1" role="group" aria-label={t.menuSetColor}>
{COLORS.map((c) => (
<button
key={c}
type="button"
title={c === "NONE" ? t.colorNone : t.colors[c]}
aria-label={c === "NONE" ? t.colorNone : t.colors[c]}
onClick={() => props.onColor(c)}
className={
c === "NONE"
? "flex h-6 items-center gap-1 rounded-[2px] border border-dotted border-faint px-1.5 text-muted hover:border-white hover:text-ink"
: "h-6 w-7 rounded-[2px] hover:outline hover:outline-2 hover:outline-offset-1 hover:outline-white"
}
style={c === "NONE" ? undefined : { background: LABEL_COLOR[c] ?? undefined }}
>
{c === "NONE" ? t.colorNone : null}
</button>
))}
</span>
<span className="flex items-center gap-0.5" role="group" aria-label={t.menuSetRating}>
{[0, 1, 2, 3, 4, 5].map((n) => (
<button key={n} type="button" className="px-0.5 text-[15px] text-star" aria-label={String(n)} onClick={() => props.onRating(n)}>
{n === 0 ? "0" : "★"}
</button>
))}
</span>
<button type="button" className="h-6 border border-black bg-cell px-2 text-ink hover:bg-cell-on" onClick={() => props.onFlag("PICK")}>
{t.photoMenuPick}
</button>
<button type="button" className="h-6 border border-black bg-cell px-2 text-ink hover:bg-cell-on" onClick={() => props.onFlag("REJECT")}>
{t.photoMenuReject}
</button>
<button type="button" className="h-6 border border-black bg-cell px-2 text-ink hover:bg-cell-on" onClick={() => props.onFlag("NONE")}>
{t.photoMenuClear}
</button>
</div>
);
}
+3 -1
View File
@@ -53,7 +53,9 @@ export function savedFilter(orgId: string): LibraryFilter {
return {
flag: FLAGS.includes(v.flag as string) ? v.flag! : "all",
minRating: Number.isInteger(v.minRating) && v.minRating! >= 0 && v.minRating! <= 5 ? v.minRating! : 0,
color: COLORS.includes(v.color as string) ? v.color! : null,
color: v.uncolored === true || !COLORS.includes(v.color as string) ? null : v.color!,
withoutColor: v.uncolored !== true && v.withoutColor === true && COLORS.includes(v.color as string),
uncolored: v.uncolored === true,
delivery: DELIVERY.includes(v.delivery as string) ? v.delivery! : "any",
noPlayers: v.noPlayers === true,
};
+14
View File
@@ -16,6 +16,20 @@ describe("folder drop", () => {
expect(opened).toEqual(["/tmp/job"]);
});
it("uploads every loose file the shell can read", async () => {
const sent: string[] = [];
const wait = beginDropWait();
nativePaths(
["/tmp/a.jpg", "/tmp/b.jpg"],
async () => null,
() => {},
async (paths) => paths.map((path) => new File([path], path.split("/").pop()!)),
(files) => sent.push(...files.map((file) => file.name)),
);
await expect(wait).resolves.toBe("native");
expect(sent).toEqual(["a.jpg", "b.jpg"]);
});
it("leaves loose files to the upload", async () => {
const opened: string[] = [];
const wait = beginDropWait();
+32 -4
View File
@@ -11,7 +11,7 @@ export interface FolderListing {
files: FolderFile[];
}
type Kind = "folder" | "files";
type Kind = "folder" | "files" | "native";
interface Gate {
promise: Promise<Kind>;
@@ -66,18 +66,34 @@ export function nativePaths(
paths: string[],
isFolder: (paths: string[]) => Promise<string | null>,
open: (path: string) => void,
/**
* Loose files. Return the photos to upload. An empty list (an older shell that cannot read the drop)
* falls back to the page's own file list, which may contain only a few of them.
*/
readFiles?: (paths: string[]) => Promise<File[]>,
upload?: (files: File[]) => void,
): void {
nativeSeen = true;
const current = takeGate();
clearTimeout(current.timer);
void isFolder(paths)
.then((folder) => {
.then(async (folder) => {
if (folder) {
finish("folder");
open(folder);
} else {
finish("files");
return;
}
if (!readFiles) {
finish("files");
return;
}
const files = await readFiles(paths).catch(() => [] as File[]);
if (!files.length) {
finish("files");
return;
}
finish("native");
upload?.(files);
})
.catch(() => finish("files"));
}
@@ -104,6 +120,18 @@ export function folderDropPath(paths: string[], invoke: Invoke = desktopInvoke):
return invoke<string | null>("folder_drop", { paths });
}
/** Bytes of one photo from the latest drop of loose files. Null when this shell cannot read drops yet. */
export async function readDroppedFile(path: string, invoke: Invoke = desktopInvoke): Promise<ArrayBuffer | null> {
if (!/\.jpe?g$/i.test(path)) return null;
try {
return asArrayBuffer(await invoke<unknown>("drop_read", { path }));
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (/not found|unknown command/i.test(message)) return null;
return null;
}
}
export async function openFolder(path: string, invoke: Invoke = desktopInvoke): Promise<FolderListing> {
try {
return await invoke<FolderListing>("folder_open", { path });
+15 -1
View File
@@ -1,6 +1,6 @@
import type { PhotoSummary } from "@photoreport/contracts";
import { describe, expect, it } from "vitest";
import { ALL_PHOTOS, initialLibrary, type LibraryFilter, libraryReducer, matchesFilter, patchForKey } from "./store.js";
import { ALL_PHOTOS, cycleColor, initialLibrary, type LibraryFilter, libraryReducer, matchesFilter, onlyUncolored, patchForKey } from "./store.js";
const photo = (id: string, capturedAt: string, extra: Partial<PhotoSummary> = {}): PhotoSummary => ({
id,
@@ -48,6 +48,9 @@ describe("library store", () => {
it("applies colleagues' culling and range selection", () => {
const patched = libraryReducer(loaded, { type: "message", message: { type: "photo.updated", ids: ["c"], patch: { flag: "PICK", rating: 3 } } });
expect(patched.photos[1]).toMatchObject({ flag: "PICK", rating: 3 });
const many = libraryReducer(patched, { type: "selectMany", ids: ["a", "c", "a"], focus: "c" });
expect([...many.selected]).toEqual(["a", "c"]);
expect(many.focus).toBe("c");
const range = libraryReducer(patched, { type: "select", id: "c", mode: "range", visible: ["a", "c"] });
expect([...range.selected]).toEqual(["a", "c"]);
const moved = libraryReducer(range, { type: "move", delta: -1, visible: ["a", "c"], extend: false });
@@ -72,6 +75,17 @@ describe("library store", () => {
expect(matchesFilter(photo("a", "", { flag: "PICK", rating: 1 }), toSend)).toBe(false);
expect(matchesFilter(photo("a", "", { flag: "NONE", rating: 5 }), toSend)).toBe(false);
expect(matchesFilter(photo("a", "", { colorLabel: "RED" }), { ...ALL_PHOTOS, color: "GREEN" })).toBe(false);
const hideRed = { ...ALL_PHOTOS, ...cycleColor(cycleColor(ALL_PHOTOS, "RED"), "RED") };
expect(hideRed).toEqual({ ...ALL_PHOTOS, color: "RED", withoutColor: true });
expect(matchesFilter(photo("a", "", { colorLabel: "RED" }), hideRed)).toBe(false);
expect(matchesFilter(photo("a", "", { colorLabel: "NONE" }), hideRed)).toBe(true);
expect(matchesFilter(photo("a", "", { colorLabel: "GREEN" }), hideRed)).toBe(true);
expect(cycleColor(hideRed, "RED")).toEqual({ color: null, withoutColor: false, uncolored: false });
const bare = onlyUncolored(ALL_PHOTOS);
expect(bare).toEqual({ color: null, withoutColor: false, uncolored: true });
expect(matchesFilter(photo("a", "", { colorLabel: "NONE" }), { ...ALL_PHOTOS, ...bare })).toBe(true);
expect(matchesFilter(photo("a", "", { colorLabel: "RED" }), { ...ALL_PHOTOS, ...bare })).toBe(false);
expect(onlyUncolored({ ...ALL_PHOTOS, ...bare })).toEqual({ color: null, withoutColor: false, uncolored: false });
expect(matchesFilter(photo("a", "", { delivery: "FAILED" }), { ...ALL_PHOTOS, delivery: "failed" })).toBe(true);
});
+28 -3
View File
@@ -21,6 +21,7 @@ export type LibraryAction =
| { type: "message"; message: LibraryMessage }
| { type: "patch"; ids: string[]; patch: PhotoPatch }
| { type: "select"; id: string; mode: "single" | "toggle" | "range"; visible: string[] }
| { type: "selectMany"; ids: string[]; focus: string | null }
| { type: "selectAll"; visible: string[] }
| { type: "move"; delta: number; visible: string[]; extend: boolean }
/** The photos still only on this computer (local FTP): those of this folder show, the others leave. */
@@ -192,6 +193,11 @@ export function libraryReducer(state: LibraryState, action: LibraryAction): Libr
const [lo, hi] = from < to ? [from, to] : [to, from];
return { ...state, selected: new Set(visible.slice(lo, hi + 1)), focus: id };
}
case "selectMany": {
const ids = action.ids.filter((id, i) => action.ids.indexOf(id) === i);
const focus = action.focus && ids.includes(action.focus) ? action.focus : (ids[ids.length - 1] ?? null);
return { ...state, selected: new Set(ids), focus, anchor: focus ?? state.anchor, wanted: null };
}
case "selectAll":
return { ...state, selected: new Set(action.visible) };
case "move": {
@@ -213,14 +219,31 @@ export interface LibraryFilter {
flag: "all" | "PICK" | "UNREJECTED" | "REJECT" | "UNFLAGGED";
minRating: number;
color: ColorLabel | null;
/** When set with `color`, hide photos that wear it and keep the rest. */
withoutColor: boolean;
/** Photo Mechanic's dotted chip: only photos with no colour class. */
uncolored: boolean;
delivery: "any" | "unsent" | "queued" | "sent" | "failed";
noPlayers: boolean;
}
export const ALL_PHOTOS: LibraryFilter = { flag: "all", minRating: 0, color: null, delivery: "any", noPlayers: false };
export const ALL_PHOTOS: LibraryFilter = { flag: "all", minRating: 0, color: null, withoutColor: false, uncolored: false, delivery: "any", noPlayers: false };
export function isAll(f: LibraryFilter): boolean {
return f.flag === "all" && !f.minRating && !f.color && f.delivery === "any" && !f.noPlayers;
return f.flag === "all" && !f.minRating && !f.color && !f.withoutColor && !f.uncolored && f.delivery === "any" && !f.noPlayers;
}
/** Colour chip: first click keeps that colour, second click hides it, third click clears. */
export function cycleColor(f: LibraryFilter, color: ColorLabel): Pick<LibraryFilter, "color" | "withoutColor" | "uncolored"> {
if (f.uncolored || f.color !== color) return { color, withoutColor: false, uncolored: false };
if (!f.withoutColor) return { color, withoutColor: true, uncolored: false };
return { color: null, withoutColor: false, uncolored: false };
}
/** The dotted chip: only photos that have no colour, or back to every colour. */
export function onlyUncolored(f: LibraryFilter): Pick<LibraryFilter, "color" | "withoutColor" | "uncolored"> {
if (f.uncolored) return { color: null, withoutColor: false, uncolored: false };
return { color: null, withoutColor: false, uncolored: true };
}
export function matchesFilter(photo: PhotoSummary, f: LibraryFilter): boolean {
@@ -229,7 +252,9 @@ export function matchesFilter(photo: PhotoSummary, f: LibraryFilter): boolean {
if (f.flag === "UNREJECTED" && photo.flag === "REJECT") return false;
if (f.flag === "UNFLAGGED" && photo.flag !== "NONE") return false;
if (f.minRating && photo.rating < f.minRating) return false;
if (f.color && photo.colorLabel !== f.color) return false;
if (f.uncolored && photo.colorLabel !== "NONE") return false;
if (!f.uncolored && f.color && f.withoutColor && photo.colorLabel === f.color) return false;
if (!f.uncolored && f.color && !f.withoutColor && photo.colorLabel !== f.color) return false;
const d = photo.delivery ?? "NONE";
if (f.delivery === "unsent" && d !== "NONE") return false;
if (f.delivery === "queued" && d !== "QUEUED") return false;
+14 -5
View File
@@ -174,10 +174,12 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
eventId: string | undefined;
original?: DesktopOrigin;
uploaderUserId?: string;
sha256?: string | null;
onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void;
}[]
>([]);
sha256?: string | null;
onSettled?: (status: UploadStatus, photo?: PhotoSummary) => void;
/** The named event was refused once. The next try lets the server place the photo by its clock. */
eventStripped?: boolean;
}[]
>([]);
const running = useRef(0);
/** No network: the queue waits (nothing fails) and carries on when the connection is back. */
const paused = useRef(false);
@@ -222,7 +224,14 @@ export function useUploadQueue(api: ApiClient, orgId: string) {
else if (res.status === 200) final = "duplicate";
else if (res.status === 0 || res.status === 502 || res.status === 503 || res.status === 504) throw new Error("network");
if (photo && final !== "failed") filed = photo;
if (final === "failed") update(item.id, { status: "failed", error: (res.body as { error?: string } | null)?.error ?? `http_${res.status}` });
const errorCode = (res.body as { error?: string } | null)?.error;
if (final === "failed" && errorCode === "event_not_in_organization" && next.eventId && !next.eventStripped) {
next.eventId = undefined;
next.eventStripped = true;
waiting = true;
update(item.id, { status: "queued", progress: 0, error: undefined });
queue.current.unshift(next);
} else if (final === "failed") update(item.id, { status: "failed", error: errorCode ?? `http_${res.status}` });
else update(item.id, { status: final, progress: 1 });
} catch (err) {
if (isNetworkError(err)) {
+100 -21
View File
@@ -14,7 +14,7 @@ import { FacesView } from "../library/FacesView.js";
import { LookupBanner } from "../library/PhotoLookup.js";
import { FolderDevelop } from "../library/FolderDevelop.js";
import { FolderSheet } from "../library/FolderSheet.js";
import { beginDropWait, folderDropPath, folderMeta, htmlDropIsFolder, mergeFolderDng, nativePaths, openFolder, folderThumb, type FolderListing } from "../library/folderDrop.js";
import { beginDropWait, folderDropPath, folderMeta, htmlDropIsFolder, mergeFolderDng, nativePaths, openFolder, readDroppedFile, folderThumb, type FolderListing } from "../library/folderDrop.js";
import { finishMergedJpeg } from "../library/finishMergedJpeg.js";
import { mergeFolderNative } from "../library/folderMerge.js";
import { MERGE_EDGE } from "../library/mergeStacks.js";
@@ -40,6 +40,8 @@ import { isNetworkError, offlineQueue } from "../offline/queue.js";
import { ensureRoster } from "../offline/roster.js";
import { patchPhotos, useQueueSize } from "../offline/sync.js";
import { FilterBar } from "../library/FilterBar.js";
import { LibraryMenus } from "../library/LibraryMenus.js";
import { SelectionBar } from "../library/SelectionBar.js";
import { SendButton } from "../library/SendButton.js";
import { isDesktop, prefs } from "../platform.js";
import { activePhoto, savedFilter, saveFilter, setActivePhoto } from "../library/active.js";
@@ -62,6 +64,7 @@ export function LibraryPage() {
const [targets, setTargets] = useState<DeliveryTarget[]>([]);
const [iptcOpen, setIptcOpen] = useState(false);
const [photoMenu, setPhotoMenu] = useState<{ x: number; y: number; id: string } | null>(null);
const [dropPartial, setDropPartial] = useState(false);
const { open: openFolderScan, syncGames } = useFolderScan();
const [state, dispatch] = useReducer(libraryReducer, initialLibrary);
const [filter, setFilterState] = useState<LibraryFilter>(() => savedFilter(orgId));
@@ -279,6 +282,11 @@ export function LibraryPage() {
const [developPath, setDevelopPath] = useState<string | null>(null);
const [openingFolder, setOpeningFolder] = useState(false);
const [removeOpen, setRemoveOpen] = useState(false);
const uploadInto = state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? state.scope : undefined;
const uploadAddRef = useRef(uploads.add);
const uploadIntoRef = useRef(uploadInto);
uploadAddRef.current = uploads.add;
uploadIntoRef.current = uploadInto;
useEffect(() => {
if (!isDesktop()) return;
let dead = false;
@@ -289,23 +297,38 @@ export function LibraryPage() {
else if (event.payload.type === "leave") setDragging(false);
else if (event.payload.type === "drop") {
setDragging(false);
nativePaths(event.payload.paths, folderDropPath, (path) => {
setOpeningFolder(true);
setLoupe(false);
void openFolder(path).then(
(listing) => {
if (dead) return;
setOpeningFolder(false);
setDevelopPath(null);
setSheet(listing);
},
() => {
if (dead) return;
setOpeningFolder(false);
setError(t.folderSheet.failed);
},
);
});
nativePaths(
event.payload.paths,
folderDropPath,
(path) => {
setOpeningFolder(true);
setLoupe(false);
void openFolder(path).then(
(listing) => {
if (dead) return;
setOpeningFolder(false);
setDevelopPath(null);
setSheet(listing);
},
() => {
if (dead) return;
setOpeningFolder(false);
setError(t.folderSheet.failed);
},
);
},
async (paths) => {
const files: File[] = [];
for (const path of paths) {
const bytes = await readDroppedFile(path);
if (!bytes) continue;
const name = path.split(/[/\\]/).pop() || "photo.jpg";
files.push(new File([bytes], name, { type: "image/jpeg" }));
}
return files;
},
(files) => uploadAddRef.current(files, uploadIntoRef.current),
);
}
}),
).then((stop) => {
@@ -317,7 +340,6 @@ export function LibraryPage() {
unlisten();
};
}, []);
const uploadInto = state.scope && state.scope !== "inbox" && !state.scope.startsWith("search:") && !state.scope.startsWith("face:") ? state.scope : undefined;
const openEvent = events.find((e) => e.id === uploadInto) ?? archivedEvents?.find((e) => e.id === uploadInto);
useEffect(() => {
const games = openEvent && !events.some((event) => event.id === openEvent.id) ? [openEvent, ...events] : events;
@@ -526,6 +548,28 @@ export function LibraryPage() {
<div className="flex min-h-[70vh] min-w-0 flex-1 flex-col lg:min-h-0">
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 border-b border-line bg-raised px-3 py-1.5 text-[12px]">
{!sheet && (
<LibraryMenus
canEdit={canCull}
hasSelection={selection.length > 0}
canRemove={isEventScope(state.scope)}
onSelectAll={() => dispatch({ type: "selectAll", visible: visibleIds })}
onSelectNone={() => dispatch({ type: "selectAll", visible: [] })}
onSelectUncolored={() => {
const ids = visible.filter((p) => p.colorLabel === "NONE").map((p) => p.id);
dispatch({ type: "selectMany", ids, focus: ids[0] ?? null });
}}
onSelectColor={(color) => {
const ids = visible.filter((p) => p.colorLabel === color).map((p) => p.id);
dispatch({ type: "selectMany", ids, focus: ids[0] ?? null });
}}
onColor={(color) => void patch(selection.map((p) => p.id), { colorLabel: color })}
onRating={(rating) => void patch(selection.map((p) => p.id), { rating })}
onFlag={(flag) => void patch(selection.map((p) => p.id), { flag })}
onInfo={() => setIptcOpen(true)}
onRemove={() => setRemoveOpen(true)}
/>
)}
<FilterBar filter={filter} onChange={setFilter} />
{players.length > 0 && (
<span className="flex min-w-0 items-center gap-2">
@@ -695,6 +739,7 @@ export function LibraryPage() {
</span>
)}
<span>
{selection.length > 0 ? `${t.selected(selection.length)} · ` : ""}
{t.ofTotal(visible.length, state.photos.length)} · {picks} ⚑
</span>
<span className="flex items-center gap-1.5" title={live}>
@@ -704,6 +749,15 @@ export function LibraryPage() {
</span>
</div>
{canCull && !sheet && selection.length > 0 && (
<SelectionBar
count={selection.length}
onColor={(color) => void patch(selection.map((p) => p.id), { colorLabel: color })}
onRating={(rating) => void patch(selection.map((p) => p.id), { rating })}
onFlag={(flag) => void patch(selection.map((p) => p.id), { flag })}
/>
)}
<div
className={`min-h-0 flex-1 ${sheet ? "flex flex-col overflow-hidden" : "overflow-y-auto"} ${dragging ? "outline outline-2 -outline-offset-4 outline-accent" : ""}`}
onDragOver={(e) => {
@@ -722,10 +776,27 @@ export function LibraryPage() {
return;
}
void beginDropWait().then((kind) => {
if (kind === "files") uploads.add(files, uploadInto);
if (kind !== "files") return;
// The current shell only receives the few files WebKit lists. Do not upload that slice.
setDropPartial(true);
});
}}
>
{dropPartial && (
<p className="m-3 flex items-center gap-3 border border-star/50 bg-star/10 px-3 py-2 text-[13px] text-ink">
<span>{t.dropPartial}</span>
<button
type="button"
className="h-7 border border-black bg-cell px-2.5 text-ink hover:bg-cell-on"
onClick={() => {
setDropPartial(false);
fileInput.current?.click();
}}
>
{t.dropChoose}
</button>
</p>
)}
{error && (
<p role="alert" className="m-3 border border-danger/40 bg-danger/10 px-3 py-2 text-[13px] text-danger">
{error}
@@ -806,6 +877,7 @@ export function LibraryPage() {
orgId={orgId}
srcFor={srcFor}
onPick={onPick}
onSelectMany={(ids, focus) => dispatch({ type: "selectMany", ids, focus })}
onOpen={onOpenLoupe}
{...(canCull ? { onMenu: onPhotoMenu } : {})}
/>
@@ -836,7 +908,14 @@ export function LibraryPage() {
/>
{photoMenu && photoMenuActions.length > 0 && (
<PhotoContextMenu x={photoMenu.x} y={photoMenu.y} actions={photoMenuActions} onClose={() => setPhotoMenu(null)} />
<PhotoContextMenu
x={photoMenu.x}
y={photoMenu.y}
actions={photoMenuActions}
onClose={() => setPhotoMenu(null)}
onColor={(color) => void patch(selection.map((p) => p.id), { colorLabel: color })}
onRating={(rating) => void patch(selection.map((p) => p.id), { rating })}
/>
)}
{removeOpen && isEventScope(state.scope) && (
<RemoveFromEventDialog
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@photoreport/desktop",
"version": "0.3.29",
"version": "0.3.30",
"private": true,
"type": "module",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "photoreport-desktop"
version = "0.3.29"
version = "0.3.30"
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."
+1
View File
@@ -38,6 +38,7 @@ fn main() {
"local_original_changed",
"local_film_thumb",
"folder_drop",
"drop_read",
"folder_open",
"folder_thumb",
"folder_read",
@@ -35,6 +35,7 @@
"allow-local-original-changed",
"allow-local-film-thumb",
"allow-folder-drop",
"allow-drop-read",
"allow-folder-open",
"allow-folder-thumb",
"allow-folder-read",
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-drop-read"
description = "Enables the drop_read command without any pre-configured scope."
commands.allow = ["drop_read"]
[[permission]]
identifier = "deny-drop-read"
description = "Denies the drop_read command without any pre-configured scope."
commands.deny = ["drop_read"]
+42 -3
View File
@@ -17,6 +17,9 @@ use crate::local::read_film_thumb;
pub struct OpenFolders {
/// Canonical paths of folders the user actually dropped on the window.
dropped: Mutex<HashSet<PathBuf>>,
/// Photos dropped as files (not inside a folder). Readable until the next drop. The page's file list
/// often receives only a few of them.
files: Mutex<HashSet<PathBuf>>,
/// Folders opened as a contact sheet this session. Thumbnails stay inside these.
open: Mutex<Vec<PathBuf>>,
}
@@ -36,19 +39,40 @@ pub struct FolderFile {
}
impl OpenFolders {
/// Remember folders from a drop on this window. Files in the same drop are ignored.
/// Remember what was dropped on this window. Folders can be opened. Loose photos can be read back,
/// because the page's own file list keeps only a few of a large drop.
pub fn note(&self, paths: &[PathBuf]) {
let mut dropped = self.dropped.lock().unwrap();
let mut files = self.files.lock().unwrap();
files.clear();
for path in paths {
if !path.is_dir() {
if path.is_dir() {
if let Ok(canon) = path.canonicalize() {
dropped.insert(canon);
}
continue;
}
if !path.is_file() || !is_photo(path) {
continue;
}
if let Ok(canon) = path.canonicalize() {
dropped.insert(canon);
files.insert(canon);
}
}
}
/// A photo from the latest drop, canonical. Anything else is refused.
pub fn allow_dropped_file(&self, path: &Path) -> Result<PathBuf, String> {
let canon = path.canonicalize().map_err(|_| "not_found".to_string())?;
if !canon.is_file() || !is_photo(&canon) {
return Err("not_a_photo".to_string());
}
if !self.files.lock().unwrap().contains(&canon) {
return Err("not_allowed".to_string());
}
Ok(canon)
}
/// The dropped folder, canonical, or an error when it was not dropped here or is not a folder.
pub fn open(&self, path: &Path) -> Result<PathBuf, String> {
let canon = path.canonicalize().map_err(|e| e.to_string())?;
@@ -296,6 +320,21 @@ fn listing(root: PathBuf) -> FolderListing {
}
}
/// One photo from the latest drop of loose files. The page uploads it. A path from anywhere else is refused.
#[tauri::command]
pub async fn drop_read(
folders: tauri::State<'_, OpenFolders>,
path: String,
) -> Result<tauri::ipc::Response, String> {
let p = folders.allow_dropped_file(Path::new(&path))?;
let meta = tokio::fs::metadata(&p).await.map_err(|e| e.to_string())?;
if meta.len() == 0 || meta.len() > 200 * 1024 * 1024 {
return Err("bad_file".to_string());
}
let bytes = tokio::fs::read(&p).await.map_err(|e| e.to_string())?;
Ok(tauri::ipc::Response::new(bytes))
}
/// The first dropped path that is a folder, so the page can open it instead of uploading the files inside.
#[tauri::command]
pub fn folder_drop(paths: Vec<String>) -> Option<String> {
+1
View File
@@ -150,6 +150,7 @@ pub fn run() {
local::local_stat,
local::local_xmp,
browse::folder_drop,
browse::drop_read,
browse::folder_open,
browse::folder_thumb,
browse::folder_read,
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport",
"version": "0.3.29",
"version": "0.3.30",
"identifier": "pt.photoreport.desktop",
"build": {
"devUrl": "http://localhost:5173",
+11 -2
View File
@@ -282,7 +282,15 @@ hand-drawn boxes.
every 6 hours (`SPORTS_SYNC=off` turns it off). It is shared by every organisation:
- **Liga Portugal** (`ligaportugal.pt/api/v1`): Betclic, Meu Super and Allianz Cup stay on the six-hour refresh.
Gives teams, squads (numbers, positions, official headshots) and the season's fixtures. On start the worker reads
Gives teams, squads (numbers, positions, official headshots) and the season's fixtures. The calendar does not
name the ground: `team/info` does (the stadium). The town is that page's city when Liga fills it, otherwise the
town written in the club's own name or in a stadium that names it ("Municipal de Amarante", "Cidade de Coimbra").
A person's name in the stadium ("Dr. Machado de Matos") is not a town. Stadium and town are stored apart
(`venue` and `city`) on the club and on the match, and choosing the match fills both on the event. The same
split is what UEFA (`stadium.city`) and the EHF (`cityName`) already publish. Handball keeps the hall from the
agenda (`LOCAL`, the same line as Recinto on the match sheet). The town is the home club's `CLUBE_LOCALIDADE`
(`getClube`: Oriental → Lisboa, Albicastrense → Castelo Branco). The federation's own card is not a club, so a
seleção does not take Lisboa from F.A.P. A club that leaves the locality blank stays without a city. On start the worker reads
every season the federation still lists, under the name that league had that year (Liga NOS, Liga Sagres, LigaPro),
so a past season keeps the squad and the shirt numbers of that year. When that read finishes, the newest
photographs already analysed are queued again for faces (thirty thousand per start). The archive's people list
@@ -456,7 +464,8 @@ credentials, another name and folder).
for Lightroom Classic ≥ 13.2 Attribute filters: `XMP-xmpDM:Pick` (1 / 0 / −1) + `Good`, `XMP-xmp:Rating`,
`XMP-xmp:Label`, plus digiKam `PickLabel` and IPTC Urgency for Photo Mechanic. When the desktop app is open it
watches local delivery folders; a Reject written back by Lightroom (XMP auto-write) sets the photo to REJECT
and retracts any delivery of that file.
and retracts any delivery of that file. A colour Photo Mechanic paints on a local original, or on a delivered
file, is copied back (`photomechanic:ColorClass`: 1 red, 3 yellow, 4 green, 5 blue, 7 purple).
**Colour ↔ destination.** A delivery target may own one library colour. Painting that colour queues the photo
only there; enqueue skips `color_mismatch` otherwise. The library colour is how you see what went where.
@@ -40,6 +40,10 @@ describe("decide", () => {
expect(decide("api", "issues", push(["apps/api/x"])).action).toBe("ignore");
});
it("deploys when a merge commit lists no files", () => {
expect(decide("app", "push", push([])).action).toBe("deploy");
});
it("deploys when Gitea truncated the commit list", () => {
expect(decide("ml", "push", push(["docs/x.md"], { total_commits: 30 })).action).toBe("deploy");
});
+2
View File
@@ -33,6 +33,8 @@ export function decide(service: Service, event: string | undefined, payload: Pus
return { action: "deploy", sha, reason: "commit list truncated" };
}
const paths = commits.flatMap((c) => [...(c.added ?? []), ...(c.modified ?? []), ...(c.removed ?? [])]);
// A merge commit often arrives with an empty file list. Skipping it left the app on an older build.
if (paths.length === 0) return { action: "deploy", sha, reason: "push listed no paths" };
return touchesService(service, paths)
? { action: "deploy", sha, reason: "owned paths changed" }
: { action: "ignore", reason: "no owned paths changed" };
+42 -6
View File
@@ -323,21 +323,57 @@ export function marksToExiftoolArgs(marks: LibraryMarks): string[] {
/**
* Read cull marks from an XMP packet (sidecar or embedded). Used when Lightroom writes Pick back to a delivered file.
*/
/**
* Photo Mechanic's colour class (the number it writes, not the English name). Same map as the IPTC variables:
* 1 red, 3 yellow, 4 green, 5 blue, 7 purple. 0 clears the colour. 2 and 6 are unused in that set.
*/
export type XmpColor = "NONE" | "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
const PM_COLOR_CLASS: Record<number, XmpColor> = {
0: "NONE",
1: "RED",
3: "YELLOW",
4: "GREEN",
5: "BLUE",
7: "PURPLE",
};
const LABEL_NAME: Record<string, XmpColor> = {
red: "RED",
winner: "RED",
yellow: "YELLOW",
superior: "YELLOW",
green: "GREEN",
"superior alt": "GREEN",
blue: "BLUE",
typical: "BLUE",
purple: "PURPLE",
extra: "PURPLE",
none: "NONE",
};
/**
* The colour Photo Mechanic or Lightroom wrote. Null when the packet does not mention a colour, so a file
* that only has a crop does not wipe a colour set in the library. Colour class wins over the label name.
*/
export function colorClassFromXmp(xmp: string): XmpColor | null {
const klass = xmpMatchNum(xmp, /(?:photomechanic:)?ColorClass\s*(?:=|:|>)\s*"?(\d+)/i) ?? xmpMatchNum(xmp, /<(?:photomechanic:)?ColorClass>(\d+)<\/(?:photomechanic:)?ColorClass>/i);
if (klass !== null) return PM_COLOR_CLASS[klass] ?? null;
const labelRaw = xmpMatchStr(xmp, /(?:xmp:Label|Label)\s*(?:=|:|>)\s*"?([A-Za-z]+(?: [A-Za-z]+)?)/i) ?? xmpMatchStr(xmp, /<xmp:Label>([^<]+)<\/xmp:Label>/i);
if (labelRaw === null) return null;
return LABEL_NAME[labelRaw.trim().toLowerCase()] ?? null;
}
export function libraryMarksFromXmp(xmp: string): LibraryMarks {
const pick = xmpMatchNum(xmp, /(?:xmpDM:pick|xmp:Pick|Pick)\s*(?:=|:|>)\s*"?(-?\d+)/i) ?? xmpMatchNum(xmp, /<xmpDM:pick>(-?\d+)<\/xmpDM:pick>/i);
const rating = xmpMatchNum(xmp, /(?:xmp:Rating|Rating)\s*(?:=|:|>)\s*"?(-?\d+)/i) ?? xmpMatchNum(xmp, /<xmp:Rating>(-?\d+)<\/xmp:Rating>/i);
const labelRaw = xmpMatchStr(xmp, /(?:xmp:Label|Label)\s*(?:=|:|>)\s*"?([A-Za-z]+)/i) ?? xmpMatchStr(xmp, /<xmp:Label>([^<]+)<\/xmp:Label>/i);
let flag: LibraryMarks["flag"] = "NONE";
if (pick === -1 || rating === -1) flag = "REJECT";
else if (pick === 1) flag = "PICK";
const colorLabel =
labelRaw && ["Red", "Yellow", "Green", "Blue", "Purple"].includes(labelRaw)
? (labelRaw.toUpperCase() as "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE")
: "NONE";
return {
flag,
rating: rating !== null && rating > 0 ? Math.min(5, rating) : 0,
colorLabel,
colorLabel: colorClassFromXmp(xmp) ?? "NONE",
};
}
+8
View File
@@ -15,6 +15,7 @@ import {
renderFileName,
renderFolder,
seasonOf,
colorClassFromXmp,
cropFromXmp,
libraryMarksFromXmp,
marksToExiftoolArgs,
@@ -170,6 +171,13 @@ describe("IPTC template", () => {
colorLabel: "BLUE",
});
expect(libraryMarksFromXmp(`xmpDM:pick="-1"`).flag).toBe("REJECT");
expect(colorClassFromXmp(`photomechanic:ColorClass="1"`)).toBe("RED");
expect(colorClassFromXmp(`photomechanic:ColorClass="3"`)).toBe("YELLOW");
expect(colorClassFromXmp(`photomechanic:ColorClass="4"`)).toBe("GREEN");
expect(colorClassFromXmp(`photomechanic:ColorClass="7"`)).toBe("PURPLE");
expect(colorClassFromXmp(`photomechanic:ColorClass="0"`)).toBe("NONE");
expect(colorClassFromXmp(`photomechanic:ColorClass="1" xmp:Label="Blue"`)).toBe("RED");
expect(colorClassFromXmp(`crs:CropTop="0.1"`)).toBeNull();
});
it("reads the soft crop Photo Mechanic and Lightroom draw from crs attributes", () => {
+2 -1
View File
@@ -198,11 +198,12 @@ export interface SportsFixture {
round: string | null;
matchNumber: string | null;
venue: string | null;
city: string | null;
homeScore: number | null;
awayScore: number | null;
sport: string;
competition: { id: string; name: string; provider: SportsProvider; code: string; gender: string | null };
home: { id: string; name: string; abbreviation: string | null; venue: string | null };
home: { id: string; name: string; abbreviation: string | null; venue: string | null; city: string | null };
away: { id: string; name: string; abbreviation: string | null };
}