Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions components/ui/ImportLogDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ export function ImportLogDialog({
const [saveState, setSaveState] = useState<SaveState>("idle");
const [isParsing, startParseTransition] = useTransition();
const autoParseRequestIdRef = useRef(0);
const importSessionIdRef = useRef(0);
const saveInFlightRef = useRef(false);
const shouldAutoParseImmediatelyRef = useRef(false);
const closeTimerRef = useRef<number | null>(null);
const navigationTimerRef = useRef<number | null>(null);
Expand Down Expand Up @@ -222,6 +224,10 @@ export function ImportLogDialog({
}, [review, selectedDeckId, userDecks]);

function resetImportState() {
autoParseRequestIdRef.current += 1;
importSessionIdRef.current += 1;
saveInFlightRef.current = false;
shouldAutoParseImmediatelyRef.current = false;
setStage("raw");
setRawLog("");
setParseError(null);
Expand Down Expand Up @@ -269,6 +275,8 @@ export function ImportLogDialog({

useEffect(() => {
return () => {
autoParseRequestIdRef.current += 1;
importSessionIdRef.current += 1;
clearCloseTimer();
clearNavigationTimer();
};
Expand Down Expand Up @@ -339,16 +347,25 @@ export function ImportLogDialog({
return;
}

const sessionId = importSessionIdRef.current;
const requestId = ++autoParseRequestIdRef.current;
try {
setIsPasting(true);
const clipboardText = await navigator.clipboard.readText();
if (autoParseRequestIdRef.current !== requestId) {
return;
}
shouldAutoParseImmediatelyRef.current = true;
setRawLog(clipboardText);
setParseError(null);
} catch {
setParseError("Unable to read from the clipboard right now.");
if (autoParseRequestIdRef.current === requestId) {
setParseError("Unable to read from the clipboard right now.");
}
} finally {
setIsPasting(false);
if (importSessionIdRef.current === sessionId) {
setIsPasting(false);
}
}
}

Expand Down Expand Up @@ -418,6 +435,11 @@ export function ImportLogDialog({
}

async function handleSubmit(formData: FormData) {
if (saveInFlightRef.current || !review) {
return;
}
saveInFlightRef.current = true;
const sessionId = importSessionIdRef.current;
setSaveError("");
setSaveState("saving");

Expand All @@ -429,6 +451,9 @@ export function ImportLogDialog({
method: "POST"
});
const result = (await response.json()) as SaveActionResult | { error?: string };
if (importSessionIdRef.current !== sessionId) {
return;
}

if (!response.ok || !("ok" in result)) {
const message = "error" in result ? result.error : undefined;
Expand Down Expand Up @@ -459,6 +484,10 @@ export function ImportLogDialog({
}, 50);
}, SUCCESS_CLOSE_DELAY_MS);
} catch (error) {
if (importSessionIdRef.current !== sessionId) {
return;
}
saveInFlightRef.current = false;
setSaveError(error instanceof Error ? error.message : "Could not save this battle log.");
setSaveState("idle");
}
Expand Down Expand Up @@ -494,6 +523,7 @@ export function ImportLogDialog({

return () => {
window.clearTimeout(timeoutId);
autoParseRequestIdRef.current += 1;
};
}, [isOpen, isTrainingCourtUrl, requestParseReview, stage, trimmedRawLog]);

Expand Down Expand Up @@ -833,6 +863,11 @@ export function ImportLogDialog({
}}
onChange={(event) => {
const nextRawLog = event.target.value;
Comment thread
jamesembling marked this conversation as resolved.
Resolved
// Only a change to the reviewed (trimmed) log supersedes a
// pending review; the auto-review effect reschedules on it.
if (nextRawLog.trim() !== trimmedRawLog) {
autoParseRequestIdRef.current += 1;
}
if (nextRawLog.length - rawLog.length >= BULK_PASTE_CHARACTER_THRESHOLD) {
shouldAutoParseImmediatelyRef.current = true;
}
Expand Down
15 changes: 15 additions & 0 deletions lib/log-import/parser/players.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,3 +119,18 @@ export function canonicalizeSelfPlayerSections(
)
}));
}

/** Match the recorded actor, including names ending in punctuation. */
export function getLeadingPlayerFromLine(line: string, playerNames: string[]) {
const normalized = String(line || "").replace(/^\s*(?:[-•]\s+)?/, "");
return (
playerNames
.toSorted((left, right) => right.length - left.length)
.find(
(player) =>
normalized.startsWith(`${player} `) ||
normalized.startsWith(`${player}'s `) ||
normalized.startsWith(`${player}’s `)
) ?? ""
);
}
49 changes: 31 additions & 18 deletions lib/log-import/parser/pokemon-mentions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,26 @@ import { normalizeText } from "@/lib/log-import/normalization";
import type { IdentificationCatalog, PlayerPokemonEvidence } from "@/lib/log-import/types";
import { stripLogCardIdentifiers } from "@/lib/battle-log/card-identifiers";

// Effect-driven plays (e.g. Rare Candy) arrive as indented "- " / "• " detail
// lines; the acting player still leads the recorded sentence.
function stripDetailMarker(line: string) {
return line.replace(/^\s*(?:[-•]\s+)?/, "");
}

function getRelevantIdentificationLines(lines: string[], playerName: string, language: Language) {
if (language === "en") {
return lines.filter(
(line) =>
line.includes(`${playerName} attached`) ||
line.includes(`${playerName} played `) ||
(line.includes(`${playerName} drew `) && line.includes("and played it to the Bench")) ||
line.includes(`${playerName} evolved `) ||
(line.includes(`${playerName}'s `) &&
(line.includes("was Knocked Out") || (line.includes(" used") && !line.includes("damage"))))
);
return lines
.map(stripDetailMarker)
.filter(
(line) =>
line.startsWith(`${playerName} attached`) ||
line.startsWith(`${playerName} played `) ||
(line.startsWith(`${playerName} drew `) && line.includes("and played it to the Bench")) ||
line.startsWith(`${playerName} evolved `) ||
(line.startsWith(`${playerName}'s `) &&
(line.includes("was Knocked Out") ||
(line.includes(" used") && !line.includes("damage"))))
);
}

if (language === "es") {
Expand All @@ -25,7 +34,9 @@ function getRelevantIdentificationLines(lines: string[], playerName: string, lan
if (language === "de") {
return lines.filter(
(line) =>
(line.includes(playerName) && line.includes(" auf der Bank zu ") && line.includes("entwickelt")) ||
(line.includes(playerName) &&
line.includes(" auf der Bank zu ") &&
line.includes("entwickelt")) ||
(line.includes(`${playerName} hat`) && line.includes(" auf die Bank gelegt."))
);
}
Expand All @@ -40,7 +51,8 @@ function getRelevantIdentificationLines(lines: string[], playerName: string, lan

if (language === "it") {
return lines.filter(
(line) => line.includes(`${playerName} ha pescato e giocato`) && line.includes(" in panchina.")
(line) =>
line.includes(`${playerName} ha pescato e giocato`) && line.includes(" in panchina.")
);
}

Expand Down Expand Up @@ -71,18 +83,19 @@ export function extractPlayerPokemonMentions(args: {
catalog: IdentificationCatalog;
}): PlayerPokemonEvidence {
const relevantLines = getRelevantIdentificationLines(args.lines, args.playerName, args.language);
// Player identities are not card evidence, even when a username is a Pokémon name.
const cardLines =
args.language === "en"
? relevantLines.map((line) => line.slice(args.playerName.length))
: relevantLines;
const mentionCounts = new Map<string, number>();
const maxTokens = args.catalog.pokemon.maxNameTokens;

relevantLines.forEach((line) => {
cardLines.forEach((line) => {
const tokens = tokenizeLine(line);

for (let startIndex = 0; startIndex < tokens.length; startIndex += 1) {
for (
let size = Math.min(maxTokens, tokens.length - startIndex);
size >= 1;
size -= 1
) {
for (let size = Math.min(maxTokens, tokens.length - startIndex); size >= 1; size -= 1) {
const phrase = tokens.slice(startIndex, startIndex + size).join(" ");
const slug = args.catalog.pokemon.normalizedNameToSlug.get(phrase);
if (!slug) {
Expand All @@ -98,7 +111,7 @@ export function extractPlayerPokemonMentions(args: {

return {
lines: relevantLines,
normalizedText: normalizeText(stripLogCardIdentifiers(relevantLines.join(" "))),
normalizedText: normalizeText(stripLogCardIdentifiers(cardLines.join(" "))),
mentionCounts
};
}
77 changes: 36 additions & 41 deletions lib/log-import/parser/stats.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import type { Language, LogSection, Result } from "@/types/index";
import { LANGUAGE_STRINGS } from "@/lib/log-import/parser/language";
import { getLeadingPlayerFromLine } from "@/lib/log-import/parser/players";
import { ImportLogValidationError } from "@/lib/log-import/types";
import { compactMap } from "@/lib/array";

const WINNER_PATTERNS: Record<Language, RegExp> = {
en: /\. (.*) wins\./g,
es: /\. (.*) ganó\./,
de: /\. (.*) hat gewonnen\./,
fr: /\. (.*) gagne\./,
it: /\. (.*) ha vinto\./,
"pt-br": /\. (.*) venceu\./
const WINNER_SUFFIXES: Record<Language, string> = {
en: " wins.",
es: " ganó.",
de: " hat gewonnen.",
fr: " gagne.",
it: " ha vinto.",
"pt-br": " venceu."
};

const CONCEDE_PATTERNS: Record<Language, RegExp[]> = {
Expand All @@ -21,27 +22,12 @@ const CONCEDE_PATTERNS: Record<Language, RegExp[]> = {
"pt-br": [/concedeu/i, /desistiu/i]
};

function getLeadingPlayerFromLine(line: string, playerNames: string[]) {
const candidates = playerNames.toSorted((left, right) => right.length - left.length);

return (
candidates.find((player) => {
const escaped = player.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return new RegExp(`^${escaped}(?:'s|\\b)`).test(String(line || ""));
}) ?? ""
);
}

function getPlayerFromLine(line: string, playerNames: string[]) {
return playerNames.find((player) => String(line || "").includes(player)) ?? "";
}

function getCoinTossWinnerFromLine(line: string, playerNames: string[]) {
if (!String(line || "").includes(" won the coin toss")) {
return "";
}

return getLeadingPlayerFromLine(line, playerNames) || getPlayerFromLine(line, playerNames);
return getLeadingPlayerFromLine(line, playerNames);
}

function getMulligansTakenFromLine(line: string) {
Expand Down Expand Up @@ -101,7 +87,10 @@ function getAttackDamageFromAction(
// Ability actions such as Festival Lead contain a recorded attack in their
// details. Read attack records, not the explanatory damage breakdown.
const title = String(action.title || "").trim();
const records = [title, ...action.details.map((detail) => detail.replace(/^\s*-\s*/, "").trim())];
const records = [
title,
...action.details.map((detail) => detail.replace(/^\s*[-•]\s+/, "").trim())
];
const nestedAttacks = records.slice(1).filter((line) => getAttackDamageFromLine(line) > 0);
// A title repeated in its details is one record. Repeated nested lines can
// represent two real attacks (Festival Lead) and must each retain their damage.
Expand Down Expand Up @@ -129,23 +118,27 @@ function getAttackDamageFromAction(
});
}

function determineWinner(lines: string[], language: Language) {
const winner = lines
.map((line) => {
const match = WINNER_PATTERNS[language].exec(line)?.[1] ?? null;
WINNER_PATTERNS[language].lastIndex = 0;
return match;
})
.find(Boolean);
function determineWinner(lines: string[], language: Language, playerNames: string[]) {
const candidates = playerNames.toSorted((left, right) => right.length - left.length);
const winners = Array.from(
new Set(
compactMap(lines, (line) =>
candidates.find((player) => {
const ending = `${player}${WINNER_SUFFIXES[language]}`;
return line === ending || line.endsWith(`. ${ending}`);
})
)
)
);

if (!winner) {
if (winners.length !== 1) {
throw new ImportLogValidationError(
"UNKNOWN_LOG",
"Could not find a winner line in this PTCGL log."
"Could not resolve exactly one winner from the players in this PTCGL log."
);
}

return winner;
return winners[0];
}

export function getPrizesTakenFromLine(line: string, language: Language) {
Expand Down Expand Up @@ -198,7 +191,7 @@ function calculateTotalTurns(sections: LogSection[]) {
})
.filter((value) => Number.isFinite(value));

return numberedTurns.length > 0 ? Math.max(...numberedTurns) : Math.ceil(nonSetupSections.length / 2);
return numberedTurns.length > 0 ? Math.max(...numberedTurns) : nonSetupSections.length;
}

function determineGoOrder(
Expand Down Expand Up @@ -265,7 +258,7 @@ export function buildStats({
return;
}

const leadingPlayer = getLeadingPlayerFromLine(line, playerNames) || getPlayerFromLine(line, playerNames);
const leadingPlayer = getLeadingPlayerFromLine(line, playerNames);
const playerStats = leadingPlayer ? statsByName[leadingPlayer] : null;
const actionLines = compactMap([line, ...action.details], (entry) => String(entry || "").trim());

Expand All @@ -275,12 +268,14 @@ export function buildStats({
coinTossWinner = coinTossPlayer;
}

const mulliganPlayer =
getLeadingPlayerFromLine(actionLine, playerNames) || getPlayerFromLine(actionLine, playerNames);
const mulliganPlayer = getLeadingPlayerFromLine(actionLine, playerNames);
const mulliganStats = mulliganPlayer ? statsByName[mulliganPlayer] : null;
const mulligansTaken = getMulligansTakenFromLine(actionLine);
if (mulliganStats && mulligansTaken > 0) {
mulliganStats.mulligans = Math.max(mulliganStats.mulligans, mulligansTaken);
// Each singular record is an event; numeric records summarize a count.
mulliganStats.mulligans = actionLine.includes("took a mulligan")
? mulliganStats.mulligans + 1
: Math.max(mulliganStats.mulligans, mulligansTaken);
}
});

Expand All @@ -296,7 +291,7 @@ export function buildStats({
});
});

const winner = determineWinner(lines, language);
const winner = determineWinner(lines, language, playerNames);
const result: Result = winner.toLowerCase() === selfPlayerName.toLowerCase() ? "Win" : "Loss";
const selfStats = statsByName[selfPlayerName];
const opponentStats = statsByName[opponentPlayerName];
Expand Down
Loading
Loading