-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbranch.ts
41 lines (35 loc) · 1.5 KB
/
branch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { LocalStorage } from "@raycast/api";
import { useCachedState } from "@raycast/utils";
import { useEffect } from "react";
import { BranchDetailsFragment, ExtendedRepositoryFieldsFragment } from "../generated/graphql";
const VISITED_BRANCH_KEY = "VISITED_BRANCHES";
const VISITED_BRANCH_LENGTH = 10;
// History was stored in `LocalStorage` before, after migration it's stored in `Cache`
async function loadVisitedBranches() {
const item = await LocalStorage.getItem<string>(VISITED_BRANCH_KEY);
if (item) {
const parsed = JSON.parse(item).slice(0, VISITED_BRANCH_LENGTH);
return parsed as BranchDetailsFragment[];
} else {
return [];
}
}
export function useBranchHistory() {
const [history, setHistory] = useCachedState<BranchDetailsFragment[]>("BranchHistory", []);
const [migratedHistory, setMigratedHistory] = useCachedState<boolean>("migratedBranchHistory", false);
useEffect(() => {
if (!migratedHistory) {
loadVisitedBranches().then((branches) => {
setHistory(branches);
setMigratedHistory(true);
});
}
}, [migratedHistory]);
function visitBranch(branch: BranchDetailsFragment, repository: ExtendedRepositoryFieldsFragment) {
const visitedBranch = [branch, ...(history?.filter((item) => item.branchName !== branch.branchName) ?? [])];
LocalStorage.setItem(VISITED_BRANCH_KEY, JSON.stringify(visitedBranch));
const nextBranch = visitedBranch.slice(0, VISITED_BRANCH_LENGTH);
setHistory(nextBranch);
}
return { history, visitBranch };
}