anki/ts/graphs/WithGraphData.svelte

87 lines
2.4 KiB
Svelte
Raw Normal View History

<!--
Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
2021-03-21 22:06:25 +01:00
<script lang="typescript">
2021-03-22 15:41:43 +01:00
import type { Writable } from "svelte/store";
2021-04-16 03:10:39 +02:00
import type { PreferenceRaw, PreferencePayload } from "sveltelib/preferences";
2021-03-22 15:41:43 +01:00
import { Stats } from "lib/proto";
import { postRequest } from "lib/postrequest";
import useAsync from "sveltelib/async";
import useAsyncReactive from "sveltelib/asyncReactive";
import { getPreferences } from "sveltelib/preferences";
2021-03-21 22:06:25 +01:00
import { daysToRevlogRange } from "./graph-helpers";
2021-03-21 22:06:25 +01:00
export let search: Writable<string>;
export let days: Writable<number>;
2021-03-21 22:06:25 +01:00
async function getGraphData(
search: string,
days: number
): Promise<Stats.GraphsResponse> {
return Stats.GraphsResponse.decode(
await postRequest("/_anki/graphData", JSON.stringify({ search, days }))
);
}
async function getGraphPreferences(): Promise<Stats.GraphPreferences> {
return Stats.GraphPreferences.decode(
await postRequest("/_anki/graphPreferences", JSON.stringify({}))
);
}
async function setGraphPreferences(
prefs: PreferencePayload<Stats.GraphPreferences>
): Promise<void> {
await postRequest(
"/_anki/setGraphPreferences",
Stats.GraphPreferences.encode(prefs).finish()
);
}
const {
loading: graphLoading,
error: graphError,
value: graphValue,
} = useAsyncReactive(() => getGraphData($search, $days), [search, days]);
2021-03-22 15:25:49 +01:00
const {
loading: prefsLoading,
error: prefsError,
value: prefsValue,
} = useAsync(() =>
getPreferences(
getGraphPreferences,
setGraphPreferences,
Stats.GraphPreferences.toObject.bind(Stats.GraphPreferences) as (
preferences: Stats.GraphPreferences,
2021-04-16 03:10:39 +02:00
options: { defaults: boolean }
) => PreferenceRaw<Stats.GraphPreferences>
)
);
2021-03-21 22:06:25 +01:00
$: revlogRange = daysToRevlogRange($days);
$: {
if ($graphError) {
alert($graphError);
}
}
$: {
if ($prefsError) {
alert($prefsError);
}
}
2021-03-21 22:06:25 +01:00
</script>
<slot
2021-03-21 22:35:53 +01:00
{revlogRange}
loading={$graphLoading || $prefsLoading}
sourceData={$graphValue}
preferences={$prefsValue}
/>