anki/ts/graphs/calendar.ts

232 lines
7.1 KiB
TypeScript
Raw Normal View History

2020-06-30 07:09:20 +02:00
// 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",
*/
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-09-30 14:16:29 +02:00
import { Stats } from "../lib/proto";
2021-01-18 23:27:57 +01:00
import {
interpolateBlues,
select,
pointer,
scaleLinear,
scaleSequentialSqrt,
2021-01-18 23:27:57 +01:00
timeDay,
timeYear,
timeSunday,
timeMonday,
timeFriday,
timeSaturday,
} from "d3";
import type { CountableTimeInterval } from "d3";
import { showTooltip, hideTooltip } from "./tooltip";
import {
GraphBounds,
setDataAvailable,
RevlogRange,
SearchDispatch,
} from "./graph-helpers";
import { clickableClass } from "./graph-styles";
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-09-30 14:16:29 +02:00
import { i18n } from "../lib/i18n";
import * as tr from "../lib/i18n";
2020-06-30 07:09:20 +02:00
export interface GraphData {
// indexed by day, where day is relative to today
reviewCount: Map<number, number>;
2021-01-18 23:27:57 +01:00
timeFunction: CountableTimeInterval;
weekdayLabels: number[];
2020-06-30 07:09:20 +02:00
}
interface DayDatum {
day: number;
count: number;
// 0-51
weekNumber: number;
// 0-6
weekDay: number;
date: Date;
}
type WeekdayType = Stats.GraphPreferences.Weekday;
const Weekday = Stats.GraphPreferences.Weekday; /* enum */
export function gatherData(
data: Stats.GraphsResponse,
firstDayOfWeek: WeekdayType
): GraphData {
2020-06-30 07:09:20 +02:00
const reviewCount = new Map<number, number>();
for (const review of data.revlog as Stats.RevlogEntry[]) {
2020-06-30 07:09:20 +02:00
if (review.buttonChosen == 0) {
continue;
}
const day = Math.ceil(
((review.id as number) / 1000 - data.nextDayAtSecs) / 86400
);
const count = reviewCount.get(day) ?? 0;
reviewCount.set(day, count + 1);
}
const timeFunction = timeFunctionForDay(firstDayOfWeek);
const weekdayLabels: number[] = [];
for (let i = 0; i < 7; i++) {
weekdayLabels.push((firstDayOfWeek + i) % 7);
2021-01-20 21:17:36 +01:00
}
return { reviewCount, timeFunction, weekdayLabels };
2020-06-30 07:09:20 +02:00
}
export function renderCalendar(
svgElem: SVGElement,
bounds: GraphBounds,
sourceData: GraphData,
dispatch: SearchDispatch,
2020-06-30 07:09:20 +02:00
targetYear: number,
nightMode: boolean,
revlogRange: RevlogRange,
setFirstDayOfWeek: (d: number) => void
2020-06-30 07:09:20 +02:00
): void {
const svg = select(svgElem);
const now = new Date();
const nowForYear = new Date();
nowForYear.setFullYear(targetYear);
const x = scaleLinear()
.range([bounds.marginLeft, bounds.width - bounds.marginRight])
2021-01-20 21:17:36 +01:00
.domain([-1, 53]);
2020-06-30 07:09:20 +02:00
// map of 0-365 -> day
const dayMap: Map<number, DayDatum> = new Map();
let maxCount = 0;
for (const [day, count] of sourceData.reviewCount.entries()) {
const date = new Date(now.getTime() + day * 86400 * 1000);
if (date.getFullYear() != targetYear) {
continue;
}
2021-01-18 23:23:55 +01:00
const weekNumber = sourceData.timeFunction.count(timeYear(date), date);
const weekDay = timeDay.count(sourceData.timeFunction(date), date);
2020-06-30 07:09:20 +02:00
const yearDay = timeDay.count(timeYear(date), date);
dayMap.set(yearDay, { day, count, weekNumber, weekDay, date } as DayDatum);
if (count > maxCount) {
maxCount = count;
}
}
2020-07-06 06:01:49 +02:00
if (!maxCount) {
setDataAvailable(svg, false);
return;
} else {
setDataAvailable(svg, true);
}
2020-06-30 07:09:20 +02:00
// fill in any blanks
const startDate = timeYear(nowForYear);
const oneYearAgoFromNow = new Date(now);
oneYearAgoFromNow.setFullYear(now.getFullYear() - 1);
for (let i = 0; i < 365; i++) {
2020-06-30 07:09:20 +02:00
const date = new Date(startDate.getTime() + i * 86400 * 1000);
if (date > now) {
// don't fill out future dates
continue;
}
if (revlogRange == RevlogRange.Year && date < oneYearAgoFromNow) {
// don't fill out dates older than a year
continue;
}
2020-06-30 07:09:20 +02:00
const yearDay = timeDay.count(timeYear(date), date);
if (!dayMap.has(yearDay)) {
2021-01-18 23:23:55 +01:00
const weekNumber = sourceData.timeFunction.count(timeYear(date), date);
const weekDay = timeDay.count(sourceData.timeFunction(date), date);
2020-06-30 07:09:20 +02:00
dayMap.set(yearDay, {
day: yearDay,
count: 0,
weekNumber,
weekDay,
date,
} as DayDatum);
}
}
const data = Array.from(dayMap.values());
2020-06-30 08:23:46 +02:00
const cappedRange = scaleLinear().range([0.2, nightMode ? 0.8 : 1]);
const blues = scaleSequentialSqrt()
.domain([0, maxCount])
.interpolator((n) => interpolateBlues(cappedRange(n)!));
2020-06-30 07:09:20 +02:00
function tooltipText(d: DayDatum): string {
const date = d.date.toLocaleString(i18n.langs, {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
});
const cards = tr.statisticsReviews({ reviews: d.count });
2020-06-30 07:09:20 +02:00
return `${date}<br>${cards}`;
}
const height = bounds.height / 10;
2021-01-20 21:17:36 +01:00
const emptyColour = nightMode ? "#333" : "#ddd";
svg.select("g.weekdays")
.selectAll("text")
.data(sourceData.weekdayLabels)
.join("text")
.text((d: number) => i18n.weekdayLabel(d))
2021-01-20 21:17:36 +01:00
.attr("width", x(-1)! - 2)
.attr("height", height - 2)
.attr("x", x(1)! - 3)
2021-01-20 21:17:36 +01:00
.attr("y", (_d, index) => bounds.marginTop + index * height)
.attr("fill", nightMode ? "#ddd" : "black")
2021-01-20 21:17:36 +01:00
.attr("dominant-baseline", "hanging")
.attr("text-anchor", "end")
2021-01-20 21:17:36 +01:00
.attr("font-size", "small")
.attr("font-family", "monospace")
2021-04-02 05:25:38 +02:00
.attr("direction", "ltr")
.style("user-select", "none")
.on("click", null)
.filter((d: number) =>
[Weekday.SUNDAY, Weekday.MONDAY, Weekday.FRIDAY, Weekday.SATURDAY].includes(
d
)
)
.on("click", (_event: MouseEvent, d: number) => setFirstDayOfWeek(d));
2021-01-20 21:17:36 +01:00
svg.select("g.days")
2020-06-30 07:09:20 +02:00
.selectAll("rect")
.data(data)
.join("rect")
2020-06-30 08:39:30 +02:00
.attr("fill", emptyColour)
.attr("width", (d: DayDatum) => x(d.weekNumber + 1)! - x(d.weekNumber)! - 2)
2020-06-30 07:09:20 +02:00
.attr("height", height - 2)
.attr("x", (d: DayDatum) => x(d.weekNumber + 1)!)
.attr("y", (d: DayDatum) => bounds.marginTop + d.weekDay * height)
.on("mousemove", (event: MouseEvent, d: DayDatum) => {
2021-01-30 02:35:33 +01:00
const [x, y] = pointer(event, document.body);
2020-06-30 07:09:20 +02:00
showTooltip(tooltipText(d), x, y);
})
.on("mouseout", hideTooltip)
.attr("class", (d: DayDatum): string => (d.count > 0 ? clickableClass : ""))
.on("click", function (_event: MouseEvent, d: DayDatum) {
if (d.count > 0) {
dispatch("search", { query: `"prop:rated=${d.day}"` });
}
})
2020-06-30 08:39:30 +02:00
.transition()
.duration(800)
.attr("fill", (d: DayDatum) => (d.count === 0 ? emptyColour : blues(d.count)!));
2020-06-30 07:09:20 +02:00
}
function timeFunctionForDay(firstDayOfWeek: WeekdayType): CountableTimeInterval {
switch (firstDayOfWeek) {
case Weekday.MONDAY:
return timeMonday;
case Weekday.FRIDAY:
return timeFriday;
case Weekday.SATURDAY:
return timeSaturday;
default:
return timeSunday;
}
}