anki/ts/graphs/buttons.ts
Damien Elmes a3d9f90af5 update to latest rules_nodejs & switch to ts_project
ts_library() is deprecated and will presumably be dropped from a
future rules_nodejs, and it wasn't working with the jest tests
after updating, so we switch over to ts_project().

There are some downsides:

- It's a bit slower, as the worker mode doesn't appear to function
at the moment.
- Getting it working with a mix of source files and generated files
was quite tricky, especially as things behave differently on Windows,
and differently when editing with VS Code. Solved with a small patch
to the rules, and a wrapper script that copies everything into the
bin folder first. To keep VS Code working correctly as well, the built
files are symlinked into the source folder.
- TS libraries are not implicitly linked to node_modules, so they
can't be imported with an absolute name like "lib/proto" - we need
to use relative paths like "../lib/proto" instead. Adjusting "paths"
in tsconfig.json makes it work for TS compilation, but then it fails
at the esbuild stage. We could resolve it by wrapping the TS
libraries in a subsequent js_library() call, but that has the downside
of losing the transient dependencies, meaning they need to be listed
again.  Alternatively we might be able to solve it in the future by
adjusting esbuild, but for now the paths have been made relative to
keep things simple.

Upsides:

- Along with updates to the Svelte tooling, Svelte typing has improved.
All exports made in a Svelte file are now visible to other files that
import them, and we no longer rebuild the Svelte files when TS files
are updated, as the Svelte files do no type checking themselves, and
are just a simple transpilation. Svelte-check now works on Windows again,
and there should be no errors when editing in VS Code after you've
built the project. The only downside seems to be that cmd+clicking
on a Svelte imports jumps to the .d.ts file instead of the original now;
presumably they'll fix that in a future plugin update.
- Each subfolder now has its own tsconfig.json, and tsc can be called
directly for testing purposes (but beware it will place build products
in the source tree): ts/node_modules/.bin/tsc -b ts
- We can drop the custom esbuild_toolchain, as it's included in the
latest rules_nodejs.

Other changes:

- "image_module_support" is moved into lib/, and imported with
<reference types=...>
- Images are now imported directly from their npm package; the
extra copy step has been removed.

Windows users may need to use "bazel clean" before building this,
due to old files lying around in the build folder.
2021-10-01 12:52:53 +10:00

264 lines
7.8 KiB
TypeScript

// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
/* eslint
@typescript-eslint/no-non-null-assertion: "off",
@typescript-eslint/no-explicit-any: "off",
*/
import { Stats } from "../lib/proto";
import {
interpolateRdYlGn,
select,
pointer,
scaleLinear,
scaleBand,
scaleSequential,
axisBottom,
axisLeft,
sum,
} from "d3";
import { showTooltip, hideTooltip } from "./tooltip";
import {
GraphBounds,
setDataAvailable,
GraphRange,
millisecondCutoffForRange,
} from "./graph-helpers";
import * as tr from "../lib/i18n";
type ButtonCounts = [number, number, number, number];
export interface GraphData {
learning: ButtonCounts;
young: ButtonCounts;
mature: ButtonCounts;
}
const ReviewKind = Stats.RevlogEntry.ReviewKind;
export function gatherData(data: Stats.GraphsResponse, range: GraphRange): GraphData {
const cutoff = millisecondCutoffForRange(range, data.nextDayAtSecs);
const learning: ButtonCounts = [0, 0, 0, 0];
const young: ButtonCounts = [0, 0, 0, 0];
const mature: ButtonCounts = [0, 0, 0, 0];
for (const review of data.revlog as Stats.RevlogEntry[]) {
if (cutoff && (review.id as number) < cutoff) {
continue;
}
let buttonNum = review.buttonChosen;
if (buttonNum <= 0 || buttonNum > 4) {
continue;
}
let buttons = learning;
switch (review.reviewKind) {
case ReviewKind.LEARNING:
case ReviewKind.RELEARNING:
// V1 scheduler only had 3 buttons in learning
if (buttonNum === 4 && data.schedulerVersion === 1) {
buttonNum = 3;
}
break;
case ReviewKind.REVIEW:
if (review.lastInterval < 21) {
buttons = young;
} else {
buttons = mature;
}
break;
case ReviewKind.FILTERED:
break;
}
buttons[buttonNum - 1] += 1;
}
return { learning, young, mature };
}
type GroupKind = "learning" | "young" | "mature";
interface Datum {
buttonNum: number;
group: GroupKind;
count: number;
}
interface TotalCorrect {
total: number;
correct: number;
percent: string;
}
export function renderButtons(
svgElem: SVGElement,
bounds: GraphBounds,
origData: Stats.GraphsResponse,
range: GraphRange
): void {
const sourceData = gatherData(origData, range);
const data = [
...sourceData.learning.map((count: number, idx: number) => {
return {
buttonNum: idx + 1,
group: "learning",
count,
} as Datum;
}),
...sourceData.young.map((count: number, idx: number) => {
return {
buttonNum: idx + 1,
group: "young",
count,
} as Datum;
}),
...sourceData.mature.map((count: number, idx: number) => {
return {
buttonNum: idx + 1,
group: "mature",
count,
} as Datum;
}),
];
const totalCorrect = (kind: GroupKind): TotalCorrect => {
const groupData = data.filter((d) => d.group == kind);
const total = sum(groupData, (d) => d.count);
const correct = sum(
groupData.filter((d) => d.buttonNum > 1),
(d) => d.count
);
const percent = total ? ((correct / total) * 100).toFixed(2) : "0";
return { total, correct, percent };
};
const yMax = Math.max(...data.map((d) => d.count));
const svg = select(svgElem);
const trans = svg.transition().duration(600) as any;
if (!yMax) {
setDataAvailable(svg, false);
return;
} else {
setDataAvailable(svg, true);
}
const xGroup = scaleBand()
.domain(["learning", "young", "mature"])
.range([bounds.marginLeft, bounds.width - bounds.marginRight]);
svg.select<SVGGElement>(".x-ticks")
.call((selection) =>
selection.transition(trans).call(
axisBottom(xGroup)
.tickFormat(((d: GroupKind) => {
let kind: string;
switch (d) {
case "learning":
kind = tr.statisticsCountsLearningCards();
break;
case "young":
kind = tr.statisticsCountsYoungCards();
break;
case "mature":
default:
kind = tr.statisticsCountsMatureCards();
break;
}
return `${kind} \u200e(${totalCorrect(d).percent}%)`;
}) as any)
.tickSizeOuter(0)
)
)
.attr("direction", "ltr");
const xButton = scaleBand()
.domain(["1", "2", "3", "4"])
.range([0, xGroup.bandwidth()])
.paddingOuter(1)
.paddingInner(0.1);
const colour = scaleSequential(interpolateRdYlGn).domain([1, 4]);
// y scale
const y = scaleLinear()
.range([bounds.height - bounds.marginBottom, bounds.marginTop])
.domain([0, yMax]);
svg.select<SVGGElement>(".y-ticks")
.call((selection) =>
selection.transition(trans).call(
axisLeft(y)
.ticks(bounds.height / 50)
.tickSizeOuter(0)
)
)
.attr("direction", "ltr");
// x bars
const updateBar = (sel: any): any => {
return sel
.attr("width", xButton.bandwidth())
.attr("opacity", 0.8)
.transition(trans)
.attr(
"x",
(d: Datum) => xGroup(d.group)! + xButton(d.buttonNum.toString())!
)
.attr("y", (d: Datum) => y(d.count)!)
.attr("height", (d: Datum) => y(0)! - y(d.count)!)
.attr("fill", (d: Datum) => colour(d.buttonNum));
};
svg.select("g.bars")
.selectAll("rect")
.data(data)
.join(
(enter) =>
enter
.append("rect")
.attr("rx", 1)
.attr(
"x",
(d: Datum) =>
xGroup(d.group)! + xButton(d.buttonNum.toString())!
)
.attr("y", y(0)!)
.attr("height", 0)
.call(updateBar),
(update) => update.call(updateBar),
(remove) =>
remove.call((remove) =>
remove.transition(trans).attr("height", 0).attr("y", y(0)!)
)
);
// hover/tooltip
function tooltipText(d: Datum): string {
const button = tr.statisticsAnswerButtonsButtonNumber();
const timesPressed = tr.statisticsAnswerButtonsButtonPressed();
const correctStr = tr.statisticsHoursCorrect(totalCorrect(d.group));
return `${button}: ${d.buttonNum}<br>${timesPressed}: ${d.count}<br>${correctStr}`;
}
svg.select("g.hover-columns")
.selectAll("rect")
.data(data)
.join("rect")
.attr("x", (d: Datum) => xGroup(d.group)! + xButton(d.buttonNum.toString())!)
.attr("y", () => y(yMax!)!)
.attr("width", xButton.bandwidth())
.attr("height", () => y(0)! - y(yMax!)!)
.on("mousemove", (event: MouseEvent, d: Datum) => {
const [x, y] = pointer(event, document.body);
showTooltip(tooltipText(d), x, y);
})
.on("mouseout", hideTooltip);
}