update TR references with args in *.ts; fix average answer time

This commit is contained in:
Damien Elmes 2021-03-26 19:09:50 +10:00
parent b435658acb
commit df93ed0b15
15 changed files with 65 additions and 49 deletions

View file

@ -422,7 +422,7 @@ group by day order by day"""
i, i,
"Average answer time", "Average answer time",
self.col.tr.statistics_average_answer_time( self.col.tr.statistics_average_answer_time(
average_seconds=average_secs average_seconds=average_secs, cards_per_minute=perMin
), ),
) )
return self._lineTbl(i), int(tot) return self._lineTbl(i), int(tot)

View file

@ -9,13 +9,13 @@ from re import Match
import stringcase import stringcase
TR_REF = re.compile(r"i18n\.tr\(i18n\.TR\.([^,) ]+)\)") TR_REF = re.compile(r"i18n.tr\(\s*i18n.TR.([^,) ]+),\s*([^)]+)\)")
def repl(m: Match) -> str: def repl(m: Match) -> str:
name = stringcase.camelcase(m.group(1).lower()) name = stringcase.camelcase(m.group(1).lower())
#args = m.group(2) args = m.group(2)
return f"i18n.{name}()" return f"i18n.{name}({args})"
def update_py(path: str) -> None: def update_py(path: str) -> None:
@ -24,7 +24,7 @@ def update_py(path: str) -> None:
if buf != buf2: if buf != buf2:
open(path, "w").writelines(buf2) open(path, "w").writelines(buf2)
print("updated", path) print("updated", path)
#print(buf2) # print(buf2)
for dirpath, dirnames, fnames in os.walk(os.environ["BUILD_WORKSPACE_DIRECTORY"]): for dirpath, dirnames, fnames in os.walk(os.environ["BUILD_WORKSPACE_DIRECTORY"]):

View file

@ -69,6 +69,15 @@ fn extract_metadata(ftl_text: &str) -> Vec<Translation> {
visitor.visit_pattern(&pattern); visitor.visit_pattern(&pattern);
let key = m.id.name.to_string(); let key = m.id.name.to_string();
// special case translations that were ported from gettext, and use embedded
// terms that reference other variables that aren't visible to our visitor
if key == "statistics-studied-today" {
visitor.variables.insert("amount".to_string());
visitor.variables.insert("cards".to_string());
} else if key == "statistics-average-answer-time" {
visitor.variables.insert("cards-per-minute".to_string());
}
let (text, variables) = visitor.into_output(); let (text, variables) = visitor.into_output();
output.push(Translation { output.push(Translation {
@ -141,10 +150,17 @@ impl From<String> for Variable {
// try to either reuse existing ones, or consider some sort of Hungarian notation // try to either reuse existing ones, or consider some sort of Hungarian notation
let kind = match name.as_str() { let kind = match name.as_str() {
"cards" | "notes" | "count" | "amount" | "reviews" | "total" | "selected" "cards" | "notes" | "count" | "amount" | "reviews" | "total" | "selected"
| "kilobytes" => VariableKind::Int, | "kilobytes" | "daysStart" | "daysEnd" | "days" | "secs-per-card" | "remaining"
"average-seconds" => VariableKind::Float, | "hourStart" | "hourEnd" | "correct" => VariableKind::Int,
"val" | "found" | "expected" | "part" => VariableKind::Any, "average-seconds" | "cards-per-minute" => VariableKind::Float,
_ => VariableKind::String, "val" | "found" | "expected" | "part" | "percent" | "day" => VariableKind::Any,
term => {
if term.ends_with("Count") || term.ends_with("Secs") {
VariableKind::Int
} else {
VariableKind::String
}
}
}; };
Variable { name, kind } Variable { name, kind }
} }

View file

@ -25,11 +25,11 @@ export function buildNextLearnMsg(
const unit = naturalUnit(secsUntil); const unit = naturalUnit(secsUntil);
const amount = Math.round(unitAmount(unit, secsUntil)); const amount = Math.round(unitAmount(unit, secsUntil));
const unitStr = unitName(unit); const unitStr = unitName(unit);
const nextLearnDue = i18n.tr(i18n.TR.SCHEDULING_NEXT_LEARN_DUE, { const nextLearnDue = i18n.schedulingNextLearnDue({
amount, amount,
unit: unitStr, unit: unitStr,
}); });
const remaining = i18n.tr(i18n.TR.SCHEDULING_LEARN_REMAINING, { const remaining = i18n.schedulingLearnRemaining({
remaining: info.learnRemaining, remaining: info.learnRemaining,
}); });
return `${nextLearnDue} ${remaining}`; return `${nextLearnDue} ${remaining}`;

View file

@ -100,11 +100,11 @@ export function buildHistogram(
const tableData = [ const tableData = [
{ {
label: i18n.statisticsTotal(), label: i18n.statisticsTotal(),
value: i18n.tr(i18n.TR.STATISTICS_CARDS, { cards: totalInPeriod }), value: i18n.statisticsCards({ cards: totalInPeriod }),
}, },
{ {
label: i18n.statisticsAverage(), label: i18n.statisticsAverage(),
value: i18n.tr(i18n.TR.STATISTICS_CARDS_PER_DAY, { count: cardsPerDay }), value: i18n.statisticsCardsPerDay({ count: cardsPerDay }),
}, },
]; ];
@ -114,9 +114,9 @@ export function buildHistogram(
_percent: number _percent: number
): string { ): string {
const day = dayLabel(i18n, bin.x0!, bin.x1!); const day = dayLabel(i18n, bin.x0!, bin.x1!);
const cards = i18n.tr(i18n.TR.STATISTICS_CARDS, { cards: bin.length }); const cards = i18n.statisticsCards({ cards: bin.length });
const total = i18n.statisticsRunningTotal(); const total = i18n.statisticsRunningTotal();
const totalCards = i18n.tr(i18n.TR.STATISTICS_CARDS, { cards: cumulative }); const totalCards = i18n.statisticsCards({ cards: cumulative });
return `${day}:<br>${cards}<br>${total}: ${totalCards}`; return `${day}:<br>${cards}<br>${total}: ${totalCards}`;
} }

View file

@ -241,10 +241,7 @@ export function renderButtons(
function tooltipText(d: Datum): string { function tooltipText(d: Datum): string {
const button = i18n.statisticsAnswerButtonsButtonNumber(); const button = i18n.statisticsAnswerButtonsButtonNumber();
const timesPressed = i18n.statisticsAnswerButtonsButtonPressed(); const timesPressed = i18n.statisticsAnswerButtonsButtonPressed();
const correctStr = i18n.tr( const correctStr = i18n.statisticsHoursCorrect(totalCorrect(d.group));
i18n.TR.STATISTICS_HOURS_CORRECT,
totalCorrect(d.group)
);
return `${button}: ${d.buttonNum}<br>${timesPressed}: ${d.count}<br>${correctStr}`; return `${button}: ${d.buttonNum}<br>${timesPressed}: ${d.count}<br>${correctStr}`;
} }

View file

@ -169,7 +169,7 @@ export function renderCalendar(
month: "long", month: "long",
day: "numeric", day: "numeric",
}); });
const cards = i18n.tr(i18n.TR.STATISTICS_REVIEWS, { reviews: d.count }); const cards = i18n.statisticsReviews({ reviews: d.count });
return `${date}<br>${cards}`; return `${date}<br>${cards}`;
} }

View file

@ -96,7 +96,7 @@ export function prepareData(
const minPct = Math.floor(bin.x0!); const minPct = Math.floor(bin.x0!);
const maxPct = Math.floor(bin.x1!); const maxPct = Math.floor(bin.x1!);
const percent = maxPct - minPct <= 10 ? `${bin.x0}%` : `${bin.x0}%-${bin.x1}%`; const percent = maxPct - minPct <= 10 ? `${bin.x0}%` : `${bin.x0}%-${bin.x1}%`;
return i18n.tr(i18n.TR.STATISTICS_CARD_EASE_TOOLTIP, { return i18n.statisticsCardEaseTooltip({
cards: bin.length, cards: bin.length,
percent, percent,
}); });

View file

@ -154,7 +154,7 @@ export function buildHistogram(
_percent: number _percent: number
): string { ): string {
const days = dayLabel(i18n, bin.x0!, bin.x1!); const days = dayLabel(i18n, bin.x0!, bin.x1!);
const cards = i18n.tr(i18n.TR.STATISTICS_CARDS_DUE, { const cards = i18n.statisticsCardsDue({
cards: binValue(bin as any), cards: binValue(bin as any),
}); });
const totalLabel = i18n.statisticsRunningTotal(); const totalLabel = i18n.statisticsRunningTotal();
@ -173,17 +173,17 @@ export function buildHistogram(
const tableData = [ const tableData = [
{ {
label: i18n.statisticsTotal(), label: i18n.statisticsTotal(),
value: i18n.tr(i18n.TR.STATISTICS_REVIEWS, { reviews: total }), value: i18n.statisticsReviews({ reviews: total }),
}, },
{ {
label: i18n.statisticsAverage(), label: i18n.statisticsAverage(),
value: i18n.tr(i18n.TR.STATISTICS_REVIEWS_PER_DAY, { value: i18n.statisticsReviewsPerDay({
count: Math.round(total / periodDays), count: Math.round(total / periodDays),
}), }),
}, },
{ {
label: i18n.statisticsDueTomorrow(), label: i18n.statisticsDueTomorrow(),
value: i18n.tr(i18n.TR.STATISTICS_REVIEWS, { value: i18n.statisticsReviews({
reviews: sourceData.dueCounts.get(1) ?? 0, reviews: sourceData.dueCounts.get(1) ?? 0,
}), }),
}, },

View file

@ -185,11 +185,11 @@ export function renderHours(
); );
function tooltipText(d: Hour): string { function tooltipText(d: Hour): string {
const hour = i18n.tr(i18n.TR.STATISTICS_HOURS_RANGE, { const hour = i18n.statisticsHoursRange({
hourStart: d.hour, hourStart: d.hour,
hourEnd: d.hour + 1, hourEnd: d.hour + 1,
}); });
const correct = i18n.tr(i18n.TR.STATISTICS_HOURS_CORRECT, { const correct = i18n.statisticsHoursCorrect({
correct: d.correctCount, correct: d.correctCount,
total: d.totalCount, total: d.totalCount,
percent: d.totalCount ? (d.correctCount / d.totalCount) * 100 : 0, percent: d.totalCount ? (d.correctCount / d.totalCount) * 100 : 0,

View file

@ -50,13 +50,13 @@ export function intervalLabel(
): string { ): string {
if (daysEnd - daysStart <= 1) { if (daysEnd - daysStart <= 1) {
// singular // singular
return i18n.tr(i18n.TR.STATISTICS_INTERVALS_DAY_SINGLE, { return i18n.statisticsIntervalsDaySingle({
day: daysStart, day: daysStart,
cards, cards,
}); });
} else { } else {
// range // range
return i18n.tr(i18n.TR.STATISTICS_INTERVALS_DAY_RANGE, { return i18n.statisticsIntervalsDayRange({
daysStart, daysStart,
daysEnd: daysEnd - 1, daysEnd: daysEnd - 1,
cards, cards,

View file

@ -228,7 +228,7 @@ export function renderReviews(
if (showTime) { if (showTime) {
return timeSpan(i18n, n / 1000); return timeSpan(i18n, n / 1000);
} else { } else {
return i18n.tr(i18n.TR.STATISTICS_REVIEWS, { reviews: n }); return i18n.statisticsReviews({ reviews: n });
} }
} }
@ -378,10 +378,10 @@ export function renderReviews(
averageAnswerTimeLabel: string; averageAnswerTimeLabel: string;
if (showTime) { if (showTime) {
totalString = timeSpan(i18n, total / 1000, false); totalString = timeSpan(i18n, total / 1000, false);
averageForDaysStudied = i18n.tr(i18n.TR.STATISTICS_MINUTES_PER_DAY, { averageForDaysStudied = i18n.statisticsMinutesPerDay({
count: Math.round(studiedAvg / 1000 / 60), count: Math.round(studiedAvg / 1000 / 60),
}); });
averageForPeriod = i18n.tr(i18n.TR.STATISTICS_MINUTES_PER_DAY, { averageForPeriod = i18n.statisticsMinutesPerDay({
count: Math.round(periodAvg / 1000 / 60), count: Math.round(periodAvg / 1000 / 60),
}); });
averageAnswerTimeLabel = i18n.statisticsAverageAnswerTimeLabel(); averageAnswerTimeLabel = i18n.statisticsAverageAnswerTimeLabel();
@ -396,16 +396,16 @@ export function renderReviews(
const totalSecs = total / 1000; const totalSecs = total / 1000;
const avgSecs = totalSecs / totalReviews; const avgSecs = totalSecs / totalReviews;
const cardsPerMin = (totalReviews * 60) / totalSecs; const cardsPerMin = (totalReviews * 60) / totalSecs;
averageAnswerTime = i18n.tr(i18n.TR.STATISTICS_AVERAGE_ANSWER_TIME, { averageAnswerTime = i18n.statisticsAverageAnswerTime({
"average-seconds": avgSecs, averageSeconds: avgSecs,
"cards-per-minute": cardsPerMin, cardsPerMinute: cardsPerMin,
}); });
} else { } else {
totalString = i18n.tr(i18n.TR.STATISTICS_REVIEWS, { reviews: total }); totalString = i18n.statisticsReviews({ reviews: total });
averageForDaysStudied = i18n.tr(i18n.TR.STATISTICS_REVIEWS_PER_DAY, { averageForDaysStudied = i18n.statisticsReviewsPerDay({
count: Math.round(studiedAvg), count: Math.round(studiedAvg),
}); });
averageForPeriod = i18n.tr(i18n.TR.STATISTICS_REVIEWS_PER_DAY, { averageForPeriod = i18n.statisticsReviewsPerDay({
count: Math.round(periodAvg), count: Math.round(periodAvg),
}); });
averageAnswerTime = averageAnswerTimeLabel = ""; averageAnswerTime = averageAnswerTimeLabel = "";
@ -414,7 +414,7 @@ export function renderReviews(
const tableData: TableDatum[] = [ const tableData: TableDatum[] = [
{ {
label: i18n.statisticsDaysStudied(), label: i18n.statisticsDaysStudied(),
value: i18n.tr(i18n.TR.STATISTICS_AMOUNT_OF_TOTAL_WITH_PERCENTAGE, { value: i18n.statisticsAmountOfTotalWithPercentage({
amount: studiedDays, amount: studiedDays,
total: periodDays, total: periodDays,
percent: Math.round((studiedDays / periodDays) * 100), percent: Math.round((studiedDays / periodDays) * 100),

View file

@ -76,7 +76,7 @@ export function gatherData(data: pb.BackendProto.GraphsOut, i18n: I18n): TodayDa
againCountText += ` ${againCount} (${((againCount / answerCount) * 100).toFixed( againCountText += ` ${againCount} (${((againCount / answerCount) * 100).toFixed(
2 2
)}%)`; )}%)`;
const typeCounts = i18n.tr(i18n.TR.STATISTICS_TODAY_TYPE_COUNTS, { const typeCounts = i18n.statisticsTodayTypeCounts({
learnCount, learnCount,
reviewCount, reviewCount,
relearnCount, relearnCount,
@ -84,7 +84,7 @@ export function gatherData(data: pb.BackendProto.GraphsOut, i18n: I18n): TodayDa
}); });
let matureText: string; let matureText: string;
if (matureCount) { if (matureCount) {
matureText = i18n.tr(i18n.TR.STATISTICS_TODAY_CORRECT_MATURE, { matureText = i18n.statisticsTodayCorrectMature({
correct: matureCorrect, correct: matureCorrect,
total: matureCount, total: matureCount,
percent: (matureCorrect / matureCount) * 100, percent: (matureCorrect / matureCount) * 100,

View file

@ -84,7 +84,7 @@ def get_args(args: List[Variable]) -> str:
def typescript_arg_name(arg: Variable) -> str: def typescript_arg_name(arg: Variable) -> str:
name = stringcase.camelcase(arg["name"]) name = stringcase.camelcase(arg["name"].replace("-", "_"))
if name == "new": if name == "new":
return "new_" return "new_"
else: else:

View file

@ -79,11 +79,14 @@ export function studiedToday(i18n: I18n, cards: number, secs: number): string {
if (cards > 0) { if (cards > 0) {
secsPer = secs / cards; secsPer = secs / cards;
} }
return i18n.tr(i18n.TR.STATISTICS_STUDIED_TODAY, { return i18n.statisticsStudiedToday({
unit: name,
secsPerCard: secsPer,
// these two are required, but don't appear in the generated code
// because they are included as part of a separate term - a byproduct
// of them having been ported from earlier Qt translations
cards, cards,
amount, amount,
unit: name,
"secs-per-card": secsPer,
}); });
} }
@ -138,19 +141,19 @@ export function dayLabel(i18n: I18n, daysStart: number, daysEnd: number): string
if (larger - smaller <= 1) { if (larger - smaller <= 1) {
// singular // singular
if (daysStart >= 0) { if (daysStart >= 0) {
return i18n.tr(i18n.TR.STATISTICS_IN_DAYS_SINGLE, { days: daysStart }); return i18n.statisticsInDaysSingle({ days: daysStart });
} else { } else {
return i18n.tr(i18n.TR.STATISTICS_DAYS_AGO_SINGLE, { days: -daysStart }); return i18n.statisticsDaysAgoSingle({ days: -daysStart });
} }
} else { } else {
// range // range
if (daysStart >= 0) { if (daysStart >= 0) {
return i18n.tr(i18n.TR.STATISTICS_IN_DAYS_RANGE, { return i18n.statisticsInDaysRange({
daysStart, daysStart,
daysEnd: daysEnd - 1, daysEnd: daysEnd - 1,
}); });
} else { } else {
return i18n.tr(i18n.TR.STATISTICS_DAYS_AGO_RANGE, { return i18n.statisticsDaysAgoRange({
daysStart: Math.abs(daysEnd - 1), daysStart: Math.abs(daysEnd - 1),
daysEnd: -daysStart, daysEnd: -daysStart,
}); });