useTimeline: use store to provide partial editing

This commit is contained in:
thislight 2024-08-06 20:27:30 +08:00
parent cde30f8e29
commit 2d75ecfbe3
3 changed files with 65 additions and 30 deletions

View file

@ -1,5 +1,6 @@
import { type mastodon } from "masto";
import { Accessor, createResource, createSignal } from "solid-js";
import { Accessor, createEffect, createResource, createSignal } from "solid-js";
import { createStore } from "solid-js/store";
type TimelineFetchTips = {
direction?: "new" | "old";
@ -17,8 +18,8 @@ export function useTimeline(timeline: Accessor<Timeline>) {
let maxId: string | undefined;
let otl: Timeline | undefined;
const idSet = new Set<string>();
return createResource<
mastodon.v1.Status[],
const [snapshot, { refetch }] = createResource<
{ records: mastodon.v1.Status[]; direction: "old" | "new" },
[Timeline],
TimelineFetchTips | undefined
>(
@ -28,7 +29,6 @@ export function useTimeline(timeline: Accessor<Timeline>) {
minId = undefined;
maxId = undefined;
idSet.clear();
info.value = [];
otl = tl;
}
const direction =
@ -44,7 +44,6 @@ export function useTimeline(timeline: Accessor<Timeline>) {
minId: maxId,
},
);
const old = info.value || [];
const diff = pager.filter((x) => !idSet.has(x.id));
for (const v of diff.map((x) => x.id)) {
idSet.add(v);
@ -54,20 +53,39 @@ export function useTimeline(timeline: Accessor<Timeline>) {
if (!maxId && pager.length > 0) {
maxId = pager[0].id;
}
return [...old, ...diff];
return {
direction: "old" as const,
records: diff,
};
} else {
maxId = pager.length > 0 ? pager[0].id : undefined;
if (!minId && pager.length > 0) {
minId = pager[pager.length - 1]?.id;
}
return [...diff, ...old];
return { direction: "new" as const, records: diff };
}
},
{
initialValue: [],
storage(init) {
return createSignal(init, { equals: false });
},
},
);
const [store, setStore] = createStore([] as mastodon.v1.Status[]);
createEffect(() => {
const shot = snapshot();
if (!shot) return;
const { direction, records } = shot;
if (direction == "new") {
setStore((x) => [...records, ...x]);
} else if (direction == "old") {
setStore((x) => [...x, ...records]);
}
});
return [
store,
snapshot,
{
refetch,
mutate: setStore,
},
] as const;
}