Bluesky app fork with some witchin' additions 馃挮
1import {useMemo} from 'react'
2
3import {device, useStorage} from '#/storage'
4import {type SessionAccount} from './types'
5
6export type AccountSortOption =
7 | 'alphabetical'
8 | 'dateModified'
9 | 'dateAdded'
10 | 'custom'
11
12type SortableAccountItem = {
13 account: Pick<SessionAccount, 'handle' | 'addedAt' | 'lastActiveAt'>
14}
15
16function getSortableAccount(
17 item: SessionAccount | SortableAccountItem,
18): Pick<SessionAccount, 'handle' | 'addedAt' | 'lastActiveAt'> {
19 return 'account' in item ? item.account : item
20}
21
22export function sortAccountItems<
23 T extends SessionAccount | SortableAccountItem,
24>(accounts: T[], sortBy: AccountSortOption, reverse: boolean) {
25 const next = [...accounts]
26 if (sortBy === 'alphabetical') {
27 next.sort((a, b) =>
28 getSortableAccount(a).handle.localeCompare(
29 getSortableAccount(b).handle,
30 undefined,
31 {
32 sensitivity: 'base',
33 },
34 ),
35 )
36 } else if (sortBy === 'dateModified') {
37 next.sort((a, b) => {
38 const left = Date.parse(getSortableAccount(a).lastActiveAt ?? '') || 0
39 const right = Date.parse(getSortableAccount(b).lastActiveAt ?? '') || 0
40 return right - left
41 })
42 } else if (sortBy === 'dateAdded') {
43 next.sort((a, b) => {
44 const left = Date.parse(getSortableAccount(a).addedAt ?? '') || 0
45 const right = Date.parse(getSortableAccount(b).addedAt ?? '') || 0
46 return right - left
47 })
48 }
49 if (reverse) {
50 next.reverse()
51 }
52 return next
53}
54
55export function useAccountSwitcherSortSettings() {
56 const [storedSortBy, setStoredSortBy] = useStorage(device, [
57 'settingsAccountSwitcherSortBy',
58 ])
59 const [reverseAccounts = false, setReverseAccounts] = useStorage(device, [
60 'settingsAccountSwitcherReverse',
61 ])
62
63 return {
64 sortBy: storedSortBy ?? ('dateModified' as AccountSortOption),
65 setSortBy: setStoredSortBy,
66 reverse: reverseAccounts,
67 setReverse: setReverseAccounts,
68 }
69}
70
71export function useSortedAccountItems<
72 T extends SessionAccount | SortableAccountItem,
73>(accounts: T[]) {
74 const {sortBy, reverse} = useAccountSwitcherSortSettings()
75
76 return useMemo(
77 () => sortAccountItems(accounts, sortBy, reverse),
78 [accounts, sortBy, reverse],
79 )
80}