Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usePullRequestReviewDraft.ts

111 lines4.0 KB

1import { useAtomValue } from "@effect/atom-react";
2import { msg } from "gt-react-native";
3import { useEffect } from "react";
4import { AppState } from "react-native";
5import * as Atom from "effect/reactivity/Atom";
6import * as Schema from "effect/Schema";
7import { appAtomRegistry } from "../../state/atom-registry";
8import { writeFileAtomically } from "../../lib/atomic-file";
9import { SerializedAsyncQueue } from "../../lib/serialized-async-queue";
10import {
11 EMPTY_REVIEW_DRAFT,
12 ReviewDraftDocument,
13 pullRequestReviewKey,
14 type ReviewDraft,
15} from "./pullRequestReviewDrafts";
16import type { PullRequestParams } from "./usePullRequestDiff";
17import { m } from "../../i18n/messages";
18​
19const state = Atom.make<{
20 drafts: Record<string, ReviewDraft>;
21 ready: boolean;
22 error: string | null;
23}>({ drafts: {}, ready: false, error: null }).pipe(Atom.keepAlive);
24const decodeDocument = Schema.decodeUnknownSync(ReviewDraftDocument);
25const queue = new SerializedAsyncQueue();
26let loading: Promise<void> | null = null;
27let timer: ReturnType<typeof setTimeout> | null = null;
28let savedDrafts: Record<string, ReviewDraft> | null = null;
29async function draftFile() {
30 const { Directory, File, Paths } = await import("expo-file-system");
31 const directory = new Directory(Paths.document, "pull-request-drafts");
32 directory.create({ idempotent: true, intermediates: true });
33 return new File(directory, "drafts.json");
35function load() {
36 if (loading) return loading;
37 loading = (async () => {
38 try {
39 const file = await draftFile();
40 const drafts = file.exists ? decodeDocument(JSON.parse(await file.text())).drafts : {};
41 savedDrafts = drafts;
42 appAtomRegistry.set(state, { drafts, ready: true, error: null });
43 } catch {
44 appAtomRegistry.set(state, {
45 ...appAtomRegistry.get(state),
46 error: m(msg("Could not restore review drafts. Reopen this screen to retry.")),
47 });
48 loading = null;
49 }
50 })();
51 return loading;
53async function persist() {
54 if (timer) clearTimeout(timer);
55 timer = null;
56 return queue.run(async () => {
57 const current = appAtomRegistry.get(state);
58 if (!current.ready) return false;
59 if (current.drafts === savedDrafts) return true;
60 try {
61 const drafts = Object.fromEntries(
62 Object.entries(current.drafts).filter(
63 ([, draft]) => draft.summary || draft.comment || draft.comments.length,
64 ),
65 );
66 await writeFileAtomically(await draftFile(), JSON.stringify({ version: 1, drafts }));
67 savedDrafts = current.drafts;
68 if (appAtomRegistry.get(state).error)
69 appAtomRegistry.set(state, { ...appAtomRegistry.get(state), error: null });
70 return true;
71 } catch {
72 appAtomRegistry.set(state, {
73 ...appAtomRegistry.get(state),
74 error: m(msg("Drafts are kept in this session, but could not be saved on this device.")),
75 });
76 return false;
77 }
78 });
80export function usePullRequestReviewDraft(params: PullRequestParams) {
81 const snapshot = useAtomValue(state);
82 const key = pullRequestReviewKey(params);
83 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- loads review drafts from disk and persists them when AppState leaves active and on unmount
84 useEffect(() => {
85 void load();
86 const listener = AppState.addEventListener("change", (phase) => {
87 if (phase !== "active") void persist();
88 });
89 return () => {
90 listener.remove();
91 void persist();
92 };
93 }, []);
94 const update = (transform: (current: ReviewDraft) => ReviewDraft) => {
95 const current = appAtomRegistry.get(state);
96 if (!current.ready) return;
97 appAtomRegistry.set(state, {
98 ...current,
99 drafts: { ...current.drafts, [key]: transform(current.drafts[key] ?? EMPTY_REVIEW_DRAFT) },
100 });
101 if (timer) clearTimeout(timer);
102 timer = setTimeout(() => void persist(), 200);
103 };
104 return {
105 draft: snapshot.drafts[key] ?? EMPTY_REVIEW_DRAFT,
106 ready: snapshot.ready,
107 error: snapshot.error,
108 update,
109 flush: persist,
110 };