48 lines
1.3 KiB
TypeScript
48 lines
1.3 KiB
TypeScript
"use client";
|
|
|
|
import { z } from "zod";
|
|
|
|
import { StorageKeys } from "@/data/storage/storage_keys";
|
|
import { Result, SessionAsyncUtil, type Result as ResultT } from "@/utils";
|
|
|
|
const ChatScrollSessionSchema = z.object({
|
|
scrollTop: z.number(),
|
|
scrollHeight: z.number(),
|
|
clientHeight: z.number(),
|
|
distanceFromBottom: z.number(),
|
|
savedAt: z.number(),
|
|
});
|
|
|
|
export type ChatScrollSession = z.output<typeof ChatScrollSessionSchema>;
|
|
|
|
export class ChatScrollSessionStorage {
|
|
private constructor() {}
|
|
|
|
static setSnapshot(snapshot: ChatScrollSession): Promise<ResultT<void>> {
|
|
return SessionAsyncUtil.setJson(
|
|
StorageKeys.chatScrollSession,
|
|
snapshot,
|
|
ChatScrollSessionSchema,
|
|
);
|
|
}
|
|
|
|
static getSnapshot(): Promise<ResultT<ChatScrollSession | null>> {
|
|
return SessionAsyncUtil.getJson(
|
|
StorageKeys.chatScrollSession,
|
|
ChatScrollSessionSchema,
|
|
);
|
|
}
|
|
|
|
static clearSnapshot(): Promise<ResultT<void>> {
|
|
return SessionAsyncUtil.remove(StorageKeys.chatScrollSession);
|
|
}
|
|
|
|
static async consumeSnapshot(): Promise<ResultT<ChatScrollSession | null>> {
|
|
const result = await ChatScrollSessionStorage.getSnapshot();
|
|
const cleared = await ChatScrollSessionStorage.clearSnapshot();
|
|
if (Result.isErr(result)) return result;
|
|
if (Result.isErr(cleared)) return cleared;
|
|
return result;
|
|
}
|
|
}
|