anki/ts/graphs/added.ts

141 lines
3.8 KiB
TypeScript
Raw Normal View History

2020-06-24 01:41:07 +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-explicit-any: "off",
*/
import type { Bin } from "d3";
import {
extent,
histogram,
interpolateBlues,
scaleLinear,
scaleSequential,
sum,
} from "d3";
Refactor i18n (#1405) Merging note: the typing changes were fixed in a separate PR. * Put rootDirs into subprojects - typings do not work for any ts or svelte files - if we set the 'rootDirs' in ts/tsconfig.json to '../bazel-bin/ts' and then inherit them from e.g. editor, the root will be changed to '../../bazel-bin/ts', however editor needs look in '../../bazel-bin/ts/editor' instead. * Rename i18n and i18n_helpers to i18n-generated and i18n - This way, we can restrict the awkwardness of importing files outside the ts directory within lib * Fix missing typing of i18n and backend_proto by adding back symlinks * Split up i18n-generated into i18n-{translate,modules} * Change i18n from singleton to functions * Revert "Put rootDirs into subprojects" This partially reverts commit e1d4292ce3979e7b7ee21bf3951b8a462d45c29c. It seems like this might not be necessary after all. However some other change made on this branch seems to have fixed the .svelte.d.ts imports * Introduce i18n-bundles to remove circular import There was a circular import i18n.ts <-> i18n-translate.ts * Create own directory for i18n * Move lib/i18n/translate to lib/translate * This restores tree shaking * Update tsconfig libs and module * es2018-2020 have wide support on all modern browsers including * Switch bundles and langs inside i18n to variables again * Add missing copyright header * Rename translate.ts to ftl.ts * Remove the symlinks again I added them to fix to have completion for tr, however this would have also have meant to abandon the tree shaking. As we want to have tree shaking, it's also not necessary to have the symlinks anymore * Revert "Update tsconfig libs and module" This reverts commit 0a96776a475e9901c1f9f3407c726d1d002fb9ef. * move withCollapsedWhitespace back to i18n/utils * Add back /ts as in rootDirs
2021-10-07 15:31:49 +02:00
import * as tr from "../lib/ftl";
import type { Cards, Stats } from "../lib/proto";
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 { dayLabel } from "../lib/time";
import type { SearchDispatch, TableDatum } from "./graph-helpers";
import { GraphRange } from "./graph-helpers";
import type { HistogramData } from "./histogram-graph";
2020-06-24 01:41:07 +02:00
export interface GraphData {
daysAdded: number[];
}
export function gatherData(data: Stats.GraphsResponse): GraphData {
2021-07-10 11:52:31 +02:00
const daysAdded = (data.cards as Cards.Card[]).map((card) => {
2020-06-24 01:41:07 +02:00
const elapsedSecs = (card.id as number) / 1000 - data.nextDayAtSecs;
return Math.ceil(elapsedSecs / 86400);
});
return { daysAdded };
}
function makeQuery(start: number, end: number): string {
const include = `"added:${start}"`;
if (start === 1) {
return include;
}
const exclude = `-"added:${end}"`;
return `${include} AND ${exclude}`;
}
2020-06-26 11:25:02 +02:00
export function buildHistogram(
data: GraphData,
range: GraphRange,
dispatch: SearchDispatch,
browserLinksSupported: boolean,
2020-08-04 08:01:11 +02:00
): [HistogramData | null, TableDatum[]] {
2020-06-24 01:41:07 +02:00
// get min/max
const total = data.daysAdded.length;
if (!total) {
2020-08-04 08:01:11 +02:00
return [null, []];
2020-06-24 01:41:07 +02:00
}
const [xMinOrig] = extent(data.daysAdded);
2020-06-24 01:41:07 +02:00
let xMin = xMinOrig;
// cap max to selected range
switch (range) {
case GraphRange.Month:
2020-06-24 01:41:07 +02:00
xMin = -31;
break;
case GraphRange.ThreeMonths:
2020-06-24 01:41:07 +02:00
xMin = -90;
break;
case GraphRange.Year:
2020-06-24 01:41:07 +02:00
xMin = -365;
break;
case GraphRange.AllTime:
2020-06-24 01:41:07 +02:00
break;
}
const xMax = 1;
const desiredBars = Math.min(70, Math.abs(xMin!));
const scale = scaleLinear().domain([xMin!, xMax]);
const bins = histogram()
.domain(scale.domain() as any)
.thresholds(scale.ticks(desiredBars))(data.daysAdded);
2020-07-06 06:01:49 +02:00
// empty graph?
if (!sum(bins, (bin) => bin.length)) {
2020-08-04 08:01:11 +02:00
return [null, []];
2020-07-06 06:01:49 +02:00
}
const adjustedRange = scaleLinear().range([0.7, 0.3]);
const colourScale = scaleSequential((n) =>
interpolateBlues(adjustedRange(n)!),
).domain([xMax!, xMin!]);
2020-06-24 01:41:07 +02:00
2020-08-04 08:01:11 +02:00
const totalInPeriod = sum(bins, (bin) => bin.length);
const periodDays = Math.abs(xMin!);
const cardsPerDay = Math.round(totalInPeriod / periodDays);
2020-08-04 08:01:11 +02:00
const tableData = [
{
label: tr.statisticsTotal(),
value: tr.statisticsCards({ cards: totalInPeriod }),
2020-08-04 08:01:11 +02:00
},
{
label: tr.statisticsAverage(),
value: tr.statisticsCardsPerDay({ count: cardsPerDay }),
2020-08-04 08:01:11 +02:00
},
];
2020-06-28 12:52:38 +02:00
function hoverText(
2021-01-30 02:08:01 +01:00
bin: Bin<number, number>,
2020-06-28 12:52:38 +02:00
cumulative: number,
_percent: number,
2020-06-28 12:52:38 +02:00
): string {
const day = dayLabel(bin.x0!, bin.x1!);
const cards = tr.statisticsCards({ cards: bin.length });
const total = tr.statisticsRunningTotal();
const totalCards = tr.statisticsCards({ cards: cumulative });
2020-06-28 12:52:38 +02:00
return `${day}:<br>${cards}<br>${total}: ${totalCards}`;
}
function onClick(bin: Bin<number, number>): void {
const start = Math.abs(bin.x0!) + 1;
const end = Math.abs(bin.x1!) + 1;
const query = makeQuery(start, end);
dispatch("search", { query });
2021-01-07 12:22:50 +01:00
}
return [
2021-01-08 14:28:38 +01:00
{
scale,
bins,
total: totalInPeriod,
hoverText,
2021-01-25 17:36:04 +01:00
onClick: browserLinksSupported ? onClick : null,
2021-01-08 14:28:38 +01:00
colourScale,
showArea: true,
},
tableData,
];
2020-06-24 01:41:07 +02:00
}