77 lines
1.9 KiB
Svelte
77 lines
1.9 KiB
Svelte
<script lang="ts" context="module">
|
|
const contextKey = {ctx: "scopeCtx"};
|
|
|
|
interface ScopeContextData {
|
|
scope: Readable<Scope>
|
|
lastHistoryRange: Writable<string>
|
|
upsertStat(stat: Stat): void
|
|
deleteStat(stat: Stat): void
|
|
updateScope(scope: Scope): void
|
|
};
|
|
|
|
const fallback: ScopeContextData = {
|
|
scope: readable({stats: []} as Scope),
|
|
lastHistoryRange: writable("last:14d"),
|
|
upsertStat: () => {},
|
|
deleteStat: () => {},
|
|
updateScope: () => {},
|
|
}
|
|
|
|
export function getScopeContext() {
|
|
return getContext(contextKey) as ScopeContextData || fallback
|
|
}
|
|
</script>
|
|
|
|
<script lang="ts">
|
|
import type Scope from "$lib/models/scope";
|
|
import { readable, writable, type Readable, type Writable } from "svelte/store";
|
|
import { getContext, setContext } from "svelte";
|
|
import type Stat from "$lib/models/stat";
|
|
|
|
export let scope: Scope;
|
|
|
|
let scopeWritable = writable<Scope>(scope);
|
|
let lastHistoryRange = writable<string>(global?.localStorage?.getItem("sl3.history.last_range") || "last:14d");
|
|
|
|
setContext<ScopeContextData>(contextKey, {
|
|
scope: {subscribe: scopeWritable.subscribe},
|
|
lastHistoryRange,
|
|
upsertStat, deleteStat, updateScope,
|
|
});
|
|
|
|
function updateScope(scope: Scope) {
|
|
scopeWritable.set(scope);
|
|
}
|
|
|
|
function upsertStat(stat: Stat) {
|
|
scopeWritable.update(s => ({
|
|
...s,
|
|
stats: [
|
|
...s.stats.filter(s => s.id != stat.id),
|
|
{...stat},
|
|
].sort((a,b) => (
|
|
a.primary == b.primary ? a.name.localeCompare(b.name) : Number(b.primary) - Number(a.primary)
|
|
))
|
|
}));
|
|
}
|
|
|
|
function deleteStat(stat: Stat) {
|
|
scopeWritable.update(s => ({
|
|
...s,
|
|
stats: s.stats.filter(s => s.id != stat.id),
|
|
}));
|
|
}
|
|
|
|
let lastWritten: Scope;
|
|
|
|
$: if (lastWritten !== scope) {
|
|
$scopeWritable = scope
|
|
lastWritten = scope
|
|
}
|
|
|
|
$: if (global?.localStorage) {
|
|
localStorage.setItem("sl3.history.last_range", $lastHistoryRange)
|
|
}
|
|
</script>
|
|
|
|
<slot></slot> |