Skip to content

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

feat(mobile): add offline download settings (#3178)

Mohamed Bassemc589a3b5e46f
diff --git a/apps/mobile/app/dashboard/_layout.tsx b/apps/mobile/app/dashboard/_layout.tsx
index bc99ba3a..7acc330e 100644
--- a/apps/mobile/app/dashboard/_layout.tsx
+++ b/apps/mobile/app/dashboard/_layout.tsx
@@ -313,6 +313,24 @@ export default function Dashboard() {
headerBackTitle: "Back",
}}
/>
+ <Stack.Screen
+ name="settings/offline-lists"
+ options={{
+ ...settingsScreenOptions,
+ title: "Lists",
+ headerTitle: "Keep Lists Offline",
+ headerBackTitle: "Back",
+ }}
+ />
+ <Stack.Screen
+ name="settings/offline-articles"
+ options={{
+ ...settingsScreenOptions,
+ title: "Downloaded Articles",
+ headerTitle: "Downloaded Articles",
+ headerBackTitle: "Back",
+ }}
+ />
<Stack.Screen
name="settings/usage"
options={{
diff --git a/apps/mobile/app/dashboard/bookmarks/[slug]/manage_lists.tsx b/apps/mobile/app/dashboard/bookmarks/[slug]/manage_lists.tsx
index b4b86c05..fdf0e2d0 100644
--- a/apps/mobile/app/dashboard/bookmarks/[slug]/manage_lists.tsx
+++ b/apps/mobile/app/dashboard/bookmarks/[slug]/manage_lists.tsx
@@ -1,6 +1,7 @@
import { Pressable, ScrollView } from "react-native";
import { Link, Stack, useLocalSearchParams } from "expo-router";
import {
+ byListPathName,
ListPicker,
listPathToPickerOption,
} from "@/components/lists/list-picker";
@@ -19,17 +20,6 @@ import {
} from "@karakeep/shared-react/hooks/lists";
import { useTRPC } from "@karakeep/shared-react/trpc";
-function byListPathName(a: ZBookmarkList[], b: ZBookmarkList[]) {
- const commonPathLength = Math.min(a.length, b.length);
-
- for (let index = 0; index < commonPathLength; index++) {
- const comparison = a[index].name.localeCompare(b[index].name);
- if (comparison !== 0) return comparison;
- }
-
- return a.length - b.length;
-}
-
const ListPickerPage = () => {
const headerHeight = useHeaderHeight();
const api = useTRPC();
diff --git a/apps/mobile/app/dashboard/settings/offline-articles.tsx b/apps/mobile/app/dashboard/settings/offline-articles.tsx
new file mode 100644
index 00000000..63dc22f1
--- /dev/null
+++ b/apps/mobile/app/dashboard/settings/offline-articles.tsx
@@ -0,0 +1,121 @@
+import { useEffect } from "react";
+import { Alert, Pressable, View } from "react-native";
+import { useRouter } from "expo-router";
+import { useHeaderHeight } from "expo-router/react-navigation";
+import EmptyState from "@/components/ui/EmptyState";
+import { Text } from "@/components/ui/Text";
+import { excludeFromOfflineDownloads } from "@/lib/offlineDownloadPrefs";
+import type { OfflineLibraryItem } from "@/lib/offlineLibrary";
+import {
+ getOfflineLibraryScope,
+ reconcileOfflineLibrary,
+ removeOfflineArticle,
+ useOfflineLibrary,
+} from "@/lib/offlineLibrary";
+import useAppSettings from "@/lib/settings";
+import { formatStorageSize } from "@/lib/storageSize";
+import { useColorScheme } from "@/lib/useColorScheme";
+import { FlashList } from "@shopify/flash-list";
+import { formatDistanceToNow } from "date-fns";
+import { BookOpen, Trash2 } from "lucide-react-native";
+
+function describe(item: OfflineLibraryItem) {
+ const parts = [
+ item.source === "manual" ? "Saved by you" : "Downloaded automatically",
+ formatDistanceToNow(item.savedAt, { addSuffix: true }),
+ ];
+ if (item.byteSize !== undefined) {
+ parts.push(formatStorageSize(item.byteSize));
+ }
+ return parts.join(" · ");
+}
+
+export default function OfflineArticles() {
+ const router = useRouter();
+ const headerHeight = useHeaderHeight();
+ const { settings } = useAppSettings();
+ const { colors } = useColorScheme();
+ const scope = getOfflineLibraryScope(settings);
+ const items = useOfflineLibrary(scope);
+
+ useEffect(() => {
+ reconcileOfflineLibrary(scope);
+ }, [scope]);
+
+ const confirmRemove = (item: OfflineLibraryItem) => {
+ Alert.alert(
+ "Remove offline copy?",
+ `"${item.displayTitle}" will be removed from this device and skipped by automatic downloads.`,
+ [
+ { text: "Cancel", style: "cancel" },
+ {
+ text: "Remove",
+ style: "destructive",
+ onPress: () => {
+ excludeFromOfflineDownloads(scope, item.bookmarkId);
+ removeOfflineArticle(scope, item.bookmarkId);
+ },
+ },
+ ],
+ );
+ };
+
+ return (
+ <FlashList
+ contentInsetAdjustmentBehavior="automatic"
+ contentContainerStyle={{
+ paddingBottom: 40 + headerHeight,
+ paddingHorizontal: 16,
+ paddingTop: 12,
+ }}
+ data={items}
+ keyExtractor={(item) => item.bookmarkId}
+ ItemSeparatorComponent={() => <View className="h-2" />}
+ ListEmptyComponent={
+ <EmptyState
+ icon={BookOpen}
+ title="No downloaded articles"
+ subtitle="Turn on automatic downloads, or open an article and make it available offline."
+ />
+ }
+ renderItem={({ item }) => (
+ <View
+ className="flex-row items-center rounded-xl bg-card px-4 py-3"
+ style={{ borderCurve: "continuous" }}
+ >
+ <Pressable
+ accessibilityRole="button"
+ className="min-w-0 flex-1 active:opacity-70"
+ onPress={() =>
+ router.push(`/dashboard/bookmarks/${item.bookmarkId}`)
+ }
+ >
+ <Text className="font-medium" numberOfLines={2}>
+ {item.displayTitle}
+ </Text>
+ {item.url ? (
+ <Text
+ className="mt-0.5 text-xs text-muted-foreground"
+ numberOfLines={1}
+ >
+ {item.url}
+ </Text>
+ ) : null}
+ <Text className="mt-1 text-xs text-muted-foreground">
+ {describe(item)}
+ </Text>
+ </Pressable>
+ <Pressable
+ accessibilityLabel={`Remove ${item.displayTitle} offline copy`}
+ accessibilityRole="button"
+ className="ml-3 p-2"
+ hitSlop={8}
+ onPress={() => confirmRemove(item)}
+ >
+ <Trash2 size={18} color={colors.destructive} />
+ </Pressable>
+ </View>
+ )}
+ />
+ );
+}
diff --git a/apps/mobile/app/dashboard/settings/offline-lists.tsx b/apps/mobile/app/dashboard/settings/offline-lists.tsx
new file mode 100644
index 00000000..f8669b69
--- /dev/null
+++ b/apps/mobile/app/dashboard/settings/offline-lists.tsx
@@ -0,0 +1,58 @@
+import { useMemo } from "react";
+import type { ListPickerOption } from "@/components/lists/list-picker";
+import {
+ byListPathName,
+ ListPicker,
+ listPathToPickerOption,
+} from "@/components/lists/list-picker";
+import QueryPageState from "@/components/QueryPageState";
+import { SettingsScreen } from "@/components/settings/settings-list";
+import { Text } from "@/components/ui/Text";
+import {
+ setListKeptOffline,
+ useOfflineDownloadPrefs,
+} from "@/lib/offlineDownloadPrefs";
+import { getOfflineLibraryScope } from "@/lib/offlineLibrary";
+import useAppSettings from "@/lib/settings";
+
+import { useBookmarkLists } from "@karakeep/shared-react/hooks/lists";
+
+export default function OfflineLists() {
+ const { settings } = useAppSettings();
+ const scope = getOfflineLibraryScope(settings);
+ const prefs = useOfflineDownloadPrefs(scope);
+ const { data, error, refetch } = useBookmarkLists();
+
+ const options = useMemo(() => {
+ const selected = new Set(prefs.listIds);
+ return [...(data?.allPaths ?? [])]
+ .sort(byListPathName)
+ .map((path): ListPickerOption => {
+ const option = listPathToPickerOption(path);
+ return {
+ ...option,
+ state: selected.has(option.id) ? "selected" : undefined,
+ };
+ });
+ }, [data?.allPaths, prefs.listIds]);
+
+ if (!data) {
+ return <QueryPageState error={error} onRetry={() => refetch()} />;
+ }
+
+ return (
+ <SettingsScreen>
+ <Text className="px-1 text-sm text-muted-foreground">
+ Articles in these lists are downloaded, including ones added later.
+ Nested lists have to be selected separately.
+ </Text>
+ <ListPicker
+ emptyMessage="You don't have any lists yet"
+ onSelect={(listId) =>
+ setListKeptOffline(scope, listId, !prefs.listIds.includes(listId))
+ }
+ options={options}
+ />
+ </SettingsScreen>
+ );
+}
diff --git a/apps/mobile/app/dashboard/settings/offline.tsx b/apps/mobile/app/dashboard/settings/offline.tsx
index 1201bfdf..efcf618e 100644
--- a/apps/mobile/app/dashboard/settings/offline.tsx
+++ b/apps/mobile/app/dashboard/settings/offline.tsx
@@ -1,59 +1,129 @@
-import { useEffect } from "react";
-import { Alert, Pressable, View } from "react-native";
+import { Alert, View } from "react-native";
import { useRouter } from "expo-router";
import {
SettingsActionRow,
SettingsGroup,
+ SettingsMenuRow,
+ SettingsNavigationRow,
SettingsScreen,
SettingsSeparator,
+ SettingsToggleRow,
} from "@/components/settings/settings-list";
-import EmptyState from "@/components/ui/EmptyState";
import { Text } from "@/components/ui/Text";
import { useToast } from "@/components/ui/Toast";
import { clearPersistedCache, usePersistedCacheSize } from "@/lib/offlineCache";
+import {
+ BUDGET_MB_OPTIONS,
+ isAutoDownloadEnabled,
+ RECENT_LIMIT_OPTIONS,
+ updateOfflineDownloadPrefs,
+ useOfflineDownloadPrefs,
+} from "@/lib/offlineDownloadPrefs";
import {
getOfflineLibraryScope,
- reconcileOfflineLibrary,
removeAllOfflineArticles,
- removeOfflineArticle,
useOfflineLibrary,
- useOfflineLibrarySize,
} from "@/lib/offlineLibrary";
+import type { OfflineSyncStatus } from "@/lib/offlineSync";
+import {
+ cancelOfflineDownloads,
+ refreshOfflineDownloads,
+ useOfflineSyncStatus,
+} from "@/lib/offlineSync";
import useAppSettings from "@/lib/settings";
-import { useColorScheme } from "@/lib/useColorScheme";
+import { formatStorageSize, megabytesToBytes } from "@/lib/storageSize";
import { useQueryClient } from "@tanstack/react-query";
import { formatDistanceToNow } from "date-fns";
-import { BookOpen, Trash2 } from "lucide-react-native";
-const storageSizeFormatter = new Intl.NumberFormat(undefined, {
- maximumFractionDigits: 1,
-});
+const RECENT_LIMIT_MENU = RECENT_LIMIT_OPTIONS.map((value) => ({
+ value,
+ label: `${value} articles`,
+}));
+
+const BUDGET_MENU = BUDGET_MB_OPTIONS.map((value) => ({
+ value,
+ label: formatStorageSize(megabytesToBytes(value)),
+}));
-function formatStorageSize(bytes: number) {
- if (bytes < 1024) {
- return `${bytes} B`;
+function pluralize(count: number, noun: string) {
+ return `${count} ${noun}${count === 1 ? "" : "s"}`;
+}
+
+function statusTitle(status: OfflineSyncStatus) {
+ switch (status.phase) {
+ case "checking":
+ return "Checking for new articles…";
+ case "downloading":
+ return "Downloading articles…";
+ case "wifi":
+ return "Waiting for Wi-Fi";
+ case "offline":
+ return "Waiting for a connection";
+ case "paused":
+ return "Paused";
+ case "error":
+ return "Couldn't check for new articles";
+ case "ready":
+ if (status.budgetReached) {
+ return "Storage limit reached";
+ }
+ return status.failed > 0 ? "Some articles are missing" : "Up to date";
+ case "idle":
+ case "disabled":
+ return "Not checked yet";
}
+}
- const units = ["KB", "MB", "GB"];
- let value = bytes / 1024;
- let unitIndex = 0;
- while (value >= 1024 && unitIndex < units.length - 1) {
- value /= 1024;
- unitIndex += 1;
+function statusNotes(status: OfflineSyncStatus) {
+ const notes: string[] = [];
+ if (status.phase === "error") {
+ notes.push("Articles that were already downloaded are still available.");
}
+ if (status.failed > 0) {
+ notes.push(
+ `${pluralize(status.failed, "article")} couldn't be downloaded yet. Some may still be processing on the server.`,
+ );
+ }
+ if (status.budgetReached) {
+ notes.push(
+ "Raise the storage limit or keep fewer articles to download the rest.",
+ );
+ }
+ return notes;
+}
- return `${storageSizeFormatter.format(value)} ${units[unitIndex]}`;
+function DownloadProgress({ status }: { status: OfflineSyncStatus }) {
+ const fraction = status.total > 0 ? status.ready / status.total : 0;
+
+ return (
+ <View
+ accessibilityRole="progressbar"
+ accessibilityValue={{ min: 0, max: status.total, now: status.ready }}
+ className="h-1 overflow-hidden rounded-full bg-muted/30"
+ >
+ <View
+ className="h-full rounded-full bg-primary"
+ style={{ width: `${Math.round(fraction * 100)}%` }}
+ />
+ </View>
+ );
}
-function CacheSectionHeader({ title, size }: { title: string; size: number }) {
+function SectionHeader({ title, detail }: { title: string; detail?: string }) {
return (
- <View className="flex-row items-center justify-between px-1 pb-2">
- <Text className="text-xs uppercase tracking-wide text-muted-foreground">
+ <View className="flex-row items-center justify-between px-4">
+ <Text
+ variant="footnote"
+ color="tertiary"
+ className="uppercase tracking-wide"
+ >
{title}
</Text>
- <Text className="text-xs tabular-nums text-muted-foreground">
- {formatStorageSize(size)}
- </Text>
+ {detail ? (
+ <Text variant="footnote" color="tertiary" className="tabular-nums">
+ {detail}
+ </Text>
+ ) : null}
</View>
);
}
@@ -63,41 +133,38 @@ export default function OfflineContent() {
const queryClient = useQueryClient();
const { toast } = useToast();
const { settings } = useAppSettings();
- const { colors } = useColorScheme();
const scope = getOfflineLibraryScope(settings);
+ const prefs = useOfflineDownloadPrefs(scope);
+ const status = useOfflineSyncStatus(scope);
const offlineLibrary = useOfflineLibrary(scope);
- const offlineLibrarySize = useOfflineLibrarySize();
const recentCacheSize = usePersistedCacheSize();
- useEffect(() => {
- reconcileOfflineLibrary(scope);
- }, [scope]);
-
- const confirmRemove = (bookmarkId: string, displayTitle: string) => {
- Alert.alert(
- "Remove offline copy?",
- `"${displayTitle}" will no longer be kept for offline reading.`,
- [
- { text: "Cancel", style: "cancel" },
- {
- text: "Remove",
- style: "destructive",
- onPress: () => removeOfflineArticle(scope, bookmarkId),
- },
- ],
- );
- };
+ const usedBytes = offlineLibrary.reduce(
+ (sum, item) => sum + (item.byteSize ?? 0),
+ 0,
+ );
+ const autoEnabled = isAutoDownloadEnabled(prefs);
+ const isBusy = status.phase === "checking" || status.phase === "downloading";
const confirmRemoveAll = () => {
Alert.alert(
"Remove all offline content?",
- "This removes every article you explicitly saved for offline reading.",
+ "Every downloaded article is removed from this device, and automatic downloads are turned off.",
[
{ text: "Cancel", style: "cancel" },
{
text: "Remove All",
style: "destructive",
- onPress: () => removeAllOfflineArticles(scope),
+ onPress: () => {
+ cancelOfflineDownloads();
+ updateOfflineDownloadPrefs(scope, (current) => ({
+ ...current,
+ recentEnabled: false,
+ listIds: [],
+ excludedIds: [],
+ }));
+ removeAllOfflineArticles(scope);
+ },
},
],
);
@@ -106,7 +173,7 @@ export default function OfflineContent() {
const confirmClearRecentCache = () => {
Alert.alert(
"Clear recent cache?",
- "Saved offline articles will be kept. Anything else will be re-cached as you browse.",
+ "Downloaded articles are kept. Everything else will be cached again as you browse.",
[
{ text: "Cancel", style: "cancel" },
{
@@ -122,86 +189,153 @@ export default function OfflineContent() {
);
};
+ const notes = statusNotes(status);
+
return (
<SettingsScreen>
<Text className="px-1 text-sm text-muted-foreground">
- Saved offline articles stay on this device. Everything else is cached
- only as you browse and can be cleared at any time.
+ Keep articles on this device so you can read them without a connection.
</Text>
- <View className="gap-4">
- <View className="gap-2">
- <CacheSectionHeader
- title="Saved offline content"
- size={offlineLibrarySize}
- />
-
- {offlineLibrary.length === 0 ? (
- <EmptyState
- icon={BookOpen}
- title="No saved offline articles"
- subtitle="Open an article and choose Make available offline."
- />
- ) : (
- <SettingsGroup>
- {offlineLibrary.map((item, index) => (
- <View key={item.bookmarkId}>
- {index > 0 ? <SettingsSeparator /> : null}
- <View className="flex-row items-center px-4 py-3">
- <Pressable
- className="min-w-0 flex-1"
- onPress={() =>
- router.push(`/dashboard/bookmarks/${item.bookmarkId}`)
- }
- >
- <Text className="font-medium" numberOfLines={2}>
- {item.displayTitle}
- </Text>
- {item.url ? (
- <Text
- className="mt-0.5 text-xs text-muted-foreground"
- numberOfLines={1}
- >
- {item.url}
- </Text>
- ) : null}
- <Text className="mt-1 text-xs text-muted-foreground">
- Saved{" "}
- {formatDistanceToNow(item.savedAt, { addSuffix: true })}
- </Text>
- </Pressable>
- <Pressable
- accessibilityLabel={`Remove ${item.displayTitle} offline copy`}
- className="ml-3 p-2"
- onPress={() =>
- confirmRemove(item.bookmarkId, item.displayTitle)
- }
- >
- <Trash2 size={18} color={colors.destructive} />
- </Pressable>
- </View>
- </View>
- ))}
- </SettingsGroup>
- )}
- </View>
-
- {offlineLibrary.length > 0 ? (
- <SettingsGroup>
- <SettingsActionRow
- centered
- label="Remove all offline content"
- onPress={confirmRemoveAll}
+ <SettingsGroup
+ header="Automatic downloads"
+ footer="Recent articles keeps your newest unarchived articles, replacing the oldest as new ones arrive."
+ >
+ <SettingsToggleRow
+ label="Recent articles"
+ onValueChange={(recentEnabled) =>
+ updateOfflineDownloadPrefs(scope, (current) => ({
+ ...current,
+ recentEnabled,
+ }))
+ }
+ value={prefs.recentEnabled}
+ />
+ {prefs.recentEnabled ? (
+ <>
+ <SettingsSeparator />
+ <SettingsMenuRow
+ label="Keep"
+ onSelect={(recentLimit) =>
+ updateOfflineDownloadPrefs(scope, (current) => ({
+ ...current,
+ recentLimit,
+ }))
+ }
+ options={RECENT_LIMIT_MENU}
+ value={prefs.recentLimit}
/>
- </SettingsGroup>
+ </>
) : null}
+ <SettingsSeparator />
+ <SettingsNavigationRow
+ label="Lists"
+ onPress={() => router.push("/dashboard/settings/offline-lists")}
+ value={
+ prefs.listIds.length > 0
+ ? `${prefs.listIds.length} selected`
+ : "None"
+ }
+ />
+ </SettingsGroup>
+
+ <SettingsGroup
+ header="Storage & network"
+ footer="Lists take priority over recent articles when space runs out. Articles you save yourself are never removed automatically."
+ >
+ <SettingsMenuRow
+ label="Storage limit"
+ onSelect={(budgetMb) =>
+ updateOfflineDownloadPrefs(scope, (current) => ({
+ ...current,
+ budgetMb,
+ }))
+ }
+ options={BUDGET_MENU}
+ value={prefs.budgetMb}
+ />
+ <SettingsSeparator />
+ <SettingsToggleRow
+ label="Download only on Wi-Fi"
+ onValueChange={(wifiOnly) =>
+ updateOfflineDownloadPrefs(scope, (current) => ({
+ ...current,
+ wifiOnly,
+ }))
+ }
+ value={prefs.wifiOnly}
+ />
+ </SettingsGroup>
+
+ {autoEnabled ? (
+ <SettingsGroup
+ header="Status"
+ footer="Articles download while the app is open. Open it before going offline to be sure you have the latest."
+ >
+ <View className="gap-2 px-4 py-2">
+ <View className="flex-row items-center justify-between gap-3">
+ <Text className="flex-1 font-medium">{statusTitle(status)}</Text>
+ {status.total > 0 ? (
+ <Text color="tertiary" className="tabular-nums">
+ {status.ready} / {status.total}
+ </Text>
+ ) : null}
+ </View>
+ {status.total > 0 ? <DownloadProgress status={status} /> : null}
+ <Text variant="footnote" color="tertiary">
+ {formatStorageSize(usedBytes)} of{" "}
+ {formatStorageSize(megabytesToBytes(prefs.budgetMb))} used
+ {status.lastCheckedAt !== undefined
+ ? ` · Checked ${formatDistanceToNow(status.lastCheckedAt, { addSuffix: true })}`
+ : ""}
+ </Text>
+ {notes.map((note) => (
+ <Text key={note} variant="footnote" color="tertiary">
+ {note}
+ </Text>
+ ))}
+ </View>
+ <SettingsSeparator />
+ <SettingsActionRow
+ disabled={isBusy}
+ isLoading={isBusy}
+ label="Download now"
+ onPress={() => void refreshOfflineDownloads({ force: true })}
+ tone="primary"
+ />
+ </SettingsGroup>
+ ) : null}
+
+ <View className="gap-1.5">
+ <SectionHeader
+ title="On this device"
+ detail={formatStorageSize(usedBytes)}
+ />
+ <SettingsGroup footer="Downloads include the article text and its images. Videos, PDFs and other attachments aren't downloaded.">
+ <SettingsNavigationRow
+ label="Downloaded articles"
+ onPress={() => router.push("/dashboard/settings/offline-articles")}
+ value={String(offlineLibrary.length)}
+ />
+ {offlineLibrary.length > 0 || autoEnabled ? (
+ <>
+ <SettingsSeparator />
+ <SettingsActionRow
+ label="Remove all offline content"
+ onPress={confirmRemoveAll}
+ />
+ </>
+ ) : null}
+ </SettingsGroup>
</View>
- <View className="gap-2">
- <CacheSectionHeader title="Recent cache" size={recentCacheSize} />
+ <View className="gap-1.5">
+ <SectionHeader
+ title="Recent cache"
+ detail={formatStorageSize(recentCacheSize)}
+ />
<SettingsGroup>
<SettingsActionRow
- centered
label="Clear recent cache"
onPress={confirmClearRecentCache}
/>
diff --git a/apps/mobile/components/lists/list-picker.tsx b/apps/mobile/components/lists/list-picker.tsx
index 62fb2bf5..285e4100 100644
--- a/apps/mobile/components/lists/list-picker.tsx
+++ b/apps/mobile/components/lists/list-picker.tsx
@@ -22,6 +22,17 @@ export function listPathToPickerOption(
};
}
+export function byListPathName(a: ZBookmarkList[], b: ZBookmarkList[]) {
+ const commonPathLength = Math.min(a.length, b.length);
+
+ for (let index = 0; index < commonPathLength; index++) {
+ const comparison = a[index].name.localeCompare(b[index].name);
+ if (comparison !== 0) return comparison;
+ }
+
+ return a.length - b.length;
+}
+
export function ListPicker({
options,
onSelect,
diff --git a/apps/mobile/components/settings/settings-list.tsx b/apps/mobile/components/settings/settings-list.tsx
index 53368434..fa91178d 100644
--- a/apps/mobile/components/settings/settings-list.tsx
+++ b/apps/mobile/components/settings/settings-list.tsx
@@ -13,7 +13,8 @@ import ChevronRight from "@/components/ui/ChevronRight";
import { Text } from "@/components/ui/Text";
import { useColorScheme } from "@/lib/useColorScheme";
import { cn } from "@/lib/utils";
-import { Check } from "lucide-react-native";
+import { MenuView } from "@react-native-menu/menu";
+import { Check, ChevronsUpDown } from "lucide-react-native";
function SettingsScreen({
children,
@@ -154,6 +155,57 @@ function SettingsToggleRow({
);
}
+function SettingsMenuRow<T extends string | number>({
+ label,
+ onSelect,
+ options,
+ value,
+}: {
+ label: string;
+ onSelect: (value: T) => void;
+ options: readonly { label: string; value: T }[];
+ value: T;
+}) {
+ const { colors } = useColorScheme();
+ const selected = options.find((option) => option.value === value);
+
+ return (
+ <MenuView
+ actions={options.map((option) => ({
+ id: String(option.value),
+ title: option.label,
+ state: option.value === value ? "on" : "off",
+ }))}
+ onPressAction={({ nativeEvent }) => {
+ const option = options.find(
+ (candidate) => String(candidate.value) === nativeEvent.event,
+ );
+ if (option) {
+ onSelect(option.value);
+ }
+ }}
+ shouldOpenOnLongPress={false}
+ >
+ <View
+ accessible
+ accessibilityLabel={`${label}: ${selected?.label ?? ""}`}
+ accessibilityRole="button"
+ className="min-h-10 flex-row items-center px-4 py-1"
+ >
+ <Text className="mr-3 flex-1" numberOfLines={1}>
+ {label}
+ </Text>
+ {selected ? (
+ <Text color="tertiary" className="mr-1.5" numberOfLines={1}>
+ {selected.label}
+ </Text>
+ ) : null}
+ <ChevronsUpDown color={colors.grey} size={15} strokeWidth={2.25} />
+ </View>
+ </MenuView>
+ );
+}
+
function SettingsChoiceRow({
description,
disabled = false,
@@ -267,6 +319,7 @@ export {
SettingsActionRow,
SettingsChoiceRow,
SettingsGroup,
+ SettingsMenuRow,
SettingsNavigationRow,
SettingsScreen,
SettingsSeparator,
diff --git a/apps/mobile/lib/offlineLibrary.ts b/apps/mobile/lib/offlineLibrary.ts
index 7c95b3a9..4fd86613 100644
--- a/apps/mobile/lib/offlineLibrary.ts
+++ b/apps/mobile/lib/offlineLibrary.ts
@@ -1,4 +1,4 @@
-import { useMemo, useSyncExternalStore } from "react";
+import { useMemo } from "react";
import { createMMKV, useMMKVString } from "react-native-mmkv";
import superjson from "superjson";
import { z } from "zod";
@@ -399,25 +399,6 @@ export function clearOfflineLibrary() {
scheduleTrim();
}
-function subscribeToOfflineLibrary(onStoreChange: () => void) {
- const listener = offlineLibraryStorage.addOnValueChangedListener(() => {
- onStoreChange();
- });
- return () => listener.remove();
-}
-
-function getOfflineLibrarySize() {
- return offlineLibraryStorage.byteSize;
-}
-
-export function useOfflineLibrarySize() {
- return useSyncExternalStore(
- subscribeToOfflineLibrary,
- getOfflineLibrarySize,
- getOfflineLibrarySize,
- );
-}
-
export function getOfflineLibraryItems(scope: string) {
return parseManifestMemoized(
offlineLibraryStorage.getString(manifestKey(scope)),
diff --git a/apps/mobile/lib/storageSize.ts b/apps/mobile/lib/storageSize.ts
index 01b0ad9f..c4724bd9 100644
--- a/apps/mobile/lib/storageSize.ts
+++ b/apps/mobile/lib/storageSize.ts
@@ -1,3 +1,23 @@
+const storageSizeFormatter = new Intl.NumberFormat(undefined, {
+ maximumFractionDigits: 1,
+});
+
+export function formatStorageSize(bytes: number) {
+ if (bytes < 1024) {
+ return `${bytes} B`;
+ }
+
+ const units = ["KB", "MB", "GB"];
+ let value = bytes / 1024;
+ let unitIndex = 0;
+ while (value >= 1024 && unitIndex < units.length - 1) {
+ value /= 1024;
+ unitIndex += 1;
+ }
+
+ return `${storageSizeFormatter.format(value)} ${units[unitIndex]}`;
+}
+
export function megabytesToBytes(megabytes: number) {
return megabytes * 1024 * 1024;
}