tutu/src/masto/timelines.ts

89 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-07-14 12:28:44 +00:00
import { type mastodon } from "masto";
import { Accessor, createEffect, createResource, createSignal } from "solid-js";
import { createStore } from "solid-js/store";
2024-07-14 12:28:44 +00:00
type TimelineFetchTips = {
direction?: "new" | "old";
};
type Timeline = {
list(params: {
maxId?: string;
minId?: string;
}): mastodon.Paginator<mastodon.v1.Status[], unknown>;
};
2024-08-05 07:33:00 +00:00
export function useTimeline(timeline: Accessor<Timeline>) {
2024-07-14 12:28:44 +00:00
let otl: Timeline | undefined;
2024-08-12 14:29:55 +00:00
let npager: mastodon.Paginator<mastodon.v1.Status[], unknown> | undefined;
let opager: mastodon.Paginator<mastodon.v1.Status[], unknown> | undefined;
const [snapshot, { refetch }] = createResource<
2024-08-12 14:29:55 +00:00
{
records: mastodon.v1.Status[];
direction: "new" | "old";
tlChanged: boolean;
},
2024-07-14 12:28:44 +00:00
[Timeline],
TimelineFetchTips | undefined
>(
() => [timeline()] as const,
async ([tl], info) => {
2024-08-12 14:29:55 +00:00
let tlChanged = false;
2024-07-14 12:28:44 +00:00
if (otl !== tl) {
2024-08-12 14:29:55 +00:00
console.debug("timeline reset");
npager = opager = undefined;
2024-07-14 12:28:44 +00:00
otl = tl;
2024-08-12 14:29:55 +00:00
tlChanged = true;
2024-07-14 12:28:44 +00:00
}
const direction =
typeof info.refetching !== "boolean"
2024-08-12 14:29:55 +00:00
? (info.refetching?.direction ?? "old")
2024-07-14 12:28:44 +00:00
: "old";
if (direction === "old") {
2024-08-12 14:29:55 +00:00
if (!opager) {
opager = tl.list({}).setDirection("next");
2024-07-14 12:28:44 +00:00
}
2024-08-12 14:29:55 +00:00
const next = await opager.next();
return {
2024-08-12 14:29:55 +00:00
direction,
records: next.value ?? [],
end: next.done,
tlChanged,
};
2024-07-14 12:28:44 +00:00
} else {
2024-08-12 14:29:55 +00:00
if (!npager) {
npager = tl.list({}).setDirection("prev");
2024-07-14 12:28:44 +00:00
}
2024-08-12 14:29:55 +00:00
const next = await npager.next();
const page = next.value ?? [];
return { direction, records: page, end: next.done, tlChanged };
2024-07-14 12:28:44 +00:00
}
},
);
const [store, setStore] = createStore([] as mastodon.v1.Status[]);
createEffect(() => {
const shot = snapshot();
if (!shot) return;
2024-08-12 14:29:55 +00:00
const { direction, records, tlChanged } = shot;
if (tlChanged) {
setStore(() => []);
}
if (direction == "new") {
setStore((x) => [...records, ...x]);
} else if (direction == "old") {
setStore((x) => [...x, ...records]);
}
});
return [
store,
snapshot,
2024-07-14 12:28:44 +00:00
{
refetch,
mutate: setStore,
2024-07-14 12:28:44 +00:00
},
] as const;
2024-07-14 12:28:44 +00:00
}